File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.721: download - view: text, annotated - select for diffs
Thu Feb 13 18:13:22 2014 UTC (10 years, 2 months ago) by bisitz
Branches: MAIN
CVS tags: HEAD
Internationalization: Added missing &mt() calls

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.721 2014/02/13 18:13:22 bisitz 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: 	$answer =~ s-\n-<br />-g;
  410: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight(&HTML::Entities::encode($answer, '"<>&')).'</tt></blockquote>';
  411: 
  412:     } elsif ( $response eq 'organic') {
  413:         my $result=&mt('Smile representation: [_1]',
  414:                            '"<tt>'.&HTML::Entities::encode($answer, '"<>&').'</tt>"');
  415: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
  416: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
  417: 	return $result;
  418:     } elsif ( $response eq 'Task') {
  419: 	if ( $answer eq 'SUBMITTED') {
  420: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
  421: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
  422: 	    return $result;
  423: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
  424: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
  425: 			       keys(%{$record}));
  426: 	    return join('<br />',($version,@matches));
  427: 			       
  428: 			       
  429: 	} else {
  430: 	    my $result =
  431: 		'<p>'
  432: 		.&mt('Overall result: [_1]',
  433: 		     $record->{$version."resource.$respid.$partid.status"})
  434: 		.'</p>';
  435: 	    
  436: 	    $result .= '<ul>';
  437: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
  438: 			     keys(%{$record}));
  439: 	    foreach my $grade (sort(@grade)) {
  440: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
  441: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
  442: 				     $dim, $record->{$grade}).
  443: 			  '</li>';
  444: 	    }
  445: 	    $result.='</ul>';
  446: 	    return $result;
  447: 	}
  448:     } elsif ( $response =~ m/(?:numerical|formula|custom)/) {
  449:         # Respect multiple input fields, see Bug #5409
  450: 	$answer = 
  451: 	    &Apache::loncommon::format_previous_attempt_value('submission',
  452: 							      $answer);
  453: 	return $answer;
  454:     }
  455:     return &HTML::Entities::encode($answer, '"<>&');
  456: }
  457: 
  458: #-- A couple of common js functions
  459: sub commonJSfunctions {
  460:     my $request = shift;
  461:     $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
  462:     function radioSelection(radioButton) {
  463: 	var selection=null;
  464: 	if (radioButton.length > 1) {
  465: 	    for (var i=0; i<radioButton.length; i++) {
  466: 		if (radioButton[i].checked) {
  467: 		    return radioButton[i].value;
  468: 		}
  469: 	    }
  470: 	} else {
  471: 	    if (radioButton.checked) return radioButton.value;
  472: 	}
  473: 	return selection;
  474:     }
  475: 
  476:     function pullDownSelection(selectOne) {
  477: 	var selection="";
  478: 	if (selectOne.length > 1) {
  479: 	    for (var i=0; i<selectOne.length; i++) {
  480: 		if (selectOne[i].selected) {
  481: 		    return selectOne[i].value;
  482: 		}
  483: 	    }
  484: 	} else {
  485:             // only one value it must be the selected one
  486: 	    return selectOne.value;
  487: 	}
  488:     }
  489: COMMONJSFUNCTIONS
  490: }
  491: 
  492: #--- Dumps the class list with usernames,list of sections,
  493: #--- section, ids and fullnames for each user.
  494: sub getclasslist {
  495:     my ($getsec,$filterlist,$getgroup) = @_;
  496:     my @getsec;
  497:     my @getgroup;
  498:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  499:     if (!ref($getsec)) {
  500: 	if ($getsec ne '' && $getsec ne 'all') {
  501: 	    @getsec=($getsec);
  502: 	}
  503:     } else {
  504: 	@getsec=@{$getsec};
  505:     }
  506:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
  507:     if (!ref($getgroup)) {
  508: 	if ($getgroup ne '' && $getgroup ne 'all') {
  509: 	    @getgroup=($getgroup);
  510: 	}
  511:     } else {
  512: 	@getgroup=@{$getgroup};
  513:     }
  514:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
  515: 
  516:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
  517:     # Bail out if we were unable to get the classlist
  518:     return if (! defined($classlist));
  519:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
  520:     #
  521:     my %sections;
  522:     my %fullnames;
  523:     foreach my $student (keys(%$classlist)) {
  524:         my $end      = 
  525:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
  526:         my $start    = 
  527:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
  528:         my $id       = 
  529:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
  530:         my $section  = 
  531:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
  532:         my $fullname = 
  533:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
  534:         my $status   = 
  535:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
  536:         my $group   = 
  537:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
  538: 	# filter students according to status selected
  539: 	if ($filterlist && (!($stu_status =~ /Any/))) {
  540: 	    if (!($stu_status =~ $status)) {
  541: 		delete($classlist->{$student});
  542: 		next;
  543: 	    }
  544: 	}
  545: 	# filter students according to groups selected
  546: 	my @stu_groups = split(/,/,$group);
  547: 	if (@getgroup) {
  548: 	    my $exclude = 1;
  549: 	    foreach my $grp (@getgroup) {
  550: 	        foreach my $stu_group (@stu_groups) {
  551: 	            if ($stu_group eq $grp) {
  552: 	                $exclude = 0;
  553:     	            } 
  554: 	        }
  555:     	        if (($grp eq 'none') && !$group) {
  556:         	        $exclude = 0;
  557:         	}
  558: 	    }
  559: 	    if ($exclude) {
  560: 	        delete($classlist->{$student});
  561: 	    }
  562: 	}
  563: 	$section = ($section ne '' ? $section : 'none');
  564: 	if (&canview($section)) {
  565: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
  566: 		$sections{$section}++;
  567: 		if ($classlist->{$student}) {
  568: 		    $fullnames{$student}=$fullname;
  569: 		}
  570: 	    } else {
  571: 		delete($classlist->{$student});
  572: 	    }
  573: 	} else {
  574: 	    delete($classlist->{$student});
  575: 	}
  576:     }
  577:     my %seen = ();
  578:     my @sections = sort(keys(%sections));
  579:     return ($classlist,\@sections,\%fullnames);
  580: }
  581: 
  582: sub canmodify {
  583:     my ($sec)=@_;
  584:     if ($perm{'mgr'}) {
  585: 	if (!defined($perm{'mgr_section'})) {
  586: 	    # can modify whole class
  587: 	    return 1;
  588: 	} else {
  589: 	    if ($sec eq $perm{'mgr_section'}) {
  590: 		#can modify the requested section
  591: 		return 1;
  592: 	    } else {
  593: 		# can't modify the request section
  594: 		return 0;
  595: 	    }
  596: 	}
  597:     }
  598:     #can't modify
  599:     return 0;
  600: }
  601: 
  602: sub canview {
  603:     my ($sec)=@_;
  604:     if ($perm{'vgr'}) {
  605: 	if (!defined($perm{'vgr_section'})) {
  606: 	    # can modify whole class
  607: 	    return 1;
  608: 	} else {
  609: 	    if ($sec eq $perm{'vgr_section'}) {
  610: 		#can modify the requested section
  611: 		return 1;
  612: 	    } else {
  613: 		# can't modify the request section
  614: 		return 0;
  615: 	    }
  616: 	}
  617:     }
  618:     #can't modify
  619:     return 0;
  620: }
  621: 
  622: #--- Retrieve the grade status of a student for all the parts
  623: sub student_gradeStatus {
  624:     my ($symb,$udom,$uname,$partlist) = @_;
  625:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
  626:     my %partstatus = ();
  627:     foreach (@$partlist) {
  628: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
  629: 	$status              = 'nothing' if ($status eq '');
  630: 	$partstatus{$_}      = $status;
  631: 	my $subkey           = "resource.$_.submitted_by";
  632: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
  633:     }
  634:     return %partstatus;
  635: }
  636: 
  637: # hidden form and javascript that calls the form
  638: # Use by verifyscript and viewgrades
  639: # Shows a student's view of problem and submission
  640: sub jscriptNform {
  641:     my ($symb) = @_;
  642:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  643:     my $jscript= &Apache::lonhtmlcommon::scripttag(
  644: 	'    function viewOneStudent(user,domain) {'."\n".
  645: 	'	document.onestudent.student.value = user;'."\n".
  646: 	'	document.onestudent.userdom.value = domain;'."\n".
  647: 	'	document.onestudent.submit();'."\n".
  648: 	'    }'."\n".
  649: 	"\n");
  650:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
  651: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  652: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
  653: 	'<input type="hidden" name="command" value="submission" />'."\n".
  654: 	'<input type="hidden" name="student" value="" />'."\n".
  655: 	'<input type="hidden" name="userdom" value="" />'."\n".
  656: 	'</form>'."\n";
  657:     return $jscript;
  658: }
  659: 
  660: 
  661: 
  662: # Given the score (as a number [0-1] and the weight) what is the final
  663: # point value? This function will round to the nearest tenth, third,
  664: # or quarter if one of those is within the tolerance of .00001.
  665: sub compute_points {
  666:     my ($score, $weight) = @_;
  667:     
  668:     my $tolerance = .00001;
  669:     my $points = $score * $weight;
  670: 
  671:     # Check for nearness to 1/x.
  672:     my $check_for_nearness = sub {
  673:         my ($factor) = @_;
  674:         my $num = ($points * $factor) + $tolerance;
  675:         my $floored_num = floor($num);
  676:         if ($num - $floored_num < 2 * $tolerance * $factor) {
  677:             return $floored_num / $factor;
  678:         }
  679:         return $points;
  680:     };
  681: 
  682:     $points = $check_for_nearness->(10);
  683:     $points = $check_for_nearness->(3);
  684:     $points = $check_for_nearness->(4);
  685:     
  686:     return $points;
  687: }
  688: 
  689: #------------------ End of general use routines --------------------
  690: 
  691: #
  692: # Find most similar essay
  693: #
  694: 
  695: sub most_similar {
  696:     my ($uname,$udom,$symb,$uessay)=@_;
  697: 
  698:     unless ($symb) { return ''; }
  699: 
  700:     unless (ref($old_essays{$symb}) eq 'HASH') { return ''; }
  701: 
  702: # ignore spaces and punctuation
  703: 
  704:     $uessay=~s/\W+/ /gs;
  705: 
  706: # ignore empty submissions (occuring when only files are sent)
  707: 
  708:     unless ($uessay=~/\w+/s) { return ''; }
  709: 
  710: # these will be returned. Do not care if not at least 50 percent similar
  711:     my $limit=0.6;
  712:     my $sname='';
  713:     my $sdom='';
  714:     my $scrsid='';
  715:     my $sessay='';
  716: # go through all essays ...
  717:     foreach my $tkey (keys(%{$old_essays{$symb}})) {
  718: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
  719: # ... except the same student
  720:         next if (($tname eq $uname) && ($tdom eq $udom));
  721: 	my $tessay=$old_essays{$symb}{$tkey};
  722: 	$tessay=~s/\W+/ /gs;
  723: # String similarity gives up if not even limit
  724: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
  725: # Found one
  726: 	if ($tsimilar>$limit) {
  727: 	    $limit=$tsimilar;
  728: 	    $sname=$tname;
  729: 	    $sdom=$tdom;
  730: 	    $scrsid=$tcrsid;
  731: 	    $sessay=$old_essays{$symb}{$tkey};
  732: 	}
  733:     }
  734:     if ($limit>0.6) {
  735:        return ($sname,$sdom,$scrsid,$sessay,$limit);
  736:     } else {
  737:        return ('','','','',0);
  738:     }
  739: }
  740: 
  741: #-------------------------------------------------------------------
  742: 
  743: #------------------------------------ Receipt Verification Routines
  744: #
  745: 
  746: sub initialverifyreceipt {
  747:    my ($request,$symb) = @_;
  748:    &commonJSfunctions($request);
  749:    return '<form name="gradingMenu" action=""><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
  750:         &Apache::lonnet::recprefix($env{'request.course.id'}).
  751:         '-<input type="text" name="receipt" size="4" />'.
  752:         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  753:         '<input type="hidden" name="command" value="verify" />'.
  754:         "</form>\n";
  755: }
  756: 
  757: #--- Check whether a receipt number is valid.---
  758: sub verifyreceipt {
  759:     my ($request,$symb)  = @_;
  760: 
  761:     my $courseid = $env{'request.course.id'};
  762:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
  763: 	$env{'form.receipt'};
  764:     $receipt     =~ s/[^\-\d]//g;
  765: 
  766:     my $title.=
  767: 	'<h3><span class="LC_info">'.
  768: 	&mt('Verifying Receipt Number [_1]',$receipt).
  769: 	'</span></h3>'."\n";
  770: 
  771:     my ($string,$contents,$matches) = ('','',0);
  772:     my (undef,undef,$fullname) = &getclasslist('all','0');
  773:     
  774:     my $receiptparts=0;
  775:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
  776: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
  777:     my $parts=['0'];
  778:     if ($receiptparts) {
  779:         my $res_error; 
  780:         ($parts)=&response_type($symb,\$res_error);
  781:         if ($res_error) {
  782:             return &navmap_errormsg();
  783:         } 
  784:     }
  785:     
  786:     my $header = 
  787: 	&Apache::loncommon::start_data_table().
  788: 	&Apache::loncommon::start_data_table_header_row().
  789: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
  790: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
  791: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
  792:     if ($receiptparts) {
  793: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
  794:     }
  795:     $header.=
  796: 	&Apache::loncommon::end_data_table_header_row();
  797: 
  798:     foreach (sort 
  799: 	     {
  800: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  801: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  802: 		 }
  803: 		 return $a cmp $b;
  804: 	     } (keys(%$fullname))) {
  805: 	my ($uname,$udom)=split(/\:/);
  806: 	foreach my $part (@$parts) {
  807: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
  808: 		$contents.=
  809: 		    &Apache::loncommon::start_data_table_row().
  810: 		    '<td>&nbsp;'."\n".
  811: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
  812: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
  813: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
  814: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
  815: 		if ($receiptparts) {
  816: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
  817: 		}
  818: 		$contents.= 
  819: 		    &Apache::loncommon::end_data_table_row()."\n";
  820: 		
  821: 		$matches++;
  822: 	    }
  823: 	}
  824:     }
  825:     if ($matches == 0) {
  826:         $string = $title
  827:                  .'<p class="LC_warning">'
  828:                  .&mt('No match found for the above receipt number.')
  829:                  .'</p>';
  830:     } else {
  831: 	$string = &jscriptNform($symb).$title.
  832: 	    '<p>'.
  833: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
  834: 	    '</p>'.
  835: 	    $header.
  836: 	    $contents.
  837: 	    &Apache::loncommon::end_data_table()."\n";
  838:     }
  839:     return $string;
  840: }
  841: 
  842: #--- This is called by a number of programs.
  843: #--- Called from the Grading Menu - View/Grade an individual student
  844: #--- Also called directly when one clicks on the subm button 
  845: #    on the problem page.
  846: sub listStudents {
  847:     my ($request,$symb,$submitonly) = @_;
  848: 
  849:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
  850:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
  851:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
  852:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
  853:     unless ($submitonly) {
  854:        $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
  855:     }
  856: 
  857:     my $result='';
  858:     my $res_error;
  859:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
  860: 
  861:     my %lt = &Apache::lonlocal::texthash (
  862: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
  863: 		'single'   => 'Please select the student before clicking on the Next button.',
  864: 	     );
  865:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
  866:     function checkSelect(checkBox) {
  867: 	var ctr=0;
  868: 	var sense="";
  869: 	if (checkBox.length > 1) {
  870: 	    for (var i=0; i<checkBox.length; i++) {
  871: 		if (checkBox[i].checked) {
  872: 		    ctr++;
  873: 		}
  874: 	    }
  875: 	    sense = '$lt{'multiple'}';
  876: 	} else {
  877: 	    if (checkBox.checked) {
  878: 		ctr = 1;
  879: 	    }
  880: 	    sense = '$lt{'single'}';
  881: 	}
  882: 	if (ctr == 0) {
  883: 	    alert(sense);
  884: 	    return false;
  885: 	}
  886: 	document.gradesub.submit();
  887:     }
  888: 
  889:     function reLoadList(formname) {
  890: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
  891: 	formname.command.value = 'submission';
  892: 	formname.submit();
  893:     }
  894: LISTJAVASCRIPT
  895: 
  896:     &commonJSfunctions($request);
  897:     $request->print($result);
  898: 
  899:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
  900: 	"\n";
  901: 	
  902:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
  903:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
  904:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
  905:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
  906:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
  907:                   .&Apache::lonhtmlcommon::row_closure();
  908:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
  909:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
  910:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
  911:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
  912:                   .&Apache::lonhtmlcommon::row_closure();
  913: 
  914:     my $submission_options;
  915:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  916:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
  917:     $env{'form.Status'} = $saveStatus;
  918:     $submission_options.=
  919:         '<span class="LC_nobreak">'.
  920:         '<label><input type="radio" name="lastSub" value="lastonly" /> '.
  921:         &mt('last submission').' </label></span>'."\n".
  922:         '<span class="LC_nobreak">'.
  923:         '<label><input type="radio" name="lastSub" value="last" /> '.
  924:         &mt('last submission with details').' </label></span>'."\n".
  925:         '<span class="LC_nobreak">'.
  926:         '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.
  927:         &mt('all submissions').'</label></span>'."\n".
  928:         '<span class="LC_nobreak">'.
  929:         '<label><input type="radio" name="lastSub" value="all" /> '.
  930:         &mt('all submissions with details').'</label></span>';
  931:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
  932:                   .$submission_options
  933:                   .&Apache::lonhtmlcommon::row_closure();
  934: 
  935:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
  936:                   .'<select name="increment">'
  937:                   .'<option value="1">'.&mt('Whole Points').'</option>'
  938:                   .'<option value=".5">'.&mt('Half Points').'</option>'
  939:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
  940:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
  941:                   .'</select>'
  942:                   .&Apache::lonhtmlcommon::row_closure();
  943: 
  944:     $gradeTable .= 
  945:         &build_section_inputs().
  946: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
  947: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  948: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
  949: 
  950:     if (exists($env{'form.Status'})) {
  951: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
  952:     } else {
  953:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
  954:                       .&Apache::lonhtmlcommon::StatusOptions(
  955:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
  956:                       .&Apache::lonhtmlcommon::row_closure();
  957:     }
  958: 
  959:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
  960:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
  961:                   .&Apache::lonhtmlcommon::row_closure(1)
  962:                   .&Apache::lonhtmlcommon::end_pick_box();
  963: 
  964:     $gradeTable .= '<p>'
  965:                   .&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"
  966:                   .'<input type="hidden" name="command" value="processGroup" />'
  967:                   .'</p>';
  968: 
  969: # checkall buttons
  970:     $gradeTable.=&check_script('gradesub', 'stuinfo');
  971:     $gradeTable.='<input type="button" '."\n".
  972:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
  973:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
  974:     $gradeTable.=&check_buttons();
  975:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
  976:     $gradeTable.= &Apache::loncommon::start_data_table().
  977: 	&Apache::loncommon::start_data_table_header_row();
  978:     my $loop = 0;
  979:     while ($loop < 2) {
  980: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
  981: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
  982: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
  983: 	    foreach my $part (sort(@$partlist)) {
  984: 		my $display_part=
  985: 		    &get_display_part((split(/_/,$part))[0],$symb);
  986: 		$gradeTable.=
  987: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
  988: 	    }
  989: 	} elsif ($submitonly eq 'queued') {
  990: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
  991: 	}
  992: 	$loop++;
  993: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
  994:     }
  995:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
  996: 
  997:     my $ctr = 0;
  998:     foreach my $student (sort 
  999: 			 {
 1000: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 1001: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 1002: 			     }
 1003: 			     return $a cmp $b;
 1004: 			 }
 1005: 			 (keys(%$fullname))) {
 1006: 	my ($uname,$udom) = split(/:/,$student);
 1007: 
 1008: 	my %status = ();
 1009: 
 1010: 	if ($submitonly eq 'queued') {
 1011: 	    my %queue_status = 
 1012: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 1013: 							$udom,$uname);
 1014: 	    next if (!defined($queue_status{'gradingqueue'}));
 1015: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
 1016: 	}
 1017: 
 1018: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1019: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
 1020: 	    my $submitted = 0;
 1021: 	    my $graded = 0;
 1022: 	    my $incorrect = 0;
 1023: 	    foreach (keys(%status)) {
 1024: 		$submitted = 1 if ($status{$_} ne 'nothing');
 1025: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
 1026: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
 1027: 		
 1028: 		my ($foo,$partid,$foo1) = split(/\./,$_);
 1029: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 1030: 		    $submitted = 0;
 1031: 		    my ($part)=split(/\./,$partid);
 1032: 		    $gradeTable.='<input type="hidden" name="'.
 1033: 			$student.':'.$part.':submitted_by" value="'.
 1034: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
 1035: 		}
 1036: 	    }
 1037: 	    
 1038: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 1039: 				     $submitonly eq 'incorrect' ||
 1040: 				     $submitonly eq 'graded'));
 1041: 	    next if (!$graded && ($submitonly eq 'graded'));
 1042: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 1043: 	}
 1044: 
 1045: 	$ctr++;
 1046: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
 1047:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
 1048: 	if ( $perm{'vgr'} eq 'F' ) {
 1049: 	    if ($ctr%2 ==1) {
 1050: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
 1051: 	    }
 1052: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
 1053:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
 1054:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
 1055: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
 1056: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
 1057: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
 1058: 
 1059: 	    if ($submitonly ne 'all') {
 1060: 		foreach (sort(keys(%status))) {
 1061: 		    next if ($_ =~ /^resource.*?submitted_by$/);
 1062: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
 1063: 		}
 1064: 	    }
 1065: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
 1066: 	    if ($ctr%2 ==0) {
 1067: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
 1068: 	    }
 1069: 	}
 1070:     }
 1071:     if ($ctr%2 ==1) {
 1072: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
 1073: 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1074: 		foreach (@$partlist) {
 1075: 		    $gradeTable.='<td>&nbsp;</td>';
 1076: 		}
 1077: 	    } elsif ($submitonly eq 'queued') {
 1078: 		$gradeTable.='<td>&nbsp;</td>';
 1079: 	    }
 1080: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
 1081:     }
 1082: 
 1083:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
 1084:         '<input type="button" '.
 1085:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
 1086:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
 1087:     if ($ctr == 0) {
 1088: 	my $num_students=(scalar(keys(%$fullname)));
 1089: 	if ($num_students eq 0) {
 1090: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
 1091: 	} else {
 1092: 	    my $submissions='submissions';
 1093: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
 1094: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
 1095: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
 1096: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
 1097: 		&mt('No '.$submissions.' found for this resource for any students. ([quant,_1,student] checked for '.$submissions.')',
 1098: 		    $num_students).
 1099: 		'</span><br />';
 1100: 	}
 1101:     } elsif ($ctr == 1) {
 1102: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
 1103:     }
 1104:     $request->print($gradeTable);
 1105:     return '';
 1106: }
 1107: 
 1108: #---- Called from the listStudents routine
 1109: 
 1110: sub check_script {
 1111:     my ($form, $type)=@_;
 1112:     my $chkallscript= &Apache::lonhtmlcommon::scripttag('
 1113:     function checkall() {
 1114:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1115:             ele = document.forms.'.$form.'.elements[i];
 1116:             if (ele.name == "'.$type.'") {
 1117:             document.forms.'.$form.'.elements[i].checked=true;
 1118:                                        }
 1119:         }
 1120:     }
 1121: 
 1122:     function checksec() {
 1123:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1124:             ele = document.forms.'.$form.'.elements[i];
 1125:            string = document.forms.'.$form.'.chksec.value;
 1126:            if
 1127:           (ele.value.indexOf(":::SECTION"+string)>0) {
 1128:               document.forms.'.$form.'.elements[i].checked=true;
 1129:             }
 1130:         }
 1131:     }
 1132: 
 1133: 
 1134:     function uncheckall() {
 1135:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1136:             ele = document.forms.'.$form.'.elements[i];
 1137:             if (ele.name == "'.$type.'") {
 1138:             document.forms.'.$form.'.elements[i].checked=false;
 1139:                                        }
 1140:         }
 1141:     }
 1142: 
 1143: '."\n");
 1144:     return $chkallscript;
 1145: }
 1146: 
 1147: sub check_buttons {
 1148:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
 1149:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
 1150:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
 1151:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
 1152:     return $buttons;
 1153: }
 1154: 
 1155: #     Displays the submissions for one student or a group of students
 1156: sub processGroup {
 1157:     my ($request,$symb)  = @_;
 1158:     my $ctr        = 0;
 1159:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1160:     my $total      = scalar(@stuchecked)-1;
 1161: 
 1162:     foreach my $student (@stuchecked) {
 1163: 	my ($uname,$udom,$fullname) = split(/:/,$student);
 1164: 	$env{'form.student'}        = $uname;
 1165: 	$env{'form.userdom'}        = $udom;
 1166: 	$env{'form.fullname'}       = $fullname;
 1167: 	&submission($request,$ctr,$total,$symb);
 1168: 	$ctr++;
 1169:     }
 1170:     return '';
 1171: }
 1172: 
 1173: #------------------------------------------------------------------------------------
 1174: #
 1175: #-------------------------- Next few routines handles grading by student, essentially
 1176: #                           handles essay response type problem/part
 1177: #
 1178: #--- Javascript to handle the submission page functionality ---
 1179: sub sub_page_js {
 1180:     my $request = shift;
 1181: 	    my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 1182:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1183:     function updateRadio(formname,id,weight) {
 1184: 	var gradeBox = formname["GD_BOX"+id];
 1185: 	var radioButton = formname["RADVAL"+id];
 1186: 	var oldpts = formname["oldpts"+id].value;
 1187: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
 1188: 	gradeBox.value = pts;
 1189: 	var resetbox = false;
 1190: 	if (isNaN(pts) || pts < 0) {
 1191: 	    alert("$alertmsg"+pts);
 1192: 	    for (var i=0; i<radioButton.length; i++) {
 1193: 		if (radioButton[i].checked) {
 1194: 		    gradeBox.value = i;
 1195: 		    resetbox = true;
 1196: 		}
 1197: 	    }
 1198: 	    if (!resetbox) {
 1199: 		formtextbox.value = "";
 1200: 	    }
 1201: 	    return;
 1202: 	}
 1203: 
 1204: 	if (pts > weight) {
 1205: 	    var resp = confirm("You entered a value ("+pts+
 1206: 			       ") greater than the weight for the part. Accept?");
 1207: 	    if (resp == false) {
 1208: 		gradeBox.value = oldpts;
 1209: 		return;
 1210: 	    }
 1211: 	}
 1212: 
 1213: 	for (var i=0; i<radioButton.length; i++) {
 1214: 	    radioButton[i].checked=false;
 1215: 	    if (pts == i && pts != "") {
 1216: 		radioButton[i].checked=true;
 1217: 	    }
 1218: 	}
 1219: 	updateSelect(formname,id);
 1220: 	formname["stores"+id].value = "0";
 1221:     }
 1222: 
 1223:     function writeBox(formname,id,pts) {
 1224: 	var gradeBox = formname["GD_BOX"+id];
 1225: 	if (checkSolved(formname,id) == 'update') {
 1226: 	    gradeBox.value = pts;
 1227: 	} else {
 1228: 	    var oldpts = formname["oldpts"+id].value;
 1229: 	    gradeBox.value = oldpts;
 1230: 	    var radioButton = formname["RADVAL"+id];
 1231: 	    for (var i=0; i<radioButton.length; i++) {
 1232: 		radioButton[i].checked=false;
 1233: 		if (i == oldpts) {
 1234: 		    radioButton[i].checked=true;
 1235: 		}
 1236: 	    }
 1237: 	}
 1238: 	formname["stores"+id].value = "0";
 1239: 	updateSelect(formname,id);
 1240: 	return;
 1241:     }
 1242: 
 1243:     function clearRadBox(formname,id) {
 1244: 	if (checkSolved(formname,id) == 'noupdate') {
 1245: 	    updateSelect(formname,id);
 1246: 	    return;
 1247: 	}
 1248: 	gradeSelect = formname["GD_SEL"+id];
 1249: 	for (var i=0; i<gradeSelect.length; i++) {
 1250: 	    if (gradeSelect[i].selected) {
 1251: 		var selectx=i;
 1252: 	    }
 1253: 	}
 1254: 	var stores = formname["stores"+id];
 1255: 	if (selectx == stores.value) { return };
 1256: 	var gradeBox = formname["GD_BOX"+id];
 1257: 	gradeBox.value = "";
 1258: 	var radioButton = formname["RADVAL"+id];
 1259: 	for (var i=0; i<radioButton.length; i++) {
 1260: 	    radioButton[i].checked=false;
 1261: 	}
 1262: 	stores.value = selectx;
 1263:     }
 1264: 
 1265:     function checkSolved(formname,id) {
 1266: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
 1267: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
 1268: 	    if (!reply) {return "noupdate";}
 1269: 	    formname.overRideScore.value = 'yes';
 1270: 	}
 1271: 	return "update";
 1272:     }
 1273: 
 1274:     function updateSelect(formname,id) {
 1275: 	formname["GD_SEL"+id][0].selected = true;
 1276: 	return;
 1277:     }
 1278: 
 1279: //=========== Check that a point is assigned for all the parts  ============
 1280:     function checksubmit(formname,val,total,parttot) {
 1281: 	formname.gradeOpt.value = val;
 1282: 	if (val == "Save & Next") {
 1283: 	    for (i=0;i<=total;i++) {
 1284: 		for (j=0;j<parttot;j++) {
 1285: 		    var partid = formname["partid"+i+"_"+j].value;
 1286: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1287: 			var points = formname["GD_BOX"+i+"_"+partid].value;
 1288: 			if (points == "") {
 1289: 			    var name = formname["name"+i].value;
 1290: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
 1291: 			    var resp = confirm("You did not assign a score for "+studentID+
 1292: 					       ", part "+partid+". Continue?");
 1293: 			    if (resp == false) {
 1294: 				formname["GD_BOX"+i+"_"+partid].focus();
 1295: 				return false;
 1296: 			    }
 1297: 			}
 1298: 		    }
 1299: 		    
 1300: 		}
 1301: 	    }
 1302: 	    
 1303: 	}
 1304: 	formname.submit();
 1305:     }
 1306: 
 1307: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1308:     function checkSubmitPage(formname,total) {
 1309: 	noscore = new Array(100);
 1310: 	var ptr = 0;
 1311: 	for (i=1;i<total;i++) {
 1312: 	    var partid = formname["q_"+i].value;
 1313: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1314: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1315: 		var status = formname["solved"+i+"_"+partid].value;
 1316: 		if (points == "" && status != "correct_by_student") {
 1317: 		    noscore[ptr] = i;
 1318: 		    ptr++;
 1319: 		}
 1320: 	    }
 1321: 	}
 1322: 	if (ptr != 0) {
 1323: 	    var sense = ptr == 1 ? ": " : "s: ";
 1324: 	    var prolist = "";
 1325: 	    if (ptr == 1) {
 1326: 		prolist = noscore[0];
 1327: 	    } else {
 1328: 		var i = 0;
 1329: 		while (i < ptr-1) {
 1330: 		    prolist += noscore[i]+", ";
 1331: 		    i++;
 1332: 		}
 1333: 		prolist += "and "+noscore[i];
 1334: 	    }
 1335: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1336: 	    if (resp == false) {
 1337: 		return false;
 1338: 	    }
 1339: 	}
 1340: 
 1341: 	formname.submit();
 1342:     }
 1343: SUBJAVASCRIPT
 1344: }
 1345: 
 1346: #--- javascript for essay type problem --
 1347: sub sub_page_kw_js {
 1348:     my $request = shift;
 1349:     my $iconpath = $request->dir_config('lonIconsURL');
 1350:     &commonJSfunctions($request);
 1351: 
 1352:     my $inner_js_msg_central= (<<INNERJS);
 1353: <script type="text/javascript">
 1354:     function checkInput() {
 1355:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1356:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1357:       var usrctr = document.msgcenter.usrctr.value;
 1358:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1359:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1360: 
 1361:       var msgchk = "";
 1362:       if (document.msgcenter.subchk.checked) {
 1363:          msgchk = "msgsub,";
 1364:       }
 1365:       var includemsg = 0;
 1366:       for (var i=1; i<=nmsg; i++) {
 1367:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1368:           var frmmsg = document.msgcenter["msg"+i];
 1369:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1370:           var showflg = opener.document.SCORE["shownOnce"+i];
 1371:           showflg.value = "1";
 1372:           var chkbox = document.msgcenter["msgn"+i];
 1373:           if (chkbox.checked) {
 1374:              msgchk += "savemsg"+i+",";
 1375:              includemsg = 1;
 1376:           }
 1377:       }
 1378:       if (document.msgcenter.newmsgchk.checked) {
 1379:          msgchk += "newmsg"+usrctr;
 1380:          includemsg = 1;
 1381:       }
 1382:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1383:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1384:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1385:       includemsg.value = msgchk;
 1386: 
 1387:       self.close()
 1388: 
 1389:     }
 1390: </script>
 1391: INNERJS
 1392: 
 1393:     my $inner_js_highlight_central= (<<INNERJS);
 1394: <script type="text/javascript">
 1395:     function updateChoice(flag) {
 1396:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1397:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1398:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1399:       opener.document.SCORE.refresh.value = "on";
 1400:       if (opener.document.SCORE.keywords.value!=""){
 1401:          opener.document.SCORE.submit();
 1402:       }
 1403:       self.close()
 1404:     }
 1405: </script>
 1406: INNERJS
 1407: 
 1408:     my $start_page_msg_central = 
 1409:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1410: 				       {'js_ready'  => 1,
 1411: 					'only_body' => 1,
 1412: 					'bgcolor'   =>'#FFFFFF',});
 1413:     my $end_page_msg_central = 
 1414: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1415: 
 1416: 
 1417:     my $start_page_highlight_central = 
 1418:         &Apache::loncommon::start_page('Highlight Central',
 1419: 				       $inner_js_highlight_central,
 1420: 				       {'js_ready'  => 1,
 1421: 					'only_body' => 1,
 1422: 					'bgcolor'   =>'#FFFFFF',});
 1423:     my $end_page_highlight_central = 
 1424: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1425: 
 1426:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1427:     $docopen=~s/^document\.//;
 1428:     my %lt = &Apache::lonlocal::texthash(
 1429:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
 1430:                 plse => 'Please select a word or group of words from document and then click this link.',
 1431:                 adds => 'Add selection to keyword list? Edit if desired.',
 1432:                 comp => 'Compose Message for: ',
 1433:                 incl => 'Include',
 1434:                 type => 'Type',
 1435:                 subj => 'Subject',
 1436:                 mesa => 'Message',
 1437:                 new  => 'New',
 1438:                 save => 'Save',
 1439:                 canc => 'Cancel',
 1440:                 kehi => 'Keyword Highlight Options',
 1441:                 txtc => 'Text Color',
 1442:                 font => 'Font Size',
 1443:                 fnst => 'Font Style',
 1444:                 col1 => 'red',
 1445:                 col2 => 'green',
 1446:                 col3 => 'blue',
 1447:                 siz1 => 'normal',
 1448:                 siz2 => '+1',
 1449:                 siz3 => '+2',
 1450:                 sty1 => 'normal',
 1451:                 sty2 => 'italic',
 1452:                 sty3 => 'bold',
 1453:              );
 1454:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1455: 
 1456: //===================== Show list of keywords ====================
 1457:   function keywords(formname) {
 1458:     var nret = prompt("$lt{'keyw'}",formname.keywords.value);
 1459:     if (nret==null) return;
 1460:     formname.keywords.value = nret;
 1461: 
 1462:     if (formname.keywords.value != "") {
 1463: 	formname.refresh.value = "on";
 1464: 	formname.submit();
 1465:     }
 1466:     return;
 1467:   }
 1468: 
 1469: //===================== Script to view submitted by ==================
 1470:   function viewSubmitter(submitter) {
 1471:     document.SCORE.refresh.value = "on";
 1472:     document.SCORE.NCT.value = "1";
 1473:     document.SCORE.unamedom0.value = submitter;
 1474:     document.SCORE.submit();
 1475:     return;
 1476:   }
 1477: 
 1478: //===================== Script to add keyword(s) ==================
 1479:   function getSel() {
 1480:     if (document.getSelection) txt = document.getSelection();
 1481:     else if (document.selection) txt = document.selection.createRange().text;
 1482:     else return;
 1483:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1484:     if (cleantxt=="") {
 1485: 	alert("$lt{'plse'}");
 1486: 	return;
 1487:     }
 1488:     var nret = prompt("$lt{'adds'}",cleantxt);
 1489:     if (nret==null) return;
 1490:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1491:     if (document.SCORE.keywords.value != "") {
 1492: 	document.SCORE.refresh.value = "on";
 1493: 	document.SCORE.submit();
 1494:     }
 1495:     return;
 1496:   }
 1497: 
 1498: //====================== Script for composing message ==============
 1499:    // preload images
 1500:    img1 = new Image();
 1501:    img1.src = "$iconpath/mailbkgrd.gif";
 1502:    img2 = new Image();
 1503:    img2.src = "$iconpath/mailto.gif";
 1504: 
 1505:   function msgCenter(msgform,usrctr,fullname) {
 1506:     var Nmsg  = msgform.savemsgN.value;
 1507:     savedMsgHeader(Nmsg,usrctr,fullname);
 1508:     var subject = msgform.msgsub.value;
 1509:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1510:     re = /msgsub/;
 1511:     var shwsel = "";
 1512:     if (re.test(msgchk)) { shwsel = "checked" }
 1513:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1514:     displaySubject(checkEntities(subject),shwsel);
 1515:     for (var i=1; i<=Nmsg; i++) {
 1516: 	var testmsg = "savemsg"+i+",";
 1517: 	re = new RegExp(testmsg,"g");
 1518: 	shwsel = "";
 1519: 	if (re.test(msgchk)) { shwsel = "checked" }
 1520: 	var message = document.SCORE["savemsg"+i].value;
 1521: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1522: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1523: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1524:     }
 1525:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1526:     shwsel = "";
 1527:     re = /newmsg/;
 1528:     if (re.test(msgchk)) { shwsel = "checked" }
 1529:     newMsg(newmsg,shwsel);
 1530:     msgTail(); 
 1531:     return;
 1532:   }
 1533: 
 1534:   function checkEntities(strx) {
 1535:     if (strx.length == 0) return strx;
 1536:     var orgStr = ["&", "<", ">", '"']; 
 1537:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1538:     var counter = 0;
 1539:     while (counter < 4) {
 1540: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1541: 	counter++;
 1542:     }
 1543:     return strx;
 1544:   }
 1545: 
 1546:   function strReplace(strx, orgStr, newStr) {
 1547:     return strx.split(orgStr).join(newStr);
 1548:   }
 1549: 
 1550:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1551:     var height = 70*Nmsg+250;
 1552:     if (height > 600) {
 1553: 	height = 600;
 1554:     }
 1555:     var xpos = (screen.width-600)/2;
 1556:     xpos = (xpos < 0) ? '0' : xpos;
 1557:     var ypos = (screen.height-height)/2-30;
 1558:     ypos = (ypos < 0) ? '0' : ypos;
 1559: 
 1560:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
 1561:     pWin.focus();
 1562:     pDoc = pWin.document;
 1563:     pDoc.$docopen;
 1564:     pDoc.write('$start_page_msg_central');
 1565: 
 1566:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1567:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1568:     pDoc.write("<h1>&nbsp;$lt{'comp'}\"+fullname+\"<\\/h1>");
 1569: 
 1570:     pDoc.write('<table style="border:1px solid black;"><tr>');
 1571:     pDoc.write("<td><b>$lt{'incl'}<\\/b><\\/td><td><b>$lt{'type'}<\\/b><\\/td><td><b>$lt{'mesa'}<\\/td><\\/tr>");
 1572: }
 1573:     function displaySubject(msg,shwsel) {
 1574:     pDoc = pWin.document;
 1575:     pDoc.write("<tr>");
 1576:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1577:     pDoc.write("<td>$lt{'subj'}<\\/td>");
 1578:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"40\\" maxlength=\\"80\\"><\\/td><\\/tr>");
 1579: }
 1580: 
 1581:   function displaySavedMsg(ctr,msg,shwsel) {
 1582:     pDoc = pWin.document;
 1583:     pDoc.write("<tr>");
 1584:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1585:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
 1586:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
 1587: }
 1588: 
 1589:   function newMsg(newmsg,shwsel) {
 1590:     pDoc = pWin.document;
 1591:     pDoc.write("<tr>");
 1592:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1593:     pDoc.write("<td align=\\"center\\">$lt{'new'}<\\/td>");
 1594:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
 1595: }
 1596: 
 1597:   function msgTail() {
 1598:     pDoc = pWin.document;
 1599:     //pDoc.write("<\\/table>");
 1600:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1601:     pDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1602:     pDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
 1603:     pDoc.write("<\\/form>");
 1604:     pDoc.write('$end_page_msg_central');
 1605:     pDoc.close();
 1606: }
 1607: 
 1608: //====================== Script for keyword highlight options ==============
 1609:   function kwhighlight() {
 1610:     var kwclr    = document.SCORE.kwclr.value;
 1611:     var kwsize   = document.SCORE.kwsize.value;
 1612:     var kwstyle  = document.SCORE.kwstyle.value;
 1613:     var redsel = "";
 1614:     var grnsel = "";
 1615:     var blusel = "";
 1616:     var txtcol1 = "$lt{'col1'}";
 1617:     var txtcol2 = "$lt{'col2'}";
 1618:     var txtcol3 = "$lt{'col3'}";
 1619:     var txtsiz1 = "$lt{'siz1'}";
 1620:     var txtsiz2 = "$lt{'siz2'}";
 1621:     var txtsiz3 = "$lt{'siz3'}";
 1622:     var txtsty1 = "$lt{'sty1'}";
 1623:     var txtsty2 = "$lt{'sty2'}";
 1624:     var txtsty3 = "$lt{'sty3'}";
 1625:     if (kwclr=="red")   {var redsel="checked='checked'"};
 1626:     if (kwclr=="green") {var grnsel="checked='checked'"};
 1627:     if (kwclr=="blue")  {var blusel="checked='checked'"};
 1628:     var sznsel = "";
 1629:     var sz1sel = "";
 1630:     var sz2sel = "";
 1631:     if (kwsize=="0")  {var sznsel="checked='checked'"};
 1632:     if (kwsize=="+1") {var sz1sel="checked='checked'"};
 1633:     if (kwsize=="+2") {var sz2sel="checked='checked'"};
 1634:     var synsel = "";
 1635:     var syisel = "";
 1636:     var sybsel = "";
 1637:     if (kwstyle=="")    {var synsel="checked='checked'"};
 1638:     if (kwstyle=="<i>") {var syisel="checked='checked'"};
 1639:     if (kwstyle=="<b>") {var sybsel="checked='checked'"};
 1640:     highlightCentral();
 1641:     highlightbody('red',txtcol1,redsel,'0',txtsiz1,sznsel,'',txtsty1,synsel);
 1642:     highlightbody('green',txtcol2,grnsel,'+1',txtsiz2,sz1sel,'<i>',txtsty2,syisel);
 1643:     highlightbody('blue',txtcol3,blusel,'+2',txtsiz3,sz2sel,'<b>',txtsty3,sybsel);
 1644:     highlightend();
 1645:     return;
 1646:   }
 1647: 
 1648:   function highlightCentral() {
 1649: //    if (window.hwdWin) window.hwdWin.close();
 1650:     var xpos = (screen.width-400)/2;
 1651:     xpos = (xpos < 0) ? '0' : xpos;
 1652:     var ypos = (screen.height-330)/2-30;
 1653:     ypos = (ypos < 0) ? '0' : ypos;
 1654: 
 1655:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1656:     hwdWin.focus();
 1657:     var hDoc = hwdWin.document;
 1658:     hDoc.$docopen;
 1659:     hDoc.write('$start_page_highlight_central');
 1660:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1661:     hDoc.write("<h1>$lt{'kehi'}<\\/h1>");
 1662: 
 1663:     hDoc.write('<table border="0" width="100%"><tr style="background-color:#A1D676">');
 1664:     hDoc.write("<th>$lt{'txtc'}<\\/th><th>$lt{'font'}<\\/th><th>$lt{'fnst'}<\\/th><\\/tr>");
 1665:   }
 1666: 
 1667:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1668:     var hDoc = hwdWin.document;
 1669:     hDoc.write("<tr>");
 1670:     hDoc.write("<td align=\\"left\\">");
 1671:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+" \\/>&nbsp;"+clrtxt+"<\\/td>");
 1672:     hDoc.write("<td align=\\"left\\">");
 1673:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+" \\/>&nbsp;"+sztxt+"<\\/td>");
 1674:     hDoc.write("<td align=\\"left\\">");
 1675:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+" \\/>&nbsp;"+sytxt+"<\\/td>");
 1676:     hDoc.write("<\\/tr>");
 1677:   }
 1678: 
 1679:   function highlightend() { 
 1680:     var hDoc = hwdWin.document;
 1681:     hDoc.write("<\\/table><br \\/>");
 1682:     hDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\" \\/>&nbsp;&nbsp;");
 1683:     hDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\" \\/><br /><br />");
 1684:     hDoc.write("<\\/form>");
 1685:     hDoc.write('$end_page_highlight_central');
 1686:     hDoc.close();
 1687:   }
 1688: 
 1689: SUBJAVASCRIPT
 1690: }
 1691: 
 1692: sub get_increment {
 1693:     my $increment = $env{'form.increment'};
 1694:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1695:         $increment != .1) {
 1696:         $increment = 1;
 1697:     }
 1698:     return $increment;
 1699: }
 1700: 
 1701: sub gradeBox_start {
 1702:     return (
 1703:         &Apache::loncommon::start_data_table()
 1704:        .&Apache::loncommon::start_data_table_header_row()
 1705:        .'<th>'.&mt('Part').'</th>'
 1706:        .'<th>'.&mt('Points').'</th>'
 1707:        .'<th>&nbsp;</th>'
 1708:        .'<th>'.&mt('Assign Grade').'</th>'
 1709:        .'<th>'.&mt('Weight').'</th>'
 1710:        .'<th>'.&mt('Grade Status').'</th>'
 1711:        .&Apache::loncommon::end_data_table_header_row()
 1712:     );
 1713: }
 1714: 
 1715: sub gradeBox_end {
 1716:     return (
 1717:         &Apache::loncommon::end_data_table()
 1718:     );
 1719: }
 1720: #--- displays the grading box, used in essay type problem and grading by page/sequence
 1721: sub gradeBox {
 1722:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 1723:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1724: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 1725:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 1726:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
 1727:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
 1728:     $wgt       = ($wgt > 0 ? $wgt : '1');
 1729:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 1730: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 1731:     my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 1732:     my $display_part= &get_display_part($partid,$symb);
 1733:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 1734: 				       [$partid]);
 1735:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 1736:     if ($last_resets{$partid}) {
 1737:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 1738:     }
 1739:     my $result=&Apache::loncommon::start_data_table_row();
 1740:     my $ctr = 0;
 1741:     my $thisweight = 0;
 1742:     my $increment = &get_increment();
 1743: 
 1744:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 1745:     while ($thisweight<=$wgt) {
 1746: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 1747:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 1748: 	    $thisweight.')" value="'.$thisweight.'" '.
 1749: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 1750: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 1751:         $thisweight += $increment;
 1752: 	$ctr++;
 1753:     }
 1754:     $radio.='</tr></table>';
 1755: 
 1756:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 1757: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 1758: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 1759: 	$wgt.')" /></td>'."\n";
 1760:     $line.='<td>/'.$wgt.' '.$wgtmsg.
 1761: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 1762: 	' </td>'."\n";
 1763:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
 1764: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 1765:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 1766: 	$line.='<option></option>'.
 1767: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
 1768:     } else {
 1769: 	$line.='<option selected="selected"></option>'.
 1770: 	    '<option value="excused" >'.&mt('excused').'</option>';
 1771:     }
 1772:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
 1773: 
 1774: 
 1775:     $result .= 
 1776: 	    '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
 1777:     $result.=&Apache::loncommon::end_data_table_row();
 1778:     $result.=&Apache::loncommon::start_data_table_row().'<td colspan="6">';
 1779:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 1780: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 1781: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 1782: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 1783:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 1784:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 1785:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 1786:         $aggtries.'" />'."\n";
 1787:     my $res_error;
 1788:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
 1789:     $result.='</td>'.&Apache::loncommon::end_data_table_row();
 1790:     if ($res_error) {
 1791:         return &navmap_errormsg();
 1792:     }
 1793:     return $result;
 1794: }
 1795: 
 1796: sub handback_box {
 1797:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
 1798:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error_pointer);
 1799:     my (@respids);
 1800:     my @part_response_id = &flatten_responseType($responseType);
 1801:     foreach my $part_response_id (@part_response_id) {
 1802:     	my ($part,$resp) = @{ $part_response_id };
 1803:         if ($part eq $partid) {
 1804:             push(@respids,$resp);
 1805:         }
 1806:     }
 1807:     my $result;
 1808:     foreach my $respid (@respids) {
 1809: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 1810: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 1811: 	next if (!@$files);
 1812: 	my $file_counter = 0;
 1813: 	foreach my $file (@$files) {
 1814: 	    if ($file =~ /\/portfolio\//) {
 1815:                 $file_counter++;
 1816:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 1817:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
 1818:     	        $file_disp = "$name.$ext";
 1819:     	        $file = $file_path.$file_disp;
 1820:     	        $result.=&mt('Return commented version of [_1] to student.',
 1821:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 1822:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 1823:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
 1824: 	    }
 1825: 	}
 1826:         if ($file_counter) {
 1827:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
 1828:                        '<span class="LC_info">'.
 1829:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
 1830:         }
 1831:     }
 1832:     return $result;    
 1833: }
 1834: 
 1835: sub show_problem {
 1836:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 1837:     my $rendered;
 1838:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 1839:     &Apache::lonxml::remember_problem_counter();
 1840:     if ($mode eq 'both' or $mode eq 'text') {
 1841: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 1842: 						       $env{'request.course.id'},
 1843: 						       undef,\%form);
 1844:     }
 1845:     if ($removeform) {
 1846: 	$rendered=~s|<form(.*?)>||g;
 1847: 	$rendered=~s|</form>||g;
 1848: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 1849:     }
 1850:     my $companswer;
 1851:     if ($mode eq 'both' or $mode eq 'answer') {
 1852: 	&Apache::lonxml::restore_problem_counter();
 1853: 	$companswer=
 1854: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 1855: 						    $env{'request.course.id'},
 1856: 						    %form);
 1857:     }
 1858:     if ($removeform) {
 1859: 	$companswer=~s|<form(.*?)>||g;
 1860: 	$companswer=~s|</form>||g;
 1861: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 1862:     }
 1863:     my $renderheading = &mt('View of the problem');
 1864:     my $answerheading = &mt('Correct answer');
 1865:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 1866:         my $stu_fullname = $env{'form.fullname'};
 1867:         if ($stu_fullname eq '') {
 1868:             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
 1869:         }
 1870:         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
 1871:         if ($forwhom ne '') {
 1872:             $renderheading = &mt('View of the problem for[_1]',$forwhom);
 1873:             $answerheading = &mt('Correct answer for[_1]',$forwhom);
 1874:         }
 1875:     }
 1876:     $rendered=
 1877:         '<div class="LC_Box">'
 1878:        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
 1879:        .$rendered
 1880:        .'</div>';
 1881:     $companswer=
 1882:         '<div class="LC_Box">'
 1883:        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
 1884:        .$companswer
 1885:        .'</div>';
 1886:     my $result;
 1887:     if ($mode eq 'both') {
 1888:         $result=$rendered.$companswer;
 1889:     } elsif ($mode eq 'text') {
 1890:         $result=$rendered;
 1891:     } elsif ($mode eq 'answer') {
 1892:         $result=$companswer;
 1893:     }
 1894:     return $result;
 1895: }
 1896: 
 1897: sub files_exist {
 1898:     my ($r, $symb) = @_;
 1899:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1900: 
 1901:     foreach my $student (@students) {
 1902:         my ($uname,$udom,$fullname) = split(/:/,$student);
 1903:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 1904: 					      $udom,$uname);
 1905:         my ($string,$timestamp)= &get_last_submission(\%record);
 1906:         foreach my $submission (@$string) {
 1907:             my ($partid,$respid) =
 1908: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 1909:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 1910: 					   \%record);
 1911:             return 1 if (@$files);
 1912:         }
 1913:     }
 1914:     return 0;
 1915: }
 1916: 
 1917: sub download_all_link {
 1918:     my ($r,$symb) = @_;
 1919:     unless (&files_exist($r, $symb)) {
 1920:        $r->print(&mt('There are currently no submitted documents.'));
 1921:        return;
 1922:     }
 1923: 
 1924:     my $all_students = 
 1925: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 1926: 
 1927:     my $parts =
 1928: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 1929: 
 1930:     my $identifier = &Apache::loncommon::get_cgi_id();
 1931:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 1932:                              'cgi.'.$identifier.'.symb' => $symb,
 1933:                              'cgi.'.$identifier.'.parts' => $parts,});
 1934:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 1935: 	      &mt('Download All Submitted Documents').'</a>');
 1936:     return;
 1937: }
 1938: 
 1939: sub submit_download_link {
 1940:     my ($request,$symb) = @_;
 1941:     if (!$symb) { return ''; }
 1942: #FIXME: Figure out which type of problem this is and provide appropriate download
 1943:     &download_all_link($request,$symb);
 1944: }
 1945: 
 1946: sub build_section_inputs {
 1947:     my $section_inputs;
 1948:     if ($env{'form.section'} eq '') {
 1949:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 1950:     } else {
 1951:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 1952:         foreach my $section (@sections) {
 1953:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 1954:         }
 1955:     }
 1956:     return $section_inputs;
 1957: }
 1958: 
 1959: # --------------------------- show submissions of a student, option to grade 
 1960: sub submission {
 1961:     my ($request,$counter,$total,$symb) = @_;
 1962:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 1963:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 1964:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 1965:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 1966: 
 1967:     my $probtitle=&Apache::lonnet::gettitle($symb); 
 1968:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 1969: 
 1970:     if (!&canview($usec)) {
 1971:         $request->print(
 1972:             '<span class="LC_warning">'.
 1973:             &mt('Unable to view requested student.').
 1974:             ' '.&mt('([_1] in section [_2] in course id [_3])',
 1975:                         $uname.':'.$udom,$usec,$env{'request.course.id'}).
 1976:             '</span>');
 1977: 	return;
 1978:     }
 1979: 
 1980:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 1981:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 1982:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 1983:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 1984:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1985: 	'" src="'.$request->dir_config('lonIconsURL').
 1986: 	'/check.gif" height="16" border="0" />';
 1987: 
 1988:     # header info
 1989:     if ($counter == 0) {
 1990: 	&sub_page_js($request);
 1991: 	&sub_page_kw_js($request);
 1992: 
 1993: 	# option to display problem, only once else it cause problems 
 1994:         # with the form later since the problem has a form.
 1995: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 1996: 	    my $mode;
 1997: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 1998: 		$mode='both';
 1999: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 2000: 		$mode='text';
 2001: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 2002: 		$mode='answer';
 2003: 	    }
 2004: 	    &Apache::lonxml::clear_problem_counter();
 2005: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 2006: 	}
 2007: 
 2008: 	# kwclr is the only variable that is guaranteed not to be blank 
 2009:         # if this subroutine has been called once.
 2010: 	my %keyhash = ();
 2011: #	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
 2012:         if (1) {
 2013: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 2014: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 2015: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 2016: 
 2017: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2018: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 2019: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 2020: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 2021: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 2022: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
 2023: 		$keyhash{$symb.'_subject'} : $probtitle;
 2024: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 2025: 	}
 2026: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 2027: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 2028: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 2029: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 2030: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 2031: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 2032: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 2033: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 2034: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 2035: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 2036: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 2037: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 2038: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 2039: 			&build_section_inputs().
 2040: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 2041: 			'<input type="hidden" name="NCT"'.
 2042: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 2043: #	if ($env{'form.handgrade'} eq 'yes') {
 2044:         if (1) {
 2045: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 2046: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 2047: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 2048: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
 2049: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 2050: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 2051: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 2052: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
 2053: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
 2054: 	    }
 2055: 	}
 2056: 	
 2057: 	my ($cts,$prnmsg) = (1,'');
 2058: 	while ($cts <= $env{'form.savemsgN'}) {
 2059: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 2060: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 2061: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 2062: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 2063: 		'" />'."\n".
 2064: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 2065: 	    $cts++;
 2066: 	}
 2067: 	$request->print($prnmsg);
 2068: 
 2069: #	if ($env{'form.handgrade'} eq 'yes') {
 2070:         if (1) {
 2071: 
 2072:             my %lt = &Apache::lonlocal::texthash(
 2073:                           keyh => 'Keyword Highlighting for Essays',
 2074:                           keyw => 'Keyword Options',
 2075:                           list => 'List',
 2076:                           past => 'Paste Selection to List',
 2077:                           high => 'Highlight Attribute',
 2078:                      );    
 2079: #
 2080: # Print out the keyword options line
 2081: #
 2082: 	    $request->print(
 2083:                 '<div class="LC_columnSection">'
 2084:                .'<fieldset><legend>'.$lt{'keyh'}.'</legend>'
 2085:                .&Apache::lonhtmlcommon::funclist_from_array(
 2086:                     ['<a href="javascript:keywords(document.SCORE);" target="_self">'.$lt{'list'}.'</a>',
 2087:                      '<a href="#" onmousedown="javascript:getSel(); return false"
 2088:  class="page">'.$lt{'past'}.'</a>',
 2089:                      '<a href="javascript:kwhighlight();" target="_self">'.$lt{'high'}.'</a>'],
 2090:                     {legend => $lt{'keyw'}})
 2091:                .'</fieldset></div>'
 2092:             );
 2093: 
 2094: #
 2095: # Load the other essays for similarity check
 2096: #
 2097:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 2098: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 2099: 	    $apath=&escape($apath);
 2100: 	    $apath=~s/\W/\_/gs;
 2101:             &init_old_essays($symb,$apath,$adom,$aname);
 2102:         }
 2103:     }
 2104: 
 2105: # This is where output for one specific student would start
 2106:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
 2107:     $request->print(
 2108:         "\n\n"
 2109:        .'<div class="LC_grade_show_user'.$add_class.'">'
 2110:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
 2111:        ."\n"
 2112:     );
 2113: 
 2114:     # Show additional functions if allowed
 2115:     if ($perm{'vgr'}) {
 2116:         $request->print(
 2117:             &Apache::loncommon::track_student_link(
 2118:                 'View recent activity',
 2119:                 $uname,$udom,'check')
 2120:            .' '
 2121:         );
 2122:     }
 2123:     if ($perm{'opa'}) {
 2124:         $request->print(
 2125:             &Apache::loncommon::pprmlink(
 2126:                 &mt('Set/Change parameters'),
 2127:                 $uname,$udom,$symb,'check'));
 2128:     }
 2129: 
 2130:     # Show Problem
 2131:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2132: 	my $mode;
 2133: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2134: 	    $mode='both';
 2135: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2136: 	    $mode='text';
 2137: 	} elsif ($env{'form.vAns'} eq 'all') {
 2138: 	    $mode='answer';
 2139: 	}
 2140: 	&Apache::lonxml::clear_problem_counter();
 2141: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2142:     }
 2143: 
 2144:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2145:     my $res_error;
 2146:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2147:     if ($res_error) {
 2148:         $request->print(&navmap_errormsg());
 2149:         return;
 2150:     }
 2151: 
 2152:     # Display student info
 2153:     $request->print(($counter == 0 ? '' : '<br />'));
 2154: 
 2155:     my $result='<div class="LC_Box">'
 2156:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
 2157:     $result.='<input type="hidden" name="name'.$counter.
 2158:              '" value="'.$env{'form.fullname'}.'" />'."\n";
 2159: #    if ($env{'form.handgrade'} eq 'no') {
 2160:     if (1) {
 2161:         $result.='<p class="LC_info">'
 2162:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
 2163:                 ."</p>\n";
 2164:     }
 2165: 
 2166:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
 2167:     my $fullname;
 2168:     my $col_fullnames = [];
 2169: #    if ($env{'form.handgrade'} eq 'yes') {
 2170:     if (1) {
 2171: 	(my $sub_result,$fullname,$col_fullnames)=
 2172: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2173: 				 $counter);
 2174: 	$result.=$sub_result;
 2175:     }
 2176:     $request->print($result."\n");
 2177:     
 2178:     # print student answer/submission
 2179:     # Options are (1) Handgraded submission only
 2180:     #             (2) Last submission, includes submission that is not handgraded 
 2181:     #                  (for multi-response type part)
 2182:     #             (3) Last submission plus the parts info
 2183:     #             (4) The whole record for this student
 2184:     
 2185:     my ($string,$timestamp)= &get_last_submission(\%record);
 2186: 	
 2187:     my $lastsubonly;
 2188: 
 2189:     if ($$timestamp eq '') {
 2190:         $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
 2191:     } else {
 2192:         $lastsubonly =
 2193:             '<div class="LC_grade_submissions_body">'
 2194:            .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
 2195: 
 2196: 	my %seenparts;
 2197: 	my @part_response_id = &flatten_responseType($responseType);
 2198: 	foreach my $part (@part_response_id) {
 2199: 	    next if ($env{'form.lastSub'} eq 'hdgrade' 
 2200: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
 2201: 
 2202: 	    my ($partid,$respid) = @{ $part };
 2203: 	    my $display_part=&get_display_part($partid,$symb);
 2204: 	    if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2205: 		if (exists($seenparts{$partid})) { next; }
 2206: 		$seenparts{$partid}=1;
 2207:                 $request->print(
 2208:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2209:                     ' <b>'.&mt('Collaborative submission by: [_1]',
 2210:                                '<a href="javascript:viewSubmitter(\''.
 2211:                                $env{"form.$uname:$udom:$partid:submitted_by"}.
 2212:                                '\');" target="_self">'.
 2213:                                $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
 2214:                     '<br />');
 2215: 		next;
 2216: 		}
 2217: 	    my $responsetype = $responseType->{$partid}->{$respid};
 2218: 	    if (!exists($record{"resource.$partid.$respid.submission"})) {
 2219:                 $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
 2220:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2221:                     ' <span class="LC_internal_info">'.
 2222:                     '('.&mt('Response ID: [_1]',$respid).')'.
 2223:                     '</span>&nbsp; &nbsp;'.
 2224: 	       	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
 2225: 		next;
 2226: 	    }
 2227: 	    foreach my $submission (@$string) {
 2228: 		my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2229: 		if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2230: 		my ($ressub,$hide,$subval) = split(/:/,$submission,3);
 2231: 		# Similarity check
 2232:                 my $similar='';
 2233:                 my ($type,$trial,$rndseed);
 2234:                 if ($hide eq 'rand') {
 2235:                     $type = 'randomizetry';
 2236:                     $trial = $record{"resource.$partid.tries"};
 2237:                     $rndseed = $record{"resource.$partid.rndseed"};
 2238:                 }
 2239: 	        if ($env{'form.checkPlag'}) {
 2240:     		    my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2241: 		        &most_similar($uname,$udom,$symb,$subval);
 2242: 		    if ($osim) {
 2243: 			$osim=int($osim*100.0);
 2244: 			my %old_course_desc = 
 2245: 			    &Apache::lonnet::coursedescription($ocrsid,
 2246: 							{'one_time' => 1});
 2247: 
 2248:                         if ($hide eq 'anon') {
 2249:                             $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
 2250:                                      &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
 2251:                         } else {
 2252: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
 2253: 				&mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
 2254: 				    $osim,
 2255: 				    &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
 2256: 				        $old_course_desc{'description'},
 2257: 				        $old_course_desc{'num'},
 2258: 				        $old_course_desc{'domain'}).
 2259: 				    '</span></h3><blockquote><i>'.
 2260: 				    &keywords_highlight($oessay).
 2261: 				    '</i></blockquote><hr />';
 2262:                         }
 2263: 	            }
 2264: 		}
 2265: 		my $order=&get_order($partid,$respid,$symb,$uname,$udom,
 2266:                                      undef,$type,$trial,$rndseed);
 2267:                 if ($env{'form.lastSub'} eq 'lastonly' || $env{'form.lastSub'} eq 'datesub' || $env{'form.lastSub'} =~ /^(last|all)$/ || ($env{'form.lastSub'} eq 'hdgrade' && 
 2268: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
 2269: 		    my $display_part=&get_display_part($partid,$symb);
 2270:                     $lastsubonly.='<div class="LC_grade_submission_part">'.
 2271:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2272:                         ' <span class="LC_internal_info">'.
 2273:                         '('.&mt('Response ID: [_1]',$respid).')'.
 2274:                         '</span>&nbsp; &nbsp;';
 2275: 		    my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2276:                         
 2277: 		    if (@$files) {
 2278:                         if ($hide eq 'anon') {
 2279:                             $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
 2280:                         } else {
 2281:                             $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
 2282:                                         .'<br /><span class="LC_warning">';
 2283:                             if(@$files == 1) {
 2284:                                 $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
 2285:                             } else {
 2286:                                 $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
 2287:                             }
 2288:                             $lastsubonly .= '</span>';                         
 2289:                             foreach my $file (@$files) {
 2290:                                 &Apache::lonnet::allowuploaded('/adm/grades',$file);
 2291:                                 $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
 2292:                             }
 2293:                         }
 2294: 			$lastsubonly.='<br />';
 2295:                     }
 2296:                     if ($hide eq 'anon') {
 2297:                         $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>'; 
 2298:                     } else {
 2299:              	        $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>'.
 2300: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
 2301: 					 $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
 2302:                     }
 2303: 	            if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2304: 		    $lastsubonly.='</div>';
 2305: 		}
 2306:             }
 2307: 	}
 2308: 	$lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
 2309:     }
 2310:     $request->print($lastsubonly);
 2311:     if ($env{'form.lastSub'} eq 'datesub') {
 2312:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2313: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2314:   
 2315:     } 
 2316:     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2317:         $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2318: 								 $env{'request.course.id'},
 2319: 								 $last,'.submission',
 2320: 								 'Apache::grades::keywords_highlight'));
 2321:     }
 2322:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2323: 	.$udom.'" />'."\n");
 2324:     # return if view submission with no grading option
 2325:     if (!&canmodify($usec)) {
 2326: 	$request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
 2327: 	return;
 2328:     } else {
 2329: 	$request->print('</div>'."\n");
 2330:     }
 2331: 
 2332:     # essay grading message center
 2333: #    if ($env{'form.handgrade'} eq 'yes') {
 2334:     if (1) {
 2335: 	my $result='<div class="LC_grade_message_center">';
 2336:     
 2337: 	$result.='<div class="LC_grade_message_center_header">'.
 2338: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
 2339: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2340: 	my $msgfor = $givenn.' '.$lastname;
 2341: 	if (scalar(@$col_fullnames) > 0) {
 2342: 	    my $lastone = pop(@$col_fullnames);
 2343: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2344: 	}
 2345: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2346: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2347: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
 2348: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2349: 	    ',\''.$msgfor.'\');" target="_self">'.
 2350: 	    &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
 2351: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2352: 	    ' <img src="'.$request->dir_config('lonIconsURL').
 2353: 	    '/mailbkgrd.gif" width="14" height="10" alt="" name="mailicon'.$counter.'" />'."\n".
 2354: 	    '<br />&nbsp;('.
 2355: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
 2356: 	$result.='</div></div>';
 2357: 	$request->print($result);
 2358:     }
 2359: 
 2360:     my %seen = ();
 2361:     my @partlist;
 2362:     my @gradePartRespid;
 2363:     my @part_response_id = &flatten_responseType($responseType);
 2364:     $request->print(
 2365:         '<div class="LC_Box">'
 2366:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
 2367:     );
 2368:     $request->print(&gradeBox_start());
 2369:     foreach my $part_response_id (@part_response_id) {
 2370:     	my ($partid,$respid) = @{ $part_response_id };
 2371: 	my $part_resp = join('_',@{ $part_response_id });
 2372: 	next if ($seen{$partid} > 0);
 2373: 	$seen{$partid}++;
 2374: 	next if ($$handgrade{$part_resp} ne 'yes' 
 2375: 		 && $env{'form.lastSub'} eq 'hdgrade');
 2376: 	push(@partlist,$partid);
 2377: 	push(@gradePartRespid,$partid.'.'.$respid);
 2378: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2379:     }
 2380:     $request->print(&gradeBox_end()); # </div>
 2381:     $request->print('</div>');
 2382: 
 2383:     $request->print('<div class="LC_grade_info_links">');
 2384:     $request->print('</div>');
 2385: 
 2386:     $result='<input type="hidden" name="partlist'.$counter.
 2387: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2388:     $result.='<input type="hidden" name="gradePartRespid'.
 2389: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2390:     my $ctr = 0;
 2391:     while ($ctr < scalar(@partlist)) {
 2392: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2393: 	    $partlist[$ctr].'" />'."\n";
 2394: 	$ctr++;
 2395:     }
 2396:     $request->print($result.''."\n");
 2397: 
 2398: # Done with printing info for one student
 2399: 
 2400:     $request->print('</div>');#LC_grade_show_user
 2401: 
 2402: 
 2403:     # print end of form
 2404:     if ($counter == $total) {
 2405:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
 2406: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2407: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
 2408: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2409: 	my $ntstu ='<select name="NTSTU">'.
 2410: 	    '<option>1</option><option>2</option>'.
 2411: 	    '<option>3</option><option>5</option>'.
 2412: 	    '<option>7</option><option>10</option></select>'."\n";
 2413: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2414: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2415:         $endform.=&mt('[_1]student(s)',$ntstu);
 2416: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2417: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2418: 	    '<input type="button" value="'.&mt('Next').'" '.
 2419: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2420:         $endform.='<span class="LC_warning">'.
 2421:                   &mt('(Next and Previous (student) do not save the scores.)').
 2422:                   '</span>'."\n" ;
 2423:         $endform.="<input type='hidden' value='".&get_increment().
 2424:             "' name='increment' />";
 2425: 	$endform.='</td></tr></table></form>';
 2426: 	$request->print($endform);
 2427:     }
 2428:     return '';
 2429: }
 2430: 
 2431: sub check_collaborators {
 2432:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2433:     my ($result,@col_fullnames);
 2434:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2435:     foreach my $part (keys(%$handgrade)) {
 2436: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2437: 					'.maxcollaborators',
 2438: 					$symb,$udom,$uname);
 2439: 	next if ($ncol <= 0);
 2440: 	$part =~ s/\_/\./g;
 2441: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2442: 	my (@good_collaborators, @bad_collaborators);
 2443: 	foreach my $possible_collaborator
 2444: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2445: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2446: 	    next if ($possible_collaborator eq '');
 2447: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
 2448: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2449: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2450: 	    # Doing this grep allows 'fuzzy' specification
 2451: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2452: 			       keys(%$classlist));
 2453: 	    if (! scalar(@matches)) {
 2454: 		push(@bad_collaborators, $possible_collaborator);
 2455: 	    } else {
 2456: 		push(@good_collaborators, @matches);
 2457: 	    }
 2458: 	}
 2459: 	if (scalar(@good_collaborators) != 0) {
 2460: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
 2461: 	    foreach my $name (@good_collaborators) {
 2462: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2463: 		push(@col_fullnames, $givenn.' '.$lastname);
 2464: 		$result.='<li>'.$fullname->{$name}.'</li>';
 2465: 	    }
 2466: 	    $result.='</ol><br />'."\n";
 2467: 	    my ($part)=split(/\./,$part);
 2468: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2469: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2470: 		"\n";
 2471: 	}
 2472: 	if (scalar(@bad_collaborators) > 0) {
 2473: 	    $result.='<div class="LC_warning">';
 2474: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2475: 	    $result .= '</div>';
 2476: 	}         
 2477: 	if (scalar(@bad_collaborators > $ncol)) {
 2478: 	    $result .= '<div class="LC_warning">';
 2479: 	    $result .= &mt('This student has submitted too many '.
 2480: 		'collaborators.  Maximum is [_1].',$ncol);
 2481: 	    $result .= '</div>';
 2482: 	}
 2483:     }
 2484:     return ($result,$fullname,\@col_fullnames);
 2485: }
 2486: 
 2487: #--- Retrieve the last submission for all the parts
 2488: sub get_last_submission {
 2489:     my ($returnhash)=@_;
 2490:     my (@string,$timestamp,%lasthidden);
 2491:     if ($$returnhash{'version'}) {
 2492: 	my %lasthash=();
 2493: 	my ($version);
 2494: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2495: 	    foreach my $key (sort(split(/\:/,
 2496: 					$$returnhash{$version.':keys'}))) {
 2497: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2498: 		$timestamp = 
 2499: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2500: 	    }
 2501: 	}
 2502:         my (%typeparts,%randombytry);
 2503:         my $showsurv = 
 2504:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
 2505:         foreach my $key (sort(keys(%lasthash))) {
 2506:             if ($key =~ /\.type$/) {
 2507:                 if (($lasthash{$key} eq 'anonsurvey') || 
 2508:                     ($lasthash{$key} eq 'anonsurveycred') ||
 2509:                     ($lasthash{$key} eq 'randomizetry')) {
 2510:                     my ($ign,@parts) = split(/\./,$key);
 2511:                     pop(@parts);
 2512:                     my $id = join('.',@parts);
 2513:                     if ($lasthash{$key} eq 'randomizetry') {
 2514:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
 2515:                     } else {
 2516:                         unless ($showsurv) {
 2517:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
 2518:                         }
 2519:                     }
 2520:                     delete($lasthash{$key});
 2521:                 }
 2522:             }
 2523:         }
 2524:         my @hidden = keys(%typeparts);
 2525:         my @randomize = keys(%randombytry);
 2526: 	foreach my $key (keys(%lasthash)) {
 2527: 	    next if ($key !~ /\.submission$/);
 2528:             my $hide;
 2529:             if (@hidden) {
 2530:                 foreach my $id (@hidden) {
 2531:                     if ($key =~ /^\Q$id\E/) {
 2532:                         $hide = 'anon';
 2533:                         last;
 2534:                     }
 2535:                 }
 2536:             }
 2537:             unless ($hide) {
 2538:                 if (@randomize) {
 2539:                     foreach my $id (@hidden) {
 2540:                         if ($key =~ /^\Q$id\E/) {
 2541:                             $hide = 'rand';
 2542:                             last;
 2543:                         }
 2544:                     }
 2545:                 }
 2546:             }
 2547: 	    my ($partid,$foo) = split(/submission$/,$key);
 2548: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
 2549: 		'<span class="LC_warning">'.&mt('Draft Copy').'</span> ' : '';
 2550: 	    #push(@string, join(':', $key, $hide, $draft.$lasthash{$key}));
 2551:             push(@string, join(':', $key, $hide, $draft.(
 2552:                 ref($lasthash{$key}) eq 'ARRAY' ?
 2553:                     join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
 2554: 	}
 2555:     }
 2556:     if (!@string) {
 2557: 	$string[0] =
 2558: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
 2559:     }
 2560:     return (\@string,\$timestamp);
 2561: }
 2562: 
 2563: #--- High light keywords, with style choosen by user.
 2564: sub keywords_highlight {
 2565:     my $string    = shift;
 2566:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2567:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2568:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2569:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2570:     foreach my $keyword (@keylist) {
 2571: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2572:     }
 2573:     return $string;
 2574: }
 2575: 
 2576: # For Tasks provide a mechanism to display previous version for one specific student
 2577: 
 2578: sub show_previous_task_version {
 2579:     my ($request,$symb) = @_;
 2580:     if ($symb eq '') {
 2581:         $request->print(
 2582:             '<span class="LC_error">'.
 2583:             &mt('Unable to handle ambiguous references.').
 2584:             '</span>');
 2585:         return '';
 2586:     }
 2587:     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
 2588:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 2589:     if (!&canview($usec)) {
 2590:         $request->print(
 2591:             '<span class="LC_warning">'.
 2592:             &mt('Unable to view previous version for requested student.').
 2593:             ' '.&mt('([_1] in section [_2] in course id [_3])',
 2594:                     $uname.':'.$udom,$usec,$env{'request.course.id'}).
 2595:             '</span>');
 2596:         return;
 2597:     }
 2598:     my $mode = 'both';
 2599:     my $isTask = ($symb =~/\.task$/);
 2600:     if ($isTask) {
 2601:         if ($env{'form.previousversion'} =~ /^\d+$/) {
 2602:             if ($env{'form.fullname'} eq '') {
 2603:                 $env{'form.fullname'} =
 2604:                     &Apache::loncommon::plainname($uname,$udom,'lastname');
 2605:             }
 2606:             my $probtitle=&Apache::lonnet::gettitle($symb);
 2607:             $request->print("\n\n".
 2608:                             '<div class="LC_grade_show_user">'.
 2609:                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 2610:                             '</h2>'."\n");
 2611:             &Apache::lonxml::clear_problem_counter();
 2612:             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
 2613:                             {'previousversion' => $env{'form.previousversion'} }));
 2614:             $request->print("\n</div>");
 2615:         }
 2616:     }
 2617:     return;
 2618: }
 2619: 
 2620: sub choose_task_version_form {
 2621:     my ($symb,$uname,$udom,$nomenu) = @_;
 2622:     my $isTask = ($symb =~/\.task$/);
 2623:     my ($current,$version,$result,$js,$displayed,$rowtitle);
 2624:     if ($isTask) {
 2625:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 2626:                                               $udom,$uname);
 2627:         if (($record{'resource.0.version'} eq '') ||
 2628:             ($record{'resource.0.version'} < 2)) {
 2629:             return ($record{'resource.0.version'},
 2630:                     $record{'resource.0.version'},$result,$js);
 2631:         } else {
 2632:             $current = $record{'resource.0.version'};
 2633:         }
 2634:         if ($env{'form.previousversion'}) {
 2635:             $displayed = $env{'form.previousversion'};
 2636:             $rowtitle = &mt('Choose another version:')
 2637:         } else {
 2638:             $displayed = $current;
 2639:             $rowtitle = &mt('Show earlier version:');
 2640:         }
 2641:         $result = '<div class="LC_left_float">';
 2642:         my $list;
 2643:         my $numversions = 0;
 2644:         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
 2645:             if ($i == $current) {
 2646:                 if (!$env{'form.previousversion'} || $nomenu) {
 2647:                     next;
 2648:                 } else {
 2649:                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
 2650:                     $numversions ++;
 2651:                 }
 2652:             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
 2653:                 unless ($i == $env{'form.previousversion'}) {
 2654:                     $numversions ++;
 2655:                 }
 2656:                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
 2657:             }
 2658:         }
 2659:         if ($numversions) {
 2660:             $symb = &HTML::Entities::encode($symb,'<>"&');
 2661:             $result .=
 2662:                 '<form name="getprev" method="post" action=""'.
 2663:                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
 2664:                 &Apache::loncommon::start_data_table().
 2665:                 &Apache::loncommon::start_data_table_row().
 2666:                 '<th align="left">'.$rowtitle.'</th>'.
 2667:                 '<td><select name="version">'.
 2668:                 '<option>'.&mt('Select').'</option>'.
 2669:                 $list.
 2670:                 '</select></td>'.
 2671:                 &Apache::loncommon::end_data_table_row();
 2672:             unless ($nomenu) {
 2673:                 $result .= &Apache::loncommon::start_data_table_row().
 2674:                 '<th align="left">'.&mt('Open in new window').'</th>'.
 2675:                 '<td><span class="LC_nobreak">'.
 2676:                 '<label><input type="radio" name="prevwin" value="1" />'.
 2677:                 &mt('Yes').'</label>'.
 2678:                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
 2679:                 '</span></td>'.
 2680:                 &Apache::loncommon::end_data_table_row();
 2681:             }
 2682:             $result .=
 2683:                 &Apache::loncommon::start_data_table_row().
 2684:                 '<th align="left">&nbsp;</th>'.
 2685:                 '<td>'.
 2686:                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
 2687:                 '</td>'.
 2688:                 &Apache::loncommon::end_data_table_row().
 2689:                 &Apache::loncommon::end_data_table().
 2690:                 '</form>';
 2691:             $js = &previous_display_javascript($nomenu,$current);
 2692:         } elsif ($displayed && $nomenu) {
 2693:             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
 2694:         } else {
 2695:             $result .= &mt('No previous versions to show for this student');
 2696:         }
 2697:         $result .= '</div>';
 2698:     }
 2699:     return ($current,$displayed,$result,$js);
 2700: }
 2701: 
 2702: sub previous_display_javascript {
 2703:     my ($nomenu,$current) = @_;
 2704:     my $js = <<"JSONE";
 2705: <script type="text/javascript">
 2706: // <![CDATA[
 2707: function previousVersion(uname,udom,symb) {
 2708:     var current = '$current';
 2709:     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
 2710:     var prevstr = new RegExp("^\\\\d+\$");
 2711:     if (!prevstr.test(version)) {
 2712:         return false;
 2713:     }
 2714:     var url = '';
 2715:     if (version == current) {
 2716:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
 2717:     } else {
 2718:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
 2719:     }
 2720: JSONE
 2721:     if ($nomenu) {
 2722:         $js .= <<"JSTWO";
 2723:     document.location.href = url;
 2724: JSTWO
 2725:     } else {
 2726:         $js .= <<"JSTHREE";
 2727:     var newwin = 0;
 2728:     for (var i=0; i<document.getprev.prevwin.length; i++) {
 2729:         if (document.getprev.prevwin[i].checked == true) {
 2730:             newwin = document.getprev.prevwin[i].value;
 2731:         }
 2732:     }
 2733:     if (newwin == 1) {
 2734:         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
 2735:         url = url+'&inhibitmenu=yes';
 2736:         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
 2737:             previousWin = window.open(url,'',options,1);
 2738:         } else {
 2739:             previousWin.location.href = url;
 2740:         }
 2741:         previousWin.focus();
 2742:         return false;
 2743:     } else {
 2744:         document.location.href = url;
 2745:         return false;
 2746:     }
 2747: JSTHREE
 2748:     }
 2749:     $js .= <<"ENDJS";
 2750:     return false;
 2751: }
 2752: // ]]>
 2753: </script>
 2754: ENDJS
 2755: 
 2756: }
 2757: 
 2758: #--- Called from submission routine
 2759: sub processHandGrade {
 2760:     my ($request,$symb) = @_;
 2761:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2762:     my $button = $env{'form.gradeOpt'};
 2763:     my $ngrade = $env{'form.NCT'};
 2764:     my $ntstu  = $env{'form.NTSTU'};
 2765:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2766:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 2767: 
 2768:     if ($button eq 'Save & Next') {
 2769: 	my $ctr = 0;
 2770: 	while ($ctr < $ngrade) {
 2771: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 2772: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 2773: 	    if ($errorflag eq 'no_score') {
 2774: 		$ctr++;
 2775: 		next;
 2776: 	    }
 2777: 	    if ($errorflag eq 'not_allowed') {
 2778: 		$request->print(
 2779:                     '<span class="LC_error">'
 2780:                    .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
 2781:                    .'</span>');
 2782: 		$ctr++;
 2783: 		next;
 2784: 	    }
 2785: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 2786: 	    my ($subject,$message,$msgstatus) = ('','','');
 2787: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 2788:             my ($feedurl,$showsymb) =
 2789: 		&get_feedurl_and_symb($symb,$uname,$udom);
 2790: 	    my $messagetail;
 2791: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 2792: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 2793: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 2794: 		$subject.=' ['.$restitle.']';
 2795: 		my (@msgnum) = split(/,/,$includemsg);
 2796: 		foreach (@msgnum) {
 2797: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 2798: 		}
 2799: 		$message =&Apache::lonfeedback::clear_out_html($message);
 2800: 		if ($env{'form.withgrades'.$ctr}) {
 2801: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 2802: 		    $messagetail = " for <a href=\"".
 2803: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
 2804: 		}
 2805: 		$msgstatus = 
 2806:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 2807: 						     $message.$messagetail,
 2808:                                                      undef,$feedurl,undef,
 2809:                                                      undef,undef,$showsymb,
 2810:                                                      $restitle);
 2811: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
 2812: 				$msgstatus.'<br />');
 2813: 	    }
 2814: 	    if ($env{'form.collaborator'.$ctr}) {
 2815: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 2816: 		foreach my $collabstr (@collabstrs) {
 2817: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 2818: 		    foreach my $collaborator (@collaborators) {
 2819: 			my ($errorflag,$pts,$wgt) = 
 2820: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 2821: 					   $env{'form.unamedom'.$ctr},$part);
 2822: 			if ($errorflag eq 'not_allowed') {
 2823: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 2824: 			    next;
 2825: 			} elsif ($message ne '') {
 2826: 			    my ($baseurl,$showsymb) = 
 2827: 				&get_feedurl_and_symb($symb,$collaborator,
 2828: 						      $udom);
 2829: 			    if ($env{'form.withgrades'.$ctr}) {
 2830: 				$messagetail = " for <a href=\"".
 2831:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
 2832: 			    }
 2833: 			    $msgstatus = 
 2834: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 2835: 			}
 2836: 		    }
 2837: 		}
 2838: 	    }
 2839: 	    $ctr++;
 2840: 	}
 2841:     }
 2842: 
 2843: #    if ($env{'form.handgrade'} eq 'yes') {
 2844:     if (1) {
 2845: 	# Keywords sorted in alphabatical order
 2846: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2847: 	my %keyhash = ();
 2848: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 2849: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 2850: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 2851: 	$env{'form.keywords'} = join(' ',@keywords);
 2852: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 2853: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 2854: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 2855: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 2856: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 2857: 
 2858: 	# message center - Order of message gets changed. Blank line is eliminated.
 2859: 	# New messages are saved in env for the next student.
 2860: 	# All messages are saved in nohist_handgrade.db
 2861: 	my ($ctr,$idx) = (1,1);
 2862: 	while ($ctr <= $env{'form.savemsgN'}) {
 2863: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 2864: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 2865: 		$idx++;
 2866: 	    }
 2867: 	    $ctr++;
 2868: 	}
 2869: 	$ctr = 0;
 2870: 	while ($ctr < $ngrade) {
 2871: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 2872: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2873: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2874: 		$idx++;
 2875: 	    }
 2876: 	    $ctr++;
 2877: 	}
 2878: 	$env{'form.savemsgN'} = --$idx;
 2879: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 2880: 	my $putresult = &Apache::lonnet::put
 2881: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 2882:     }
 2883:     # Called by Save & Refresh from Highlight Attribute Window
 2884:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 2885:     if ($env{'form.refresh'} eq 'on') {
 2886: 	my ($ctr,$total) = (0,0);
 2887: 	while ($ctr < $ngrade) {
 2888: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 2889: 	    $ctr++;
 2890: 	}
 2891: 	$env{'form.NTSTU'}=$ngrade;
 2892: 	$ctr = 0;
 2893: 	while ($ctr < $total) {
 2894: 	    my $processUser = $env{'form.unamedom'.$ctr};
 2895: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2896: 	    $env{'form.fullname'} = $$fullname{$processUser};
 2897: 	    &submission($request,$ctr,$total-1,$symb);
 2898: 	    $ctr++;
 2899: 	}
 2900: 	return '';
 2901:     }
 2902: 
 2903:     # Get the next/previous one or group of students
 2904:     my $firststu = $env{'form.unamedom0'};
 2905:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 2906:     my $ctr = 2;
 2907:     while ($laststu eq '') {
 2908: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 2909: 	$ctr++;
 2910: 	$laststu = $firststu if ($ctr > $ngrade);
 2911:     }
 2912: 
 2913:     my (@parsedlist,@nextlist);
 2914:     my ($nextflg) = 0;
 2915:     foreach my $item (sort 
 2916: 	     {
 2917: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 2918: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 2919: 		 }
 2920: 		 return $a cmp $b;
 2921: 	     } (keys(%$fullname))) {
 2922: # FIXME: this is fishy, looks like the button label
 2923: 	if ($nextflg == 1 && $button =~ /Next$/) {
 2924: 	    push(@parsedlist,$item);
 2925: 	}
 2926: 	$nextflg = 1 if ($item eq $laststu);
 2927: 	if ($button eq 'Previous') {
 2928: 	    last if ($item eq $firststu);
 2929: 	    push(@parsedlist,$item);
 2930: 	}
 2931:     }
 2932:     $ctr = 0;
 2933: # FIXME: this is fishy, looks like the button label
 2934:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 2935:     my $res_error;
 2936:     my ($partlist) = &response_type($symb,\$res_error);
 2937:     if ($res_error) {
 2938:         $request->print(&navmap_errormsg());
 2939:         return;
 2940:     }
 2941:     foreach my $student (@parsedlist) {
 2942: 	my $submitonly=$env{'form.submitonly'};
 2943: 	my ($uname,$udom) = split(/:/,$student);
 2944: 	
 2945: 	if ($submitonly eq 'queued') {
 2946: 	    my %queue_status = 
 2947: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 2948: 							$udom,$uname);
 2949: 	    next if (!defined($queue_status{'gradingqueue'}));
 2950: 	}
 2951: 
 2952: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 2953: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2954: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 2955: 	    my $submitted = 0;
 2956: 	    my $ungraded = 0;
 2957: 	    my $incorrect = 0;
 2958: 	    foreach my $item (keys(%status)) {
 2959: 		$submitted = 1 if ($status{$item} ne 'nothing');
 2960: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 2961: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 2962: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 2963: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 2964: 		    $submitted = 0;
 2965: 		}
 2966: 	    }
 2967: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 2968: 				     $submitonly eq 'incorrect' ||
 2969: 				     $submitonly eq 'graded'));
 2970: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 2971: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 2972: 	}
 2973: 	push(@nextlist,$student) if ($ctr < $ntstu);
 2974: 	last if ($ctr == $ntstu);
 2975: 	$ctr++;
 2976:     }
 2977: 
 2978:     $ctr = 0;
 2979:     my $total = scalar(@nextlist)-1;
 2980: 
 2981:     foreach (sort(@nextlist)) {
 2982: 	my ($uname,$udom,$submitter) = split(/:/);
 2983: 	$env{'form.student'}  = $uname;
 2984: 	$env{'form.userdom'}  = $udom;
 2985: 	$env{'form.fullname'} = $$fullname{$_};
 2986: 	&submission($request,$ctr,$total,$symb);
 2987: 	$ctr++;
 2988:     }
 2989:     if ($total < 0) {
 2990: 	my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
 2991: 	$request->print($the_end);
 2992:     }
 2993:     return '';
 2994: }
 2995: 
 2996: #---- Save the score and award for each student, if changed
 2997: sub saveHandGrade {
 2998:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 2999:     my @version_parts;
 3000:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 3001: 					   $env{'request.course.id'});
 3002:     if (!&canmodify($usec)) { return('not_allowed'); }
 3003:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 3004:     my @parts_graded;
 3005:     my %newrecord  = ();
 3006:     my ($pts,$wgt) = ('','');
 3007:     my %aggregate = ();
 3008:     my $aggregateflag = 0;
 3009:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 3010:     foreach my $new_part (@parts) {
 3011: 	#collaborator ($submi may vary for different parts
 3012: 	if ($submitter && $new_part ne $part) { next; }
 3013: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 3014: 	if ($dropMenu eq 'excused') {
 3015: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 3016: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 3017: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 3018: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 3019: 		}
 3020: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3021: 	    }
 3022: 	} elsif ($dropMenu eq 'reset status'
 3023: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 3024: 	    foreach my $key (keys(%record)) {
 3025: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 3026: 	    }
 3027: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3028: 		"$env{'user.name'}:$env{'user.domain'}";
 3029:             my $totaltries = $record{'resource.'.$part.'.tries'};
 3030: 
 3031:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 3032: 					       [$new_part]);
 3033:             my $aggtries =$totaltries;
 3034:             if ($last_resets{$new_part}) {
 3035:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 3036: 					   $new_part);
 3037:             }
 3038: 
 3039:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 3040:             if ($aggtries > 0) {
 3041:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3042:                 $aggregateflag = 1;
 3043:             }
 3044: 	} elsif ($dropMenu eq '') {
 3045: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 3046: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 3047: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 3048: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 3049: 		next;
 3050: 	    }
 3051: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 3052: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 3053: 	    my $partial= $pts/$wgt;
 3054: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 3055: 		#do not update score for part if not changed.
 3056:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 3057: 		next;
 3058: 	    } else {
 3059: 	        push(@parts_graded,$new_part);
 3060: 	    }
 3061: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 3062: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 3063: 	    }
 3064: 	    my $reckey = 'resource.'.$new_part.'.solved';
 3065: 	    if ($partial == 0) {
 3066: 		if ($record{$reckey} ne 'incorrect_by_override') {
 3067: 		    $newrecord{$reckey} = 'incorrect_by_override';
 3068: 		}
 3069: 	    } else {
 3070: 		if ($record{$reckey} ne 'correct_by_override') {
 3071: 		    $newrecord{$reckey} = 'correct_by_override';
 3072: 		}
 3073: 	    }	    
 3074: 	    if ($submitter && 
 3075: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 3076: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 3077: 	    }
 3078: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3079: 		"$env{'user.name'}:$env{'user.domain'}";
 3080: 	}
 3081: 	# unless problem has been graded, set flag to version the submitted files
 3082: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 3083: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 3084: 	        $dropMenu eq 'reset status')
 3085: 	   {
 3086: 	    push(@version_parts,$new_part);
 3087: 	}
 3088:     }
 3089:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3090:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3091: 
 3092:     if (%newrecord) {
 3093:         if (@version_parts) {
 3094:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 3095:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 3096: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 3097: 	    foreach my $new_part (@version_parts) {
 3098: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 3099: 				$new_part,\%newrecord);
 3100: 	    }
 3101:         }
 3102: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 3103: 				$env{'request.course.id'},$domain,$stuname);
 3104: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 3105: 				     $cdom,$cnum,$domain,$stuname);
 3106:     }
 3107:     if ($aggregateflag) {
 3108:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3109: 			      $cdom,$cnum);
 3110:     }
 3111:     return ('',$pts,$wgt);
 3112: }
 3113: 
 3114: sub check_and_remove_from_queue {
 3115:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 3116:     my @ungraded_parts;
 3117:     foreach my $part (@{$parts}) {
 3118: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 3119: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 3120: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 3121: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 3122: 		) {
 3123: 	    push(@ungraded_parts, $part);
 3124: 	}
 3125:     }
 3126:     if ( !@ungraded_parts ) {
 3127: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 3128: 					       $cnum,$domain,$stuname);
 3129:     }
 3130: }
 3131: 
 3132: sub handback_files {
 3133:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 3134:     my $portfolio_root = '/userfiles/portfolio';
 3135:     my $res_error;
 3136:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3137:     if ($res_error) {
 3138:         $request->print('<br />'.&navmap_errormsg().'<br />');
 3139:         return;
 3140:     }
 3141:     my @handedback;
 3142:     my $file_msg;
 3143:     my @part_response_id = &flatten_responseType($responseType);
 3144:     foreach my $part_response_id (@part_response_id) {
 3145:     	my ($part_id,$resp_id) = @{ $part_response_id };
 3146: 	my $part_resp = join('_',@{ $part_response_id });
 3147:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
 3148:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
 3149:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3' 
 3150:                 if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
 3151:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
 3152:                     my ($directory,$answer_file) = 
 3153:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
 3154:                     my ($answer_name,$answer_ver,$answer_ext) =
 3155: 		        &file_name_version_ext($answer_file);
 3156: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 3157:                     my $getpropath = 1;
 3158:                     my ($dir_list,$listerror) = 
 3159:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
 3160:                                                  $domain,$stuname,$getpropath);
 3161: 		    my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
 3162:                     # fix filename
 3163:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 3164:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 3165:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
 3166:             	                                $save_file_name);
 3167:                     if ($result !~ m|^/uploaded/|) {
 3168:                         $request->print('<br /><span class="LC_error">'.
 3169:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 3170:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
 3171:                                         '</span>');
 3172:                     } else {
 3173:                         # mark the file as read only
 3174:                         push(@handedback,$save_file_name);
 3175: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 3176: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 3177: 			}
 3178:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 3179: 			$file_msg.= '<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
 3180:                     }
 3181:                     $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>'));
 3182:                 }
 3183:             }
 3184:         }
 3185:     }
 3186:     if (@handedback > 0) {
 3187:         $request->print('<br />');
 3188:         my @what = ($symb,$env{'request.course.id'},'handback');
 3189:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
 3190:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});    
 3191:         my ($subject,$message);
 3192:         if (scalar(@handedback) == 1) {
 3193:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
 3194:             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
 3195:         } else {
 3196:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
 3197:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
 3198:         }
 3199:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
 3200:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
 3201:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
 3202:         my ($feedurl,$showsymb) =
 3203:             &get_feedurl_and_symb($symb,$domain,$stuname);
 3204:         my $restitle = &Apache::lonnet::gettitle($symb);
 3205:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
 3206:         my $msgstatus =
 3207:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
 3208:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
 3209:                  $restitle);
 3210:         if ($msgstatus) {
 3211:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
 3212:         }
 3213:     }
 3214:     return;
 3215: }
 3216: 
 3217: sub get_feedurl_and_symb {
 3218:     my ($symb,$uname,$udom) = @_;
 3219:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3220:     $url = &Apache::lonnet::clutter($url);
 3221:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 3222: 					$symb,$udom,$uname);
 3223:     if ($encrypturl =~ /^yes$/i) {
 3224: 	&Apache::lonenc::encrypted(\$url,1);
 3225: 	&Apache::lonenc::encrypted(\$symb,1);
 3226:     }
 3227:     return ($url,$symb);
 3228: }
 3229: 
 3230: sub get_submitted_files {
 3231:     my ($udom,$uname,$partid,$respid,$record) = @_;
 3232:     my @files;
 3233:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 3234:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 3235:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 3236:     	    push(@files,$file_url.$file);
 3237:         }
 3238:     }
 3239:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 3240:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 3241:     }
 3242:     return (\@files);
 3243: }
 3244: 
 3245: # ----------- Provides number of tries since last reset.
 3246: sub get_num_tries {
 3247:     my ($record,$last_reset,$part) = @_;
 3248:     my $timestamp = '';
 3249:     my $num_tries = 0;
 3250:     if ($$record{'version'}) {
 3251:         for (my $version=$$record{'version'};$version>=1;$version--) {
 3252:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 3253:                 $timestamp = $$record{$version.':timestamp'};
 3254:                 if ($timestamp > $last_reset) {
 3255:                     $num_tries ++;
 3256:                 } else {
 3257:                     last;
 3258:                 }
 3259:             }
 3260:         }
 3261:     }
 3262:     return $num_tries;
 3263: }
 3264: 
 3265: # ----------- Determine decrements required in aggregate totals 
 3266: sub decrement_aggs {
 3267:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 3268:     my %decrement = (
 3269:                         attempts => 0,
 3270:                         users => 0,
 3271:                         correct => 0
 3272:                     );
 3273:     $decrement{'attempts'} = $aggtries;
 3274:     if ($solvedstatus =~ /^correct/) {
 3275:         $decrement{'correct'} = 1;
 3276:     }
 3277:     if ($aggtries == $totaltries) {
 3278:         $decrement{'users'} = 1;
 3279:     }
 3280:     foreach my $type (keys(%decrement)) {
 3281:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 3282:     }
 3283:     return;
 3284: }
 3285: 
 3286: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 3287: sub get_last_resets {
 3288:     my ($symb,$courseid,$partids) =@_;
 3289:     my %last_resets;
 3290:     my $cdom = $env{'course.'.$courseid.'.domain'};
 3291:     my $cname = $env{'course.'.$courseid.'.num'};
 3292:     my @keys;
 3293:     foreach my $part (@{$partids}) {
 3294: 	push(@keys,"$symb\0$part\0resettime");
 3295:     }
 3296:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 3297: 				     $cdom,$cname);
 3298:     foreach my $part (@{$partids}) {
 3299: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 3300:     }
 3301:     return %last_resets;
 3302: }
 3303: 
 3304: # ----------- Handles creating versions for portfolio files as answers
 3305: sub version_portfiles {
 3306:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 3307:     my $version_parts = join('|',@$v_flag);
 3308:     my @returned_keys;
 3309:     my $parts = join('|', @$parts_graded);
 3310:     my $portfolio_root = '/userfiles/portfolio';
 3311:     foreach my $key (keys(%$record)) {
 3312:         my $new_portfiles;
 3313:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 3314:             my @versioned_portfiles;
 3315:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 3316:             foreach my $file (@portfiles) {
 3317:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 3318:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 3319: 		my ($answer_name,$answer_ver,$answer_ext) =
 3320: 		    &file_name_version_ext($answer_file);
 3321:                 my $getpropath = 1;    
 3322:                 my ($dir_list,$listerror) = 
 3323:                     &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,
 3324:                                              $stu_name,$getpropath);
 3325:                 my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
 3326:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
 3327:                 if ($new_answer ne 'problem getting file') {
 3328:                     push(@versioned_portfiles, $directory.$new_answer);
 3329:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
 3330:                         [$directory.$new_answer],
 3331:                         [$symb,$env{'request.course.id'},'graded']);
 3332:                 }
 3333:             }
 3334:             $$record{$key} = join(',',@versioned_portfiles);
 3335:             push(@returned_keys,$key);
 3336:         }
 3337:     } 
 3338:     return (@returned_keys);   
 3339: }
 3340: 
 3341: sub get_next_version {
 3342:     my ($answer_name, $answer_ext, $dir_list) = @_;
 3343:     my $version;
 3344:     if (ref($dir_list) eq 'ARRAY') {
 3345:         foreach my $row (@{$dir_list}) {
 3346:             my ($file) = split(/\&/,$row,2);
 3347:             my ($file_name,$file_version,$file_ext) =
 3348: 	        &file_name_version_ext($file);
 3349:             if (($file_name eq $answer_name) && 
 3350: 	        ($file_ext eq $answer_ext)) {
 3351:                      # gets here if filename and extension match, 
 3352:                      # regardless of version
 3353:                 if ($file_version ne '') {
 3354:                     # a versioned file is found  so save it for later
 3355:                     if ($file_version > $version) {
 3356: 		        $version = $file_version;
 3357: 	            }
 3358:                 }
 3359:             }
 3360:         }
 3361:     }
 3362:     $version ++;
 3363:     return($version);
 3364: }
 3365: 
 3366: sub version_selected_portfile {
 3367:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 3368:     my ($answer_name,$answer_ver,$answer_ext) =
 3369:         &file_name_version_ext($file_name);
 3370:     my $new_answer;
 3371:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 3372:     if($env{'form.copy'} eq '-1') {
 3373:         $new_answer = 'problem getting file';
 3374:     } else {
 3375:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 3376:         my $copy_result = &Apache::lonnet::finishuserfileupload(
 3377:                             $stu_name,$domain,'copy',
 3378: 		        '/portfolio'.$directory.$new_answer);
 3379:     }    
 3380:     return ($new_answer);
 3381: }
 3382: 
 3383: sub file_name_version_ext {
 3384:     my ($file)=@_;
 3385:     my @file_parts = split(/\./, $file);
 3386:     my ($name,$version,$ext);
 3387:     if (@file_parts > 1) {
 3388: 	$ext=pop(@file_parts);
 3389: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 3390: 	    $version=pop(@file_parts);
 3391: 	}
 3392: 	$name=join('.',@file_parts);
 3393:     } else {
 3394: 	$name=join('.',@file_parts);
 3395:     }
 3396:     return($name,$version,$ext);
 3397: }
 3398: 
 3399: #--------------------------------------------------------------------------------------
 3400: #
 3401: #-------------------------- Next few routines handles grading by section or whole class
 3402: #
 3403: #--- Javascript to handle grading by section or whole class
 3404: sub viewgrades_js {
 3405:     my ($request) = shift;
 3406: 
 3407:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3408:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
 3409:    function writePoint(partid,weight,point) {
 3410: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3411: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3412: 	if (point == "textval") {
 3413: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3414: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3415: 		alert("$alertmsg"+parseFloat(point));
 3416: 		var resetbox = false;
 3417: 		for (var i=0; i<radioButton.length; i++) {
 3418: 		    if (radioButton[i].checked) {
 3419: 			textbox.value = i;
 3420: 			resetbox = true;
 3421: 		    }
 3422: 		}
 3423: 		if (!resetbox) {
 3424: 		    textbox.value = "";
 3425: 		}
 3426: 		return;
 3427: 	    }
 3428: 	    if (parseFloat(point) > parseFloat(weight)) {
 3429: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3430: 				   ") greater than the weight for the part. Accept?");
 3431: 		if (resp == false) {
 3432: 		    textbox.value = "";
 3433: 		    return;
 3434: 		}
 3435: 	    }
 3436: 	    for (var i=0; i<radioButton.length; i++) {
 3437: 		radioButton[i].checked=false;
 3438: 		if (parseFloat(point) == i) {
 3439: 		    radioButton[i].checked=true;
 3440: 		}
 3441: 	    }
 3442: 
 3443: 	} else {
 3444: 	    textbox.value = parseFloat(point);
 3445: 	}
 3446: 	for (i=0;i<document.classgrade.total.value;i++) {
 3447: 	    var user = document.classgrade["ctr"+i].value;
 3448: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3449: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3450: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3451: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3452: 	    if (saveval != "correct") {
 3453: 		scorename.value = point;
 3454: 		if (selname[0].selected != true) {
 3455: 		    selname[0].selected = true;
 3456: 		}
 3457: 	    }
 3458: 	}
 3459: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3460:     }
 3461: 
 3462:     function writeRadText(partid,weight) {
 3463: 	var selval   = document.classgrade["SELVAL_"+partid];
 3464: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3465:         var override = document.classgrade["FORCE_"+partid].checked;
 3466: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3467: 	if (selval[1].selected || selval[2].selected) {
 3468: 	    for (var i=0; i<radioButton.length; i++) {
 3469: 		radioButton[i].checked=false;
 3470: 
 3471: 	    }
 3472: 	    textbox.value = "";
 3473: 
 3474: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3475: 		var user = document.classgrade["ctr"+i].value;
 3476: 		user = user.replace(new RegExp(':', 'g'),"_");
 3477: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3478: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3479: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3480: 		if ((saveval != "correct") || override) {
 3481: 		    scorename.value = "";
 3482: 		    if (selval[1].selected) {
 3483: 			selname[1].selected = true;
 3484: 		    } else {
 3485: 			selname[2].selected = true;
 3486: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3487: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3488: 		    }
 3489: 		}
 3490: 	    }
 3491: 	} else {
 3492: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3493: 		var user = document.classgrade["ctr"+i].value;
 3494: 		user = user.replace(new RegExp(':', 'g'),"_");
 3495: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3496: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3497: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3498: 		if ((saveval != "correct") || override) {
 3499: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3500: 		    selname[0].selected = true;
 3501: 		}
 3502: 	    }
 3503: 	}	    
 3504:     }
 3505: 
 3506:     function changeSelect(partid,user) {
 3507: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3508: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3509: 	var point  = textbox.value;
 3510: 	var weight = document.classgrade["weight_"+partid].value;
 3511: 
 3512: 	if (isNaN(point) || parseFloat(point) < 0) {
 3513: 	    alert("$alertmsg"+parseFloat(point));
 3514: 	    textbox.value = "";
 3515: 	    return;
 3516: 	}
 3517: 	if (parseFloat(point) > parseFloat(weight)) {
 3518: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3519: 			       ") greater than the weight of the part. Accept?");
 3520: 	    if (resp == false) {
 3521: 		textbox.value = "";
 3522: 		return;
 3523: 	    }
 3524: 	}
 3525: 	selval[0].selected = true;
 3526:     }
 3527: 
 3528:     function changeOneScore(partid,user) {
 3529: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3530: 	if (selval[1].selected || selval[2].selected) {
 3531: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3532: 	    if (selval[2].selected) {
 3533: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3534: 	    }
 3535:         }
 3536:     }
 3537: 
 3538:     function resetEntry(numpart) {
 3539: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3540: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3541: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3542: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3543: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3544: 	    for (var i=0; i<radioButton.length; i++) {
 3545: 		radioButton[i].checked=false;
 3546: 
 3547: 	    }
 3548: 	    textbox.value = "";
 3549: 	    selval[0].selected = true;
 3550: 
 3551: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3552: 		var user = document.classgrade["ctr"+i].value;
 3553: 		user = user.replace(new RegExp(':', 'g'),"_");
 3554: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3555: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3556: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3557: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3558: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3559: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3560: 		if (saveselval == "excused") {
 3561: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3562: 		} else {
 3563: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3564: 		}
 3565: 	    }
 3566: 	}
 3567:     }
 3568: 
 3569: VIEWJAVASCRIPT
 3570: }
 3571: 
 3572: #--- show scores for a section or whole class w/ option to change/update a score
 3573: sub viewgrades {
 3574:     my ($request,$symb) = @_;
 3575:     &viewgrades_js($request);
 3576: 
 3577:     #need to make sure we have the correct data for later EXT calls, 
 3578:     #thus invalidate the cache
 3579:     &Apache::lonnet::devalidatecourseresdata(
 3580:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3581:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3582:     &Apache::lonnet::clear_EXT_cache_status();
 3583: 
 3584:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3585: 
 3586:     #view individual student submission form - called using Javascript viewOneStudent
 3587:     $result.=&jscriptNform($symb);
 3588: 
 3589:     #beginning of class grading form
 3590:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3591:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3592: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3593: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3594: 	&build_section_inputs().
 3595: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3596: 
 3597:     my ($common_header,$specific_header);
 3598:     if ($env{'form.section'} eq 'all') {
 3599: 	$common_header = &mt('Assign Common Grade to Class');
 3600:         $specific_header = &mt('Assign Grade to Specific Students in Class');
 3601:     } elsif ($env{'form.section'} eq 'none') {
 3602:         $common_header = &mt('Assign Common Grade to Students in no Section');
 3603: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
 3604:     } else {
 3605:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3606:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
 3607: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
 3608:     }
 3609:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
 3610:     #radio buttons/text box for assigning points for a section or class.
 3611:     #handles different parts of a problem
 3612:     my $res_error;
 3613:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3614:     if ($res_error) {
 3615:         return &navmap_errormsg();
 3616:     }
 3617:     my %weight = ();
 3618:     my $ctsparts = 0;
 3619:     my %seen = ();
 3620:     my @part_response_id = &flatten_responseType($responseType);
 3621:     foreach my $part_response_id (@part_response_id) {
 3622:     	my ($partid,$respid) = @{ $part_response_id };
 3623: 	my $part_resp = join('_',@{ $part_response_id });
 3624: 	next if $seen{$partid};
 3625: 	$seen{$partid}++;
 3626: 	my $handgrade=$$handgrade{$part_resp};
 3627: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 3628: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 3629: 
 3630: 	my $display_part=&get_display_part($partid,$symb);
 3631: 	my $radio.='<table border="0"><tr>';  
 3632: 	my $ctr = 0;
 3633: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 3634: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 3635: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 3636: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 3637: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 3638: 	    $ctr++;
 3639: 	}
 3640: 	$radio.='</tr></table>';
 3641: 	my $line = '<input type="text" name="TEXTVAL_'.
 3642: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
 3643: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 3644: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 3645:         $line.= '<td><b>'.&mt('Grade Status').':</b>'.
 3646:             '<select name="SELVAL_'.$partid.'" '.
 3647:             'onchange="javascript:writeRadText(\''.$partid.'\','.
 3648:                 $weight{$partid}.')"> '.
 3649: 	    '<option selected="selected"> </option>'.
 3650: 	    '<option value="excused">'.&mt('excused').'</option>'.
 3651: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 3652: 	    '</select></td>'.
 3653:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 3654: 	$line.='<input type="hidden" name="partid_'.
 3655: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 3656: 	$line.='<input type="hidden" name="weight_'.
 3657: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 3658: 
 3659: 	$result.=
 3660: 	    &Apache::loncommon::start_data_table_row()."\n".
 3661: 	    '<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>'.
 3662: 	    &Apache::loncommon::end_data_table_row()."\n";
 3663: 	$ctsparts++;
 3664:     }
 3665:     $result.=&Apache::loncommon::end_data_table()."\n".
 3666: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 3667:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 3668: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
 3669: 
 3670:     #table listing all the students in a section/class
 3671:     #header of table
 3672:     $result.= '<h3>'.$specific_header.'</h3>'.
 3673:               &Apache::loncommon::start_data_table().
 3674: 	      &Apache::loncommon::start_data_table_header_row().
 3675: 	      '<th>'.&mt('No.').'</th>'.
 3676: 	      '<th>'.&nameUserString('header')."</th>\n";
 3677:     my $partserror;
 3678:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3679:     if ($partserror) {
 3680:         return &navmap_errormsg();
 3681:     }
 3682:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 3683:     my @partids = ();
 3684:     foreach my $part (@parts) {
 3685: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3686:         my $narrowtext = &mt('Tries');
 3687: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 3688: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 3689: 	my ($partid) = &split_part_type($part);
 3690:         push(@partids,$partid);
 3691: #
 3692: # FIXME: Looks like $display looks at English text
 3693: #
 3694: 	my $display_part=&get_display_part($partid,$symb);
 3695: 	if ($display =~ /^Partial Credit Factor/) {
 3696: 	    $result.='<th>'.
 3697: 		&mt('Score Part: [_1][_2](weight = [_3])',
 3698: 		    $display_part,'<br />',$weight{$partid}).'</th>'."\n";
 3699: 	    next;
 3700: 	    
 3701: 	} else {
 3702: 	    if ($display =~ /Problem Status/) {
 3703: 		my $grade_status_mt = &mt('Grade Status');
 3704: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 3705: 	    }
 3706: 	    my $part_mt = &mt('Part:');
 3707: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 3708: 	}
 3709: 
 3710: 	$result.='<th>'.$display.'</th>'."\n";
 3711:     }
 3712:     $result.=&Apache::loncommon::end_data_table_header_row();
 3713: 
 3714:     my %last_resets = 
 3715: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 3716: 
 3717:     #get info for each student
 3718:     #list all the students - with points and grade status
 3719:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3720:     my $ctr = 0;
 3721:     foreach (sort 
 3722: 	     {
 3723: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3724: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3725: 		 }
 3726: 		 return $a cmp $b;
 3727: 	     } (keys(%$fullname))) {
 3728: 	$ctr++;
 3729: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 3730: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
 3731:     }
 3732:     $result.=&Apache::loncommon::end_data_table();
 3733:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 3734:     $result.='<input type="button" value="'.&mt('Save').'" '.
 3735: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
 3736:     if (scalar(%$fullname) eq 0) {
 3737: 	my $colspan=3+scalar(@parts);
 3738: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3739:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 3740: 	$result='<span class="LC_warning">'.
 3741: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 3742: 	        $section_display, $stu_status).
 3743: 	    '</span>';
 3744:     }
 3745:     return $result;
 3746: }
 3747: 
 3748: #--- call by previous routine to display each student
 3749: sub viewstudentgrade {
 3750:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 3751:     my ($uname,$udom) = split(/:/,$student);
 3752:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 3753:     my %aggregates = (); 
 3754:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 3755: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
 3756: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
 3757: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 3758: 	'\');" target="_self">'.$fullname.'</a> '.
 3759: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 3760:     $student=~s/:/_/; # colon doen't work in javascript for names
 3761:     foreach my $apart (@$parts) {
 3762: 	my ($part,$type) = &split_part_type($apart);
 3763: 	my $score=$record{"resource.$part.$type"};
 3764:         $result.='<td align="center">';
 3765:         my ($aggtries,$totaltries);
 3766:         unless (exists($aggregates{$part})) {
 3767: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 3768: 
 3769: 	    $aggtries = $totaltries;
 3770:             if ($$last_resets{$part}) {  
 3771:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 3772: 					   $part);
 3773:             }
 3774:             $result.='<input type="hidden" name="'.
 3775:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 3776:             $result.='<input type="hidden" name="'.
 3777:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 3778:             $aggregates{$part} = 1;
 3779:         }
 3780: 	if ($type eq 'awarded') {
 3781: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 3782: 	    $result.='<input type="hidden" name="'.
 3783: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 3784: 	    $result.='<input type="text" name="'.
 3785: 		'GD_'.$student.'_'.$part.'_awarded" '.
 3786:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
 3787: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 3788: 	} elsif ($type eq 'solved') {
 3789: 	    my ($status,$foo)=split(/_/,$score,2);
 3790: 	    $status = 'nothing' if ($status eq '');
 3791: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 3792: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 3793: 	    $result.='&nbsp;<select name="'.
 3794: 		'GD_'.$student.'_'.$part.'_solved" '.
 3795:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 3796: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 3797: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 3798: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 3799: 	    $result.="</select>&nbsp;</td>\n";
 3800: 	} else {
 3801: 	    $result.='<input type="hidden" name="'.
 3802: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 3803: 		    "\n";
 3804: 	    $result.='<input type="text" name="'.
 3805: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 3806: 		'value="'.$score.'" size="4" /></td>'."\n";
 3807: 	}
 3808:     }
 3809:     $result.=&Apache::loncommon::end_data_table_row();
 3810:     return $result;
 3811: }
 3812: 
 3813: #--- change scores for all the students in a section/class
 3814: #    record does not get update if unchanged
 3815: sub editgrades {
 3816:     my ($request,$symb) = @_;
 3817: 
 3818:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3819:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 3820:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
 3821: 
 3822:     my $result= &Apache::loncommon::start_data_table().
 3823: 	&Apache::loncommon::start_data_table_header_row().
 3824: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 3825: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 3826:     my %scoreptr = (
 3827: 		    'correct'  =>'correct_by_override',
 3828: 		    'incorrect'=>'incorrect_by_override',
 3829: 		    'excused'  =>'excused',
 3830: 		    'ungraded' =>'ungraded_attempted',
 3831:                     'credited' =>'credit_attempted',
 3832: 		    'nothing'  => '',
 3833: 		    );
 3834:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 3835: 
 3836:     my (@partid);
 3837:     my %weight = ();
 3838:     my %columns = ();
 3839:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 3840: 
 3841:     my $partserror;
 3842:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3843:     if ($partserror) {
 3844:         return &navmap_errormsg();
 3845:     }
 3846:     my $header;
 3847:     while ($ctr < $env{'form.totalparts'}) {
 3848: 	my $partid = $env{'form.partid_'.$ctr};
 3849: 	push(@partid,$partid);
 3850: 	$weight{$partid} = $env{'form.weight_'.$partid};
 3851: 	$ctr++;
 3852:     }
 3853:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3854:     foreach my $partid (@partid) {
 3855: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 3856: 	    '<th align="center">'.&mt('New Score').'</th>';
 3857: 	$columns{$partid}=2;
 3858: 	foreach my $stores (@parts) {
 3859: 	    my ($part,$type) = &split_part_type($stores);
 3860: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 3861: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 3862: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 3863: 	    $display =~ s/\[Part: \Q$part\E\]//;
 3864:             my $narrowtext = &mt('Tries');
 3865: 	    $display =~ s/Number of Attempts/$narrowtext/;
 3866: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 3867: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 3868: 	    $columns{$partid}+=2;
 3869: 	}
 3870:     }
 3871:     foreach my $partid (@partid) {
 3872: 	my $display_part=&get_display_part($partid,$symb);
 3873: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 3874: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 3875: 	    '</th>';
 3876: 
 3877:     }
 3878:     $result .= &Apache::loncommon::end_data_table_header_row().
 3879: 	&Apache::loncommon::start_data_table_header_row().
 3880: 	$header.
 3881: 	&Apache::loncommon::end_data_table_header_row();
 3882:     my @noupdate;
 3883:     my ($updateCtr,$noupdateCtr) = (1,1);
 3884:     for ($i=0; $i<$env{'form.total'}; $i++) {
 3885: 	my $line;
 3886: 	my $user = $env{'form.ctr'.$i};
 3887: 	my ($uname,$udom)=split(/:/,$user);
 3888: 	my %newrecord;
 3889: 	my $updateflag = 0;
 3890: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 3891: 	my $usec=$classlist->{"$uname:$udom"}[5];
 3892: 	if (!&canmodify($usec)) {
 3893: 	    my $numcols=scalar(@partid)*4+2;
 3894: 	    push(@noupdate,
 3895: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
 3896: 		 &mt('Not allowed to modify student')."</span></td></tr>");
 3897: 	    next;
 3898: 	}
 3899:         my %aggregate = ();
 3900:         my $aggregateflag = 0;
 3901: 	$user=~s/:/_/; # colon doen't work in javascript for names
 3902: 	foreach (@partid) {
 3903: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 3904: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 3905: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 3906: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3907: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 3908: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 3909: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 3910: 	    my $score;
 3911: 	    if ($partial eq '') {
 3912: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3913: 	    } elsif ($partial > 0) {
 3914: 		$score = 'correct_by_override';
 3915: 	    } elsif ($partial == 0) {
 3916: 		$score = 'incorrect_by_override';
 3917: 	    }
 3918: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 3919: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 3920: 
 3921: 	    $newrecord{'resource.'.$_.'.regrader'}=
 3922: 		"$env{'user.name'}:$env{'user.domain'}";
 3923: 	    if ($dropMenu eq 'reset status' &&
 3924: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 3925: 		$newrecord{'resource.'.$_.'.tries'} = '';
 3926: 		$newrecord{'resource.'.$_.'.solved'} = '';
 3927: 		$newrecord{'resource.'.$_.'.award'} = '';
 3928: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 3929: 		$updateflag = 1;
 3930:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 3931:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 3932:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 3933:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 3934:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3935:                     $aggregateflag = 1;
 3936:                 }
 3937: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 3938: 		$updateflag = 1;
 3939: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 3940: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 3941: 		$rec_update++;
 3942: 	    }
 3943: 
 3944: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3945: 		'<td align="center">'.$awarded.
 3946: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 3947: 
 3948: 
 3949: 	    my $partid=$_;
 3950: 	    foreach my $stores (@parts) {
 3951: 		my ($part,$type) = &split_part_type($stores);
 3952: 		if ($part !~ m/^\Q$partid\E/) { next;}
 3953: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 3954: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 3955: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 3956: 		if ($awarded ne '' && $awarded ne $old_aw) {
 3957: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 3958: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3959: 		    $updateflag=1;
 3960: 		}
 3961: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3962: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 3963: 	    }
 3964: 	}
 3965: 	$line.="\n";
 3966: 
 3967: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3968: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3969: 
 3970: 	if ($updateflag) {
 3971: 	    $count++;
 3972: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 3973: 				    $udom,$uname);
 3974: 
 3975: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 3976: 					      $cnum,$udom,$uname)) {
 3977: 		# need to figure out if should be in queue.
 3978: 		my %record =  
 3979: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 3980: 					     $udom,$uname);
 3981: 		my $all_graded = 1;
 3982: 		my $none_graded = 1;
 3983: 		foreach my $part (@parts) {
 3984: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 3985: 			$all_graded = 0;
 3986: 		    } else {
 3987: 			$none_graded = 0;
 3988: 		    }
 3989: 		}
 3990: 
 3991: 		if ($all_graded || $none_graded) {
 3992: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 3993: 							   $symb,$cdom,$cnum,
 3994: 							   $udom,$uname);
 3995: 		}
 3996: 	    }
 3997: 
 3998: 	    $result.=&Apache::loncommon::start_data_table_row().
 3999: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 4000: 		&Apache::loncommon::end_data_table_row();
 4001: 	    $updateCtr++;
 4002: 	} else {
 4003: 	    push(@noupdate,
 4004: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 4005: 	    $noupdateCtr++;
 4006: 	}
 4007:         if ($aggregateflag) {
 4008:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4009: 				  $cdom,$cnum);
 4010:         }
 4011:     }
 4012:     if (@noupdate) {
 4013: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
 4014: 	my $numcols=scalar(@partid)*4+2;
 4015: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 4016: 	    '<td align="center" colspan="'.$numcols.'">'.
 4017: 	    &mt('No Changes Occurred For the Students Below').
 4018: 	    '</td>'.
 4019: 	    &Apache::loncommon::end_data_table_row();
 4020: 	foreach my $line (@noupdate) {
 4021: 	    $result.=
 4022: 		&Apache::loncommon::start_data_table_row().
 4023: 		$line.
 4024: 		&Apache::loncommon::end_data_table_row();
 4025: 	}
 4026:     }
 4027:     $result .= &Apache::loncommon::end_data_table();
 4028:     my $msg = '<p><b>'.
 4029: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 4030: 	    $rec_update,$count).'</b><br />'.
 4031: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 4032: 	'</b></p>';
 4033:     return $title.$msg.$result;
 4034: }
 4035: 
 4036: sub split_part_type {
 4037:     my ($partstr) = @_;
 4038:     my ($temp,@allparts)=split(/_/,$partstr);
 4039:     my $type=pop(@allparts);
 4040:     my $part=join('_',@allparts);
 4041:     return ($part,$type);
 4042: }
 4043: 
 4044: #------------- end of section for handling grading by section/class ---------
 4045: #
 4046: #----------------------------------------------------------------------------
 4047: 
 4048: 
 4049: #----------------------------------------------------------------------------
 4050: #
 4051: #-------------------------- Next few routines handles grading by csv upload
 4052: #
 4053: #--- Javascript to handle csv upload
 4054: sub csvupload_javascript_reverse_associate {
 4055:     my $error1=&mt('You need to specify the username or the student/employee ID');
 4056:     my $error2=&mt('You need to specify at least one grading field');
 4057:   return(<<ENDPICK);
 4058:   function verify(vf) {
 4059:     var foundsomething=0;
 4060:     var founduname=0;
 4061:     var foundID=0;
 4062:     for (i=0;i<=vf.nfields.value;i++) {
 4063:       tw=eval('vf.f'+i+'.selectedIndex');
 4064:       if (i==0 && tw!=0) { foundID=1; }
 4065:       if (i==1 && tw!=0) { founduname=1; }
 4066:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 4067:     }
 4068:     if (founduname==0 && foundID==0) {
 4069: 	alert('$error1');
 4070: 	return;
 4071:     }
 4072:     if (foundsomething==0) {
 4073: 	alert('$error2');
 4074: 	return;
 4075:     }
 4076:     vf.submit();
 4077:   }
 4078:   function flip(vf,tf) {
 4079:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4080:     var i;
 4081:     for (i=0;i<=vf.nfields.value;i++) {
 4082:       //can not pick the same destination field for both name and domain
 4083:       if (((i ==0)||(i ==1)) && 
 4084:           ((tf==0)||(tf==1)) && 
 4085:           (i!=tf) &&
 4086:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4087:         eval('vf.f'+i+'.selectedIndex=0;')
 4088:       }
 4089:     }
 4090:   }
 4091: ENDPICK
 4092: }
 4093: 
 4094: sub csvupload_javascript_forward_associate {
 4095:     my $error1=&mt('You need to specify the username or the student/employee ID');
 4096:     my $error2=&mt('You need to specify at least one grading field');
 4097:   return(<<ENDPICK);
 4098:   function verify(vf) {
 4099:     var foundsomething=0;
 4100:     var founduname=0;
 4101:     var foundID=0;
 4102:     for (i=0;i<=vf.nfields.value;i++) {
 4103:       tw=eval('vf.f'+i+'.selectedIndex');
 4104:       if (tw==1) { foundID=1; }
 4105:       if (tw==2) { founduname=1; }
 4106:       if (tw>3) { foundsomething=1; }
 4107:     }
 4108:     if (founduname==0 && foundID==0) {
 4109: 	alert('$error1');
 4110: 	return;
 4111:     }
 4112:     if (foundsomething==0) {
 4113: 	alert('$error2');
 4114: 	return;
 4115:     }
 4116:     vf.submit();
 4117:   }
 4118:   function flip(vf,tf) {
 4119:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4120:     var i;
 4121:     //can not pick the same destination field twice
 4122:     for (i=0;i<=vf.nfields.value;i++) {
 4123:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4124:         eval('vf.f'+i+'.selectedIndex=0;')
 4125:       }
 4126:     }
 4127:   }
 4128: ENDPICK
 4129: }
 4130: 
 4131: sub csvuploadmap_header {
 4132:     my ($request,$symb,$datatoken,$distotal)= @_;
 4133:     my $javascript;
 4134:     if ($env{'form.upfile_associate'} eq 'reverse') {
 4135: 	$javascript=&csvupload_javascript_reverse_associate();
 4136:     } else {
 4137: 	$javascript=&csvupload_javascript_forward_associate();
 4138:     }
 4139: 
 4140:     $symb = &Apache::lonenc::check_encrypt($symb);
 4141:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
 4142:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
 4143:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
 4144:     my $reverse=&mt("Reverse Association");
 4145:     $request->print(<<ENDPICK);
 4146: <br />
 4147: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 4148: <input type="hidden" name="associate"  value="" />
 4149: <input type="hidden" name="phase"      value="three" />
 4150: <input type="hidden" name="datatoken"  value="$datatoken" />
 4151: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 4152: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 4153: <input type="hidden" name="upfile_associate" 
 4154:                                        value="$env{'form.upfile_associate'}" />
 4155: <input type="hidden" name="symb"       value="$symb" />
 4156: <input type="hidden" name="command"    value="csvuploadoptions" />
 4157: <hr />
 4158: ENDPICK
 4159:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
 4160:     return '';
 4161: 
 4162: }
 4163: 
 4164: sub csvupload_fields {
 4165:     my ($symb,$errorref) = @_;
 4166:     my (@parts) = &getpartlist($symb,$errorref);
 4167:     if (ref($errorref)) {
 4168:         if ($$errorref) {
 4169:             return;
 4170:         }
 4171:     }
 4172: 
 4173:     my @fields=(['ID','Student/Employee ID'],
 4174: 		['username','Student Username'],
 4175: 		['domain','Student Domain']);
 4176:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 4177:     foreach my $part (sort(@parts)) {
 4178: 	my @datum;
 4179: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 4180: 	my $name=$part;
 4181: 	if  (!$display) { $display = $name; }
 4182: 	@datum=($name,$display);
 4183: 	if ($name=~/^stores_(.*)_awarded/) {
 4184: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 4185: 	}
 4186: 	push(@fields,\@datum);
 4187:     }
 4188:     return (@fields);
 4189: }
 4190: 
 4191: sub csvuploadmap_footer {
 4192:     my ($request,$i,$keyfields) =@_;
 4193:     my $buttontext = &mt('Assign Grades');
 4194:     $request->print(<<ENDPICK);
 4195: </table>
 4196: <input type="hidden" name="nfields" value="$i" />
 4197: <input type="hidden" name="keyfields" value="$keyfields" />
 4198: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
 4199: </form>
 4200: ENDPICK
 4201: }
 4202: 
 4203: sub checkforfile_js {
 4204:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 4205:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
 4206:     function checkUpload(formname) {
 4207: 	if (formname.upfile.value == "") {
 4208: 	    alert("$alertmsg");
 4209: 	    return false;
 4210: 	}
 4211: 	formname.submit();
 4212:     }
 4213: CSVFORMJS
 4214:     return $result;
 4215: }
 4216: 
 4217: sub upcsvScores_form {
 4218:     my ($request,$symb) = @_;
 4219:     if (!$symb) {return '';}
 4220:     my $result=&checkforfile_js();
 4221:     $result.=&Apache::loncommon::start_data_table().
 4222:              &Apache::loncommon::start_data_table_header_row().
 4223:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
 4224:              &Apache::loncommon::end_data_table_header_row().
 4225:              &Apache::loncommon::start_data_table_row().'<td>';
 4226:     my $upload=&mt("Upload Scores");
 4227:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 4228:     my $ignore=&mt('Ignore First Line');
 4229:     $symb = &Apache::lonenc::check_encrypt($symb);
 4230:     $result.=<<ENDUPFORM;
 4231: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4232: <input type="hidden" name="symb" value="$symb" />
 4233: <input type="hidden" name="command" value="csvuploadmap" />
 4234: $upfile_select
 4235: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 4236: </form>
 4237: ENDUPFORM
 4238:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 4239:                            &mt("How do I create a CSV file from a spreadsheet")).
 4240:              '</td>'.
 4241:             &Apache::loncommon::end_data_table_row().
 4242:             &Apache::loncommon::end_data_table();
 4243:     return $result;
 4244: }
 4245: 
 4246: 
 4247: sub csvuploadmap {
 4248:     my ($request,$symb)= @_;
 4249:     if (!$symb) {return '';}
 4250: 
 4251:     my $datatoken;
 4252:     if (!$env{'form.datatoken'}) {
 4253: 	$datatoken=&Apache::loncommon::upfile_store($request);
 4254:     } else {
 4255: 	$datatoken=$env{'form.datatoken'};
 4256: 	&Apache::loncommon::load_tmp_file($request);
 4257:     }
 4258:     my @records=&Apache::loncommon::upfile_record_sep();
 4259:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 4260:     my ($i,$keyfields);
 4261:     if (@records) {
 4262:         my $fieldserror;
 4263: 	my @fields=&csvupload_fields($symb,\$fieldserror);
 4264:         if ($fieldserror) {
 4265:             $request->print(&navmap_errormsg());
 4266:             return;
 4267:         }
 4268: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 4269: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 4270: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 4271: 							  \@fields);
 4272: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 4273: 	    chop($keyfields);
 4274: 	} else {
 4275: 	    unshift(@fields,['none','']);
 4276: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 4277: 							    \@fields);
 4278:             foreach my $rec (@records) {
 4279:                 my %temp = &Apache::loncommon::record_sep($rec);
 4280:                 if (%temp) {
 4281:                     $keyfields=join(',',sort(keys(%temp)));
 4282:                     last;
 4283:                 }
 4284:             }
 4285: 	}
 4286:     }
 4287:     &csvuploadmap_footer($request,$i,$keyfields);
 4288: 
 4289:     return '';
 4290: }
 4291: 
 4292: sub csvuploadoptions {
 4293:     my ($request,$symb)= @_;
 4294:     my $overwrite=&mt('Overwrite any existing score');
 4295:     $request->print(<<ENDPICK);
 4296: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4297: <input type="hidden" name="command"    value="csvuploadassign" />
 4298: <p>
 4299: <label>
 4300:    <input type="checkbox" name="overwite_scores" checked="checked" />
 4301:    $overwrite
 4302: </label>
 4303: </p>
 4304: ENDPICK
 4305:     my %fields=&get_fields();
 4306:     if (!defined($fields{'domain'})) {
 4307: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 4308: 	$request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
 4309:     }
 4310:     foreach my $key (sort(keys(%env))) {
 4311: 	if ($key !~ /^form\.(.*)$/) { next; }
 4312: 	my $cleankey=$1;
 4313: 	if ($cleankey eq 'command') { next; }
 4314: 	$request->print('<input type="hidden" name="'.$cleankey.
 4315: 			'"  value="'.$env{$key}.'" />'."\n");
 4316:     }
 4317:     # FIXME do a check for any duplicated user ids...
 4318:     # FIXME do a check for any invalid user ids?...
 4319:     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
 4320: <hr /></form>'."\n");
 4321:     return '';
 4322: }
 4323: 
 4324: sub get_fields {
 4325:     my %fields;
 4326:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 4327:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 4328: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 4329: 	    if ($env{'form.f'.$i} ne 'none') {
 4330: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 4331: 	    }
 4332: 	} else {
 4333: 	    if ($env{'form.f'.$i} ne 'none') {
 4334: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 4335: 	    }
 4336: 	}
 4337:     }
 4338:     return %fields;
 4339: }
 4340: 
 4341: sub csvuploadassign {
 4342:     my ($request,$symb)= @_;
 4343:     if (!$symb) {return '';}
 4344:     my $error_msg = '';
 4345:     &Apache::loncommon::load_tmp_file($request);
 4346:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 4347:     my %fields=&get_fields();
 4348:     my $courseid=$env{'request.course.id'};
 4349:     my ($classlist) = &getclasslist('all',0);
 4350:     my @notallowed;
 4351:     my @skipped;
 4352:     my @warnings;
 4353:     my $countdone=0;
 4354:     foreach my $grade (@gradedata) {
 4355: 	my %entries=&Apache::loncommon::record_sep($grade);
 4356: 	my $domain;
 4357: 	if ($entries{$fields{'domain'}}) {
 4358: 	    $domain=$entries{$fields{'domain'}};
 4359: 	} else {
 4360: 	    $domain=$env{'form.default_domain'};
 4361: 	}
 4362: 	$domain=~s/\s//g;
 4363: 	my $username=$entries{$fields{'username'}};
 4364: 	$username=~s/\s//g;
 4365: 	if (!$username) {
 4366: 	    my $id=$entries{$fields{'ID'}};
 4367: 	    $id=~s/\s//g;
 4368: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 4369: 	    $username=$ids{$id};
 4370: 	}
 4371: 	if (!exists($$classlist{"$username:$domain"})) {
 4372: 	    my $id=$entries{$fields{'ID'}};
 4373: 	    $id=~s/\s//g;
 4374: 	    if ($id) {
 4375: 		push(@skipped,"$id:$domain");
 4376: 	    } else {
 4377: 		push(@skipped,"$username:$domain");
 4378: 	    }
 4379: 	    next;
 4380: 	}
 4381: 	my $usec=$classlist->{"$username:$domain"}[5];
 4382: 	if (!&canmodify($usec)) {
 4383: 	    push(@notallowed,"$username:$domain");
 4384: 	    next;
 4385: 	}
 4386: 	my %points;
 4387: 	my %grades;
 4388: 	foreach my $dest (keys(%fields)) {
 4389: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 4390: 		$dest eq 'domain') { next; }
 4391: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 4392: 	    if ($dest=~/stores_(.*)_points/) {
 4393: 		my $part=$1;
 4394: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 4395: 					      $symb,$domain,$username);
 4396:                 if ($wgt) {
 4397:                     $entries{$fields{$dest}}=~s/\s//g;
 4398:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 4399:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 4400:                                           : 'correct_by_override';
 4401:                     if ($pcr>1) {
 4402:                        push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
 4403:                     }
 4404:                     $grades{"resource.$part.awarded"}=$pcr;
 4405:                     $grades{"resource.$part.solved"}=$award;
 4406:                     $points{$part}=1;
 4407:                 } else {
 4408:                     $error_msg = "<br />" .
 4409:                         &mt("Some point values were assigned"
 4410:                             ." for problems with a weight "
 4411:                             ."of zero. These values were "
 4412:                             ."ignored.");
 4413:                 }
 4414: 	    } else {
 4415: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 4416: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 4417: 		my $store_key=$dest;
 4418: 		$store_key=~s/^stores/resource/;
 4419: 		$store_key=~s/_/\./g;
 4420: 		$grades{$store_key}=$entries{$fields{$dest}};
 4421: 	    }
 4422: 	}
 4423: 	if (! %grades) { 
 4424:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 4425:         } else {
 4426: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 4427: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 4428: 					   $env{'request.course.id'},
 4429: 					   $domain,$username);
 4430: 	   if ($result eq 'ok') {
 4431: # Successfully stored
 4432: 	      $request->print('.');
 4433: # Remove from grading queue
 4434:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
 4435:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
 4436:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
 4437:                                              $domain,$username);
 4438:               $countdone++;
 4439:            } else {
 4440: 	      $request->print("<p><span class=\"LC_error\">".
 4441:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 4442:                                   "$username:$domain",$result)."</span></p>");
 4443: 	   }
 4444: 	   $request->rflush();
 4445:         }
 4446:     }
 4447:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
 4448:     if (@warnings) {
 4449:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
 4450:         $request->print(join(', ',@warnings));
 4451:     }
 4452:     if (@skipped) {
 4453: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
 4454:         $request->print(join(', ',@skipped));
 4455:     }
 4456:     if (@notallowed) {
 4457: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
 4458: 	$request->print(join(', ',@notallowed));
 4459:     }
 4460:     $request->print("<br />\n");
 4461:     return $error_msg;
 4462: }
 4463: #------------- end of section for handling csv file upload ---------
 4464: #
 4465: #-------------------------------------------------------------------
 4466: #
 4467: #-------------- Next few routines handle grading by page/sequence
 4468: #
 4469: #--- Select a page/sequence and a student to grade
 4470: sub pickStudentPage {
 4471:     my ($request,$symb) = @_;
 4472: 
 4473:     my $alertmsg = &mt('Please select the student you wish to grade.');
 4474:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
 4475: 
 4476: function checkPickOne(formname) {
 4477:     if (radioSelection(formname.student) == null) {
 4478: 	alert("$alertmsg");
 4479: 	return;
 4480:     }
 4481:     ptr = pullDownSelection(formname.selectpage);
 4482:     formname.page.value = formname["page"+ptr].value;
 4483:     formname.title.value = formname["title"+ptr].value;
 4484:     formname.submit();
 4485: }
 4486: 
 4487: LISTJAVASCRIPT
 4488:     &commonJSfunctions($request);
 4489: 
 4490:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4491:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4492:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4493: 
 4494:     my $result='<h3><span class="LC_info">&nbsp;'.
 4495: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 4496: 
 4497:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 4498:     my $map_error;
 4499:     my ($titles,$symbx) = &getSymbMap($map_error);
 4500:     if ($map_error) {
 4501:         $request->print(&navmap_errormsg());
 4502:         return; 
 4503:     }
 4504:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 4505: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 4506: #    my $type=($curpage =~ /\.(page|sequence)/);
 4507: 
 4508:     # Collection of hidden fields
 4509:     my $ctr=0;
 4510:     foreach (@$titles) {
 4511:         my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4512:         $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 4513:         $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 4514:         $ctr++;
 4515:     }
 4516:     $result.='<input type="hidden" name="page" />'."\n".
 4517:         '<input type="hidden" name="title" />'."\n";
 4518: 
 4519:     $result.=&build_section_inputs();
 4520:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4521:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 4522: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 4523: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 4524: 
 4525:     # Show grading options
 4526:     $result.=&Apache::lonhtmlcommon::start_pick_box();
 4527:     my $select = '<select name="selectpage">'."\n";
 4528:     $ctr=0;
 4529:     foreach (@$titles) {
 4530: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4531: 	$select.='<option value="'.$ctr.'"'.
 4532: 	    ($$symbx{$_} =~ /$curpage$/ ? ' selected="selected"' : '').
 4533: 	    '>'.$showtitle.'</option>'."\n";
 4534: 	$ctr++;
 4535:     }
 4536:     $select.= '</select>';
 4537: 
 4538:     $result.=
 4539:         &Apache::lonhtmlcommon::row_title(&mt('Problems from'))
 4540:        .$select
 4541:        .&Apache::lonhtmlcommon::row_closure();
 4542: 
 4543:     $result.=
 4544:         &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
 4545:        .'<label><input type="radio" name="vProb" value="no"'
 4546:            .' checked="checked" /> '.&mt('no').' </label>'."\n"
 4547:        .'<label><input type="radio" name="vProb" value="yes" />'
 4548:            .&mt('yes').'</label>'."\n"
 4549:        .&Apache::lonhtmlcommon::row_closure();
 4550: 
 4551:     $result.=
 4552:         &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
 4553:        .'<label><input type="radio" name="lastSub" value="none" /> '
 4554:            .&mt('none').' </label>'."\n"
 4555:        .'<label><input type="radio" name="lastSub" value="datesub"'
 4556:            .' checked="checked" /> '.&mt('all submissions').'</label>'."\n"
 4557:        .'<label><input type="radio" name="lastSub" value="all" /> '
 4558:            .&mt('all submissions with details').' </label>'
 4559:        .&Apache::lonhtmlcommon::row_closure();
 4560:     
 4561:     $result.=
 4562:         &Apache::lonhtmlcommon::row_title(&mt('Use CODE'))
 4563:        .'<input type="text" name="CODE" value="" />'
 4564:        .&Apache::lonhtmlcommon::row_closure(1)
 4565:        .&Apache::lonhtmlcommon::end_pick_box();
 4566: 
 4567:     # Show list of students to select for grading
 4568:     $result.='<br /><input type="button" '.
 4569:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 4570: 
 4571:     $request->print($result);
 4572: 
 4573:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 4574: 	&Apache::loncommon::start_data_table().
 4575: 	&Apache::loncommon::start_data_table_header_row().
 4576: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4577: 	'<th>'.&nameUserString('header').'</th>'.
 4578: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4579: 	'<th>'.&nameUserString('header').'</th>'.
 4580: 	&Apache::loncommon::end_data_table_header_row();
 4581:  
 4582:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 4583:     my $ptr = 1;
 4584:     foreach my $student (sort 
 4585: 			 {
 4586: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4587: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4588: 			     }
 4589: 			     return $a cmp $b;
 4590: 			 } (keys(%$fullname))) {
 4591: 	my ($uname,$udom) = split(/:/,$student);
 4592: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 4593:                                   : '</td>');
 4594: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 4595: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 4596: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 4597: 	$studentTable.=
 4598: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 4599:                          : '');
 4600: 	$ptr++;
 4601:     }
 4602:     if ($ptr%2 == 0) {
 4603: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 4604: 	    &Apache::loncommon::end_data_table_row();
 4605:     }
 4606:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 4607:     $studentTable.='<input type="button" '.
 4608:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 4609: 
 4610:     $request->print($studentTable);
 4611: 
 4612:     return '';
 4613: }
 4614: 
 4615: sub getSymbMap {
 4616:     my ($map_error) = @_;
 4617:     my $navmap = Apache::lonnavmaps::navmap->new();
 4618:     unless (ref($navmap)) {
 4619:         if (ref($map_error)) {
 4620:             $$map_error = 'navmap';
 4621:         }
 4622:         return;
 4623:     }
 4624:     my %symbx = ();
 4625:     my @titles = ();
 4626:     my $minder = 0;
 4627: 
 4628:     # Gather every sequence that has problems.
 4629:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 4630: 					       1,0,1);
 4631:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 4632: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 4633: 	    my $title = $minder.'.'.
 4634: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 4635: 	    push(@titles, $title); # minder in case two titles are identical
 4636: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 4637: 	    $minder++;
 4638: 	}
 4639:     }
 4640:     return \@titles,\%symbx;
 4641: }
 4642: 
 4643: #
 4644: #--- Displays a page/sequence w/wo problems, w/wo submissions
 4645: sub displayPage {
 4646:     my ($request,$symb) = @_;
 4647:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4648:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4649:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4650:     my $pageTitle = $env{'form.page'};
 4651:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4652:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4653:     my $usec=$classlist->{$env{'form.student'}}[5];
 4654: 
 4655:     #need to make sure we have the correct data for later EXT calls, 
 4656:     #thus invalidate the cache
 4657:     &Apache::lonnet::devalidatecourseresdata(
 4658:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 4659:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 4660:     &Apache::lonnet::clear_EXT_cache_status();
 4661: 
 4662:     if (!&canview($usec)) {
 4663:         $request->print(
 4664:             '<span class="LC_warning">'.
 4665:             &mt('Unable to view requested student. ([_1])',
 4666:                     $env{'form.student'}).
 4667:             '</span>');
 4668:         return;
 4669:     }
 4670:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4671:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 4672: 	'</h3>'."\n";
 4673:     $env{'form.CODE'} = uc($env{'form.CODE'});
 4674:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 4675: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 4676:     } else {
 4677: 	delete($env{'form.CODE'});
 4678:     }
 4679:     &sub_page_js($request);
 4680:     $request->print($result);
 4681: 
 4682:     my $navmap = Apache::lonnavmaps::navmap->new();
 4683:     unless (ref($navmap)) {
 4684:         $request->print(&navmap_errormsg());
 4685:         return;
 4686:     }
 4687:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 4688:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4689:     if (!$map) {
 4690: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 4691: 	return; 
 4692:     }
 4693:     my $iterator = $navmap->getIterator($map->map_start(),
 4694: 					$map->map_finish());
 4695: 
 4696:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 4697: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 4698: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 4699: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 4700: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 4701: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 4702: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4703: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
 4704: 
 4705:     if (defined($env{'form.CODE'})) {
 4706: 	$studentTable.=
 4707: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 4708:     }
 4709:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 4710: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 4711: 
 4712:     $studentTable.='&nbsp;<span class="LC_info">'.
 4713:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
 4714:         '</span>'."\n".
 4715: 	&Apache::loncommon::start_data_table().
 4716: 	&Apache::loncommon::start_data_table_header_row().
 4717: 	'<th>'.&mt('Prob.').'</th>'.
 4718: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 4719: 	&Apache::loncommon::end_data_table_header_row();
 4720: 
 4721:     &Apache::lonxml::clear_problem_counter();
 4722:     my ($depth,$question,$prob) = (1,1,1);
 4723:     $iterator->next(); # skip the first BEGIN_MAP
 4724:     my $curRes = $iterator->next(); # for "current resource"
 4725:     while ($depth > 0) {
 4726:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4727:         if($curRes == $iterator->END_MAP) { $depth--; }
 4728: 
 4729:         if (ref($curRes) && $curRes->is_problem()) {
 4730: 	    my $parts = $curRes->parts();
 4731:             my $title = $curRes->compTitle();
 4732: 	    my $symbx = $curRes->symb();
 4733: 	    $studentTable.=
 4734: 		&Apache::loncommon::start_data_table_row().
 4735: 		'<td align="center" valign="top" >'.$prob.
 4736: 		(scalar(@{$parts}) == 1 ? '' 
 4737: 		                        : '<br />('.&mt('[_1]parts',
 4738: 							scalar(@{$parts}).'&nbsp;').')'
 4739: 		 ).
 4740: 		 '</td>';
 4741: 	    $studentTable.='<td valign="top">';
 4742: 	    my %form = ('CODE' => $env{'form.CODE'},);
 4743: 	    if ($env{'form.vProb'} eq 'yes' ) {
 4744: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 4745: 					     undef,'both',\%form);
 4746: 	    } else {
 4747: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 4748: 		$companswer =~ s|<form(.*?)>||g;
 4749: 		$companswer =~ s|</form>||g;
 4750: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 4751: #		    $companswer =~ s/$1/ /ms;
 4752: #		    $request->print('match='.$1."<br />\n");
 4753: #		}
 4754: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 4755: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 4756: 	    }
 4757: 
 4758: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 4759: 
 4760: 	    if ($env{'form.lastSub'} eq 'datesub') {
 4761: 		if ($record{'version'} eq '') {
 4762: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
 4763: 		} else {
 4764: 		    my %responseType = ();
 4765: 		    foreach my $partid (@{$parts}) {
 4766: 			my @responseIds =$curRes->responseIds($partid);
 4767: 			my @responseType =$curRes->responseType($partid);
 4768: 			my %responseIds;
 4769: 			for (my $i=0;$i<=$#responseIds;$i++) {
 4770: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 4771: 			}
 4772: 			$responseType{$partid} = \%responseIds;
 4773: 		    }
 4774: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 4775: 
 4776: 		}
 4777: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 4778: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 4779: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 4780: 									$env{'request.course.id'},
 4781: 									'','.submission');
 4782:  
 4783: 	    }
 4784: 	    if (&canmodify($usec)) {
 4785:             $studentTable.=&gradeBox_start();
 4786: 		foreach my $partid (@{$parts}) {
 4787: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 4788: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 4789: 		    $question++;
 4790: 		}
 4791:             $studentTable.=&gradeBox_end();
 4792: 		$prob++;
 4793: 	    }
 4794: 	    $studentTable.='</td></tr>';
 4795: 
 4796: 	}
 4797:         $curRes = $iterator->next();
 4798:     }
 4799: 
 4800:     $studentTable.=
 4801:         '</table>'."\n".
 4802:         '<input type="button" value="'.&mt('Save').'" '.
 4803:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 4804:         '</form>'."\n";
 4805:     $request->print($studentTable);
 4806: 
 4807:     return '';
 4808: }
 4809: 
 4810: sub displaySubByDates {
 4811:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 4812:     my $isCODE=0;
 4813:     my $isTask = ($symb =~/\.task$/);
 4814:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 4815:     my $studentTable=&Apache::loncommon::start_data_table().
 4816: 	&Apache::loncommon::start_data_table_header_row().
 4817: 	'<th>'.&mt('Date/Time').'</th>'.
 4818: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 4819:         ($isTask?'<th>'.&mt('Version').'</th>':'').
 4820: 	'<th>'.&mt('Submission').'</th>'.
 4821: 	'<th>'.&mt('Status').'</th>'.
 4822: 	&Apache::loncommon::end_data_table_header_row();
 4823:     my ($version);
 4824:     my %mark;
 4825:     my %orders;
 4826:     $mark{'correct_by_student'} = $checkIcon;
 4827:     if (!exists($$record{'1:timestamp'})) {
 4828: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 4829:     }
 4830: 
 4831:     my $interaction;
 4832:     my $no_increment = 1;
 4833:     my %lastrndseed;
 4834:     for ($version=1;$version<=$$record{'version'};$version++) {
 4835: 	my $timestamp = 
 4836: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 4837: 	if (exists($$record{$version.':resource.0.version'})) {
 4838: 	    $interaction = $$record{$version.':resource.0.version'};
 4839: 	}
 4840:         if ($isTask && $env{'form.previousversion'}) {
 4841:             next unless ($interaction == $env{'form.previousversion'});
 4842:         }
 4843: 	my $where = ($isTask ? "$version:resource.$interaction"
 4844: 		             : "$version:resource");
 4845: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 4846: 	    '<td>'.$timestamp.'</td>';
 4847: 	if ($isCODE) {
 4848: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 4849: 	}
 4850:         if ($isTask) {
 4851:             $studentTable.='<td>'.$interaction.'</td>';
 4852:         }
 4853: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 4854: 	my @displaySub = ();
 4855: 	foreach my $partid (@{$parts}) {
 4856:             my ($hidden,$type);
 4857:             $type = $$record{$version.':resource.'.$partid.'.type'};
 4858:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
 4859:                 $hidden = 1;
 4860:             }
 4861: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
 4862: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 4863: 	    
 4864: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 4865: 	    my $display_part=&get_display_part($partid,$symb);
 4866: 	    foreach my $matchKey (@matchKey) {
 4867: 		if (exists($$record{$version.':'.$matchKey}) &&
 4868: 		    $$record{$version.':'.$matchKey} ne '') {
 4869:                     
 4870: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 4871: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 4872:                     $displaySub[0].='<span class="LC_nobreak">';
 4873:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
 4874:                                    .' <span class="LC_internal_info">'
 4875:                                    .'('.&mt('Response ID: [_1]',$responseId).')'
 4876:                                    .'</span>'
 4877:                                    .' <b>';
 4878:                     if ($hidden) {
 4879:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
 4880:                     } else {
 4881:                         my ($trial,$rndseed,$newvariation);
 4882:                         if ($type eq 'randomizetry') {
 4883:                             $trial = $$record{"$where.$partid.tries"};
 4884:                             $rndseed = $$record{"$where.$partid.rndseed"};
 4885:                         }
 4886: 		        if ($$record{"$where.$partid.tries"} eq '') {
 4887: 			    $displaySub[0].=&mt('Trial not counted');
 4888: 		        } else {
 4889: 			    $displaySub[0].=&mt('Trial: [_1]',
 4890: 					    $$record{"$where.$partid.tries"});
 4891:                             if ($rndseed || $lastrndseed{$partid}) {
 4892:                                 if ($rndseed ne $lastrndseed{$partid}) {
 4893:                                     $newvariation = '&nbsp;('.&mt('New variation this try').')';
 4894:                                 }
 4895:                             }
 4896:                             $lastrndseed{$partid} = $rndseed;
 4897: 		        }
 4898: 		        my $responseType=($isTask ? 'Task'
 4899:                                               : $responseType->{$partid}->{$responseId});
 4900: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
 4901: 		        if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
 4902: 			    $orders{$partid}->{$responseId}=
 4903: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
 4904:                                            $no_increment,$type,$trial,$rndseed);
 4905: 		        }
 4906: 		        $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
 4907: 		        $displaySub[0].='&nbsp; '.
 4908: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
 4909:                     }
 4910: 		}
 4911: 	    }
 4912: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 4913: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 4914: 				    $$record{"$where.$partid.checkedin"},
 4915: 				    $$record{"$where.$partid.checkedin.slot"}).
 4916: 					'<br />';
 4917: 	    }
 4918: 	    if (exists $$record{"$where.$partid.award"}) {
 4919: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 4920: 		    lc($$record{"$where.$partid.award"}).' '.
 4921: 		    $mark{$$record{"$where.$partid.solved"}}.
 4922: 		    '<br />';
 4923: 	    }
 4924: 	    if (exists $$record{"$where.$partid.regrader"}) {
 4925: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 4926: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4927: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 4928: 		$displaySub[2].=
 4929: 		    $$record{"$version:resource.$partid.regrader"}.
 4930: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4931: 	    }
 4932: 	}
 4933: 	# needed because old essay regrader has not parts info
 4934: 	if (exists $$record{"$version:resource.regrader"}) {
 4935: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 4936: 	}
 4937: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 4938: 	if ($displaySub[2]) {
 4939: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 4940: 	}
 4941: 	$studentTable.='&nbsp;</td>'.
 4942: 	    &Apache::loncommon::end_data_table_row();
 4943:     }
 4944:     $studentTable.=&Apache::loncommon::end_data_table();
 4945:     return $studentTable;
 4946: }
 4947: 
 4948: sub updateGradeByPage {
 4949:     my ($request,$symb) = @_;
 4950: 
 4951:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4952:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4953:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4954:     my $pageTitle = $env{'form.page'};
 4955:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4956:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4957:     my $usec=$classlist->{$env{'form.student'}}[5];
 4958:     if (!&canmodify($usec)) {
 4959: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 4960: 	return;
 4961:     }
 4962:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4963:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 4964: 	'</h3>'."\n";
 4965: 
 4966:     $request->print($result);
 4967: 
 4968: 
 4969:     my $navmap = Apache::lonnavmaps::navmap->new();
 4970:     unless (ref($navmap)) {
 4971:         $request->print(&navmap_errormsg());
 4972:         return;
 4973:     }
 4974:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 4975:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4976:     if (!$map) {
 4977: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 4978: 	return; 
 4979:     }
 4980:     my $iterator = $navmap->getIterator($map->map_start(),
 4981: 					$map->map_finish());
 4982: 
 4983:     my $studentTable=
 4984: 	&Apache::loncommon::start_data_table().
 4985: 	&Apache::loncommon::start_data_table_header_row().
 4986: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 4987: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 4988: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 4989: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 4990: 	&Apache::loncommon::end_data_table_header_row();
 4991: 
 4992:     $iterator->next(); # skip the first BEGIN_MAP
 4993:     my $curRes = $iterator->next(); # for "current resource"
 4994:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
 4995:     while ($depth > 0) {
 4996:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4997:         if($curRes == $iterator->END_MAP) { $depth--; }
 4998: 
 4999:         if (ref($curRes) && $curRes->is_problem()) {
 5000: 	    my $parts = $curRes->parts();
 5001:             my $title = $curRes->compTitle();
 5002: 	    my $symbx = $curRes->symb();
 5003: 	    $studentTable.=
 5004: 		&Apache::loncommon::start_data_table_row().
 5005: 		'<td align="center" valign="top" >'.$prob.
 5006: 		(scalar(@{$parts}) == 1 ? '' 
 5007:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
 5008: 		.')').'</td>';
 5009: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 5010: 
 5011: 	    my %newrecord=();
 5012: 	    my @displayPts=();
 5013:             my %aggregate = ();
 5014:             my $aggregateflag = 0;
 5015: 	    foreach my $partid (@{$parts}) {
 5016: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 5017: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 5018: 
 5019: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 5020: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 5021: 		my $partial = $newpts/$wgt;
 5022: 		my $score;
 5023: 		if ($partial > 0) {
 5024: 		    $score = 'correct_by_override';
 5025: 		} elsif ($newpts ne '') { #empty is taken as 0
 5026: 		    $score = 'incorrect_by_override';
 5027: 		}
 5028: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 5029: 		if ($dropMenu eq 'excused') {
 5030: 		    $partial = '';
 5031: 		    $score = 'excused';
 5032: 		} elsif ($dropMenu eq 'reset status'
 5033: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 5034: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 5035: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 5036: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 5037: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 5038: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 5039: 		    $changeflag++;
 5040: 		    $newpts = '';
 5041:                     
 5042:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 5043:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 5044:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 5045:                     if ($aggtries > 0) {
 5046:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 5047:                         $aggregateflag = 1;
 5048:                     }
 5049: 		}
 5050: 		my $display_part=&get_display_part($partid,$curRes->symb());
 5051: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 5052: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5053: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 5054: 		    '&nbsp;<br />';
 5055: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5056: 		     (($score eq 'excused') ? 'excused' : $newpts).
 5057: 		    '&nbsp;<br />';
 5058: 		$question++;
 5059: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 5060: 
 5061: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 5062: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 5063: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 5064: 		    if (scalar(keys(%newrecord)) > 0);
 5065: 
 5066: 		$changeflag++;
 5067: 	    }
 5068: 	    if (scalar(keys(%newrecord)) > 0) {
 5069: 		my %record = 
 5070: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 5071: 					     $udom,$uname);
 5072: 
 5073: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 5074: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 5075: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 5076: 		    $newrecord{'resource.CODE'} = '';
 5077: 		}
 5078: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 5079: 					$udom,$uname);
 5080: 		%record = &Apache::lonnet::restore($symbx,
 5081: 						   $env{'request.course.id'},
 5082: 						   $udom,$uname);
 5083: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 5084: 					     $cdom,$cnum,$udom,$uname);
 5085: 	    }
 5086: 	    
 5087:             if ($aggregateflag) {
 5088:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 5089:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 5090:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 5091:             }
 5092: 
 5093: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 5094: 		'<td valign="top">'.$displayPts[1].'</td>'.
 5095: 		&Apache::loncommon::end_data_table_row();
 5096: 
 5097: 	    $prob++;
 5098: 	}
 5099:         $curRes = $iterator->next();
 5100:     }
 5101: 
 5102:     $studentTable.=&Apache::loncommon::end_data_table();
 5103:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 5104: 		  &mt('The scores were changed for [quant,_1,problem].',
 5105: 		  $changeflag));
 5106:     $request->print($grademsg.$studentTable);
 5107: 
 5108:     return '';
 5109: }
 5110: 
 5111: #-------- end of section for handling grading by page/sequence ---------
 5112: #
 5113: #-------------------------------------------------------------------
 5114: 
 5115: #-------------------- Bubblesheet (Scantron) Grading -------------------
 5116: #
 5117: #------ start of section for handling grading by page/sequence ---------
 5118: 
 5119: =pod
 5120: 
 5121: =head1 Bubble sheet grading routines
 5122: 
 5123:   For this documentation:
 5124: 
 5125:    'scanline' refers to the full line of characters
 5126:    from the file that we are parsing that represents one entire sheet
 5127: 
 5128:    'bubble line' refers to the data
 5129:    representing the line of bubbles that are on the physical bubblesheet
 5130: 
 5131: 
 5132: The overall process is that a scanned in bubblesheet data is uploaded
 5133: into a course. When a user wants to grade, they select a
 5134: sequence/folder of resources, a file of bubblesheet info, and pick
 5135: one of the predefined configurations for what each scanline looks
 5136: like.
 5137: 
 5138: Next each scanline is checked for any errors of either 'missing
 5139: bubbles' (it's an error because it may have been mis-scanned
 5140: because too light bubbling), 'double bubble' (each bubble line should
 5141: have no more than one letter picked), invalid or duplicated CODE,
 5142: invalid student/employee ID
 5143: 
 5144: If the CODE option is used that determines the randomization of the
 5145: homework problems, either way the student/employee ID is looked up into a
 5146: username:domain.
 5147: 
 5148: During the validation phase the instructor can choose to skip scanlines. 
 5149: 
 5150: After the validation phase, there are now 3 bubblesheet files
 5151: 
 5152:   scantron_original_filename (unmodified original file)
 5153:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 5154:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 5155: 
 5156: Also there is a separate hash nohist_scantrondata that contains extra
 5157: correction information that isn't representable in the bubblesheet
 5158: file (see &scantron_getfile() for more information)
 5159: 
 5160: After all scanlines are either valid, marked as valid or skipped, then
 5161: foreach line foreach problem in the picked sequence, an ssi request is
 5162: made that simulates a user submitting their selected letter(s) against
 5163: the homework problem.
 5164: 
 5165: =over 4
 5166: 
 5167: 
 5168: 
 5169: =item defaultFormData
 5170: 
 5171:   Returns html hidden inputs used to hold context/default values.
 5172: 
 5173:  Arguments:
 5174:   $symb - $symb of the current resource 
 5175: 
 5176: =cut
 5177: 
 5178: sub defaultFormData {
 5179:     my ($symb)=@_;
 5180:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />';
 5181: }
 5182: 
 5183: 
 5184: =pod 
 5185: 
 5186: =item getSequenceDropDown
 5187: 
 5188:    Return html dropdown of possible sequences to grade
 5189:  
 5190:  Arguments:
 5191:    $symb - $symb of the current resource
 5192:    $map_error - ref to scalar which will container error if
 5193:                 $navmap object is unavailable in &getSymbMap().
 5194: 
 5195: =cut
 5196: 
 5197: sub getSequenceDropDown {
 5198:     my ($symb,$map_error)=@_;
 5199:     my $result='<select name="selectpage">'."\n";
 5200:     my ($titles,$symbx) = &getSymbMap($map_error);
 5201:     if (ref($map_error)) {
 5202:         return if ($$map_error);
 5203:     }
 5204:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 5205:     my $ctr=0;
 5206:     foreach (@$titles) {
 5207: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 5208: 	$result.='<option value="'.$$symbx{$_}.'" '.
 5209: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 5210: 	    '>'.$showtitle.'</option>'."\n";
 5211: 	$ctr++;
 5212:     }
 5213:     $result.= '</select>';
 5214:     return $result;
 5215: }
 5216: 
 5217: my %bubble_lines_per_response;     # no. bubble lines for each response.
 5218:                                    # key is zero-based index - 0, 1, 2 ...
 5219: 
 5220: my %first_bubble_line;             # First bubble line no. for each bubble.
 5221: 
 5222: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 5223:                                    # matchresponse or rankresponse, where 
 5224:                                    # an individual response can have multiple 
 5225:                                    # lines
 5226: 
 5227: my %responsetype_per_response;     # responsetype for each response
 5228: 
 5229: my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
 5230:                                    # numbered response. Needed when randomorder
 5231:                                    # or randompick are in use. Key is ID, value 
 5232:                                    # is response number.
 5233: 
 5234: # Save and restore the bubble lines array to the form env.
 5235: 
 5236: 
 5237: sub save_bubble_lines {
 5238:     foreach my $line (keys(%bubble_lines_per_response)) {
 5239: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 5240: 	$env{"form.scantron.first_bubble_line.$line"} =
 5241: 	    $first_bubble_line{$line};
 5242:         $env{"form.scantron.sub_bubblelines.$line"} = 
 5243:             $subdivided_bubble_lines{$line};
 5244:         $env{"form.scantron.responsetype.$line"} =
 5245:             $responsetype_per_response{$line};
 5246:     }
 5247:     foreach my $resid (keys(%masterseq_id_responsenum)) {
 5248:         my $line = $masterseq_id_responsenum{$resid};
 5249:         $env{"form.scantron.residpart.$line"} = $resid;
 5250:     }
 5251: }
 5252: 
 5253: 
 5254: sub restore_bubble_lines {
 5255:     my $line = 0;
 5256:     %bubble_lines_per_response = ();
 5257:     %masterseq_id_responsenum = ();
 5258:     while ($env{"form.scantron.bubblelines.$line"}) {
 5259: 	my $value = $env{"form.scantron.bubblelines.$line"};
 5260: 	$bubble_lines_per_response{$line} = $value;
 5261: 	$first_bubble_line{$line}  =
 5262: 	    $env{"form.scantron.first_bubble_line.$line"};
 5263:         $subdivided_bubble_lines{$line} =
 5264:             $env{"form.scantron.sub_bubblelines.$line"};
 5265:         $responsetype_per_response{$line} =
 5266:             $env{"form.scantron.responsetype.$line"};
 5267:         my $id = $env{"form.scantron.residpart.$line"};
 5268:         $masterseq_id_responsenum{$id} = $line;
 5269: 	$line++;
 5270:     }
 5271: }
 5272: 
 5273: =pod 
 5274: 
 5275: =item scantron_filenames
 5276: 
 5277:    Returns a list of the scantron files in the current course 
 5278: 
 5279: =cut
 5280: 
 5281: sub scantron_filenames {
 5282:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5283:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5284:     my $getpropath = 1;
 5285:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
 5286:                                                         $cname,$getpropath);
 5287:     my @possiblenames;
 5288:     if (ref($dirlist) eq 'ARRAY') {
 5289:         foreach my $filename (sort(@{$dirlist})) {
 5290: 	    ($filename)=split(/&/,$filename);
 5291: 	    if ($filename!~/^scantron_orig_/) { next ; }
 5292: 	    $filename=~s/^scantron_orig_//;
 5293: 	    push(@possiblenames,$filename);
 5294:         }
 5295:     }
 5296:     return @possiblenames;
 5297: }
 5298: 
 5299: =pod 
 5300: 
 5301: =item scantron_uploads
 5302: 
 5303:    Returns  html drop-down list of scantron files in current course.
 5304: 
 5305:  Arguments:
 5306:    $file2grade - filename to set as selected in the dropdown
 5307: 
 5308: =cut
 5309: 
 5310: sub scantron_uploads {
 5311:     my ($file2grade) = @_;
 5312:     my $result=	'<select name="scantron_selectfile">';
 5313:     $result.="<option></option>";
 5314:     foreach my $filename (sort(&scantron_filenames())) {
 5315: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 5316:     }
 5317:     $result.="</select>";
 5318:     return $result;
 5319: }
 5320: 
 5321: =pod 
 5322: 
 5323: =item scantron_scantab
 5324: 
 5325:   Returns html drop down of the scantron formats in the scantronformat.tab
 5326:   file.
 5327: 
 5328: =cut
 5329: 
 5330: sub scantron_scantab {
 5331:     my $result='<select name="scantron_format">'."\n";
 5332:     $result.='<option></option>'."\n";
 5333:     my @lines = &get_scantronformat_file();
 5334:     if (@lines > 0) {
 5335:         foreach my $line (@lines) {
 5336:             next if (($line =~ /^\#/) || ($line eq ''));
 5337: 	    my ($name,$descrip)=split(/:/,$line);
 5338: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 5339:         }
 5340:     }
 5341:     $result.='</select>'."\n";
 5342:     return $result;
 5343: }
 5344: 
 5345: =pod
 5346: 
 5347: =item get_scantronformat_file
 5348: 
 5349:   Returns an array containing lines from the scantron format file for
 5350:   the domain of the course.
 5351: 
 5352:   If a url for a custom.tab file is listed in domain's configuration.db, 
 5353:   lines are from this file.
 5354: 
 5355:   Otherwise, if a default.tab has been published in RES space by the 
 5356:   domainconfig user, lines are from this file.
 5357: 
 5358:   Otherwise, fall back to getting lines from the legacy file on the
 5359:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
 5360: 
 5361: =cut
 5362: 
 5363: sub get_scantronformat_file {
 5364:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5365:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
 5366:     my $gottab = 0;
 5367:     my @lines;
 5368:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 5369:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 5370:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 5371:             if ($formatfile ne '-1') {
 5372:                 @lines = split("\n",$formatfile,-1);
 5373:                 $gottab = 1;
 5374:             }
 5375:         }
 5376:     }
 5377:     if (!$gottab) {
 5378:         my $confname = $cdom.'-domainconfig';
 5379:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 5380:         my $formatfile =  &Apache::lonnet::getfile($default);
 5381:         if ($formatfile ne '-1') {
 5382:             @lines = split("\n",$formatfile,-1);
 5383:             $gottab = 1;
 5384:         }
 5385:     }
 5386:     if (!$gottab) {
 5387:         my @domains = &Apache::lonnet::current_machine_domains();
 5388:         if (grep(/^\Q$cdom\E$/,@domains)) {
 5389:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 5390:             @lines = <$fh>;
 5391:             close($fh);
 5392:         } else {
 5393:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
 5394:             @lines = <$fh>;
 5395:             close($fh);
 5396:         }
 5397:     }
 5398:     return @lines;
 5399: }
 5400: 
 5401: =pod 
 5402: 
 5403: =item scantron_CODElist
 5404: 
 5405:   Returns html drop down of the saved CODE lists from current course,
 5406:   generated from earlier printings.
 5407: 
 5408: =cut
 5409: 
 5410: sub scantron_CODElist {
 5411:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5412:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5413:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 5414:     my $namechoice='<option></option>';
 5415:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 5416: 	if ($name =~ /^error: 2 /) { next; }
 5417: 	if ($name =~ /^type\0/) { next; }
 5418: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 5419:     }
 5420:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 5421:     return $namechoice;
 5422: }
 5423: 
 5424: =pod 
 5425: 
 5426: =item scantron_CODEunique
 5427: 
 5428:   Returns the html for "Each CODE to be used once" radio.
 5429: 
 5430: =cut
 5431: 
 5432: sub scantron_CODEunique {
 5433:     my $result='<span class="LC_nobreak">
 5434:                  <label><input type="radio" name="scantron_CODEunique"
 5435:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 5436:                 </span>
 5437:                 <span class="LC_nobreak">
 5438:                  <label><input type="radio" name="scantron_CODEunique"
 5439:                         value="no" />'.&mt('No').' </label>
 5440:                 </span>';
 5441:     return $result;
 5442: }
 5443: 
 5444: =pod 
 5445: 
 5446: =item scantron_selectphase
 5447: 
 5448:   Generates the initial screen to start the bubblesheet process.
 5449:   Allows for - starting a grading run.
 5450:              - downloading existing scan data (original, corrected
 5451:                                                 or skipped info)
 5452: 
 5453:              - uploading new scan data
 5454: 
 5455:  Arguments:
 5456:   $r          - The Apache request object
 5457:   $file2grade - name of the file that contain the scanned data to score
 5458: 
 5459: =cut
 5460: 
 5461: sub scantron_selectphase {
 5462:     my ($r,$file2grade,$symb) = @_;
 5463:     if (!$symb) {return '';}
 5464:     my $map_error;
 5465:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
 5466:     if ($map_error) {
 5467:         $r->print('<br />'.&navmap_errormsg().'<br />');
 5468:         return;
 5469:     }
 5470:     my $default_form_data=&defaultFormData($symb);
 5471:     my $file_selector=&scantron_uploads($file2grade);
 5472:     my $format_selector=&scantron_scantab();
 5473:     my $CODE_selector=&scantron_CODElist();
 5474:     my $CODE_unique=&scantron_CODEunique();
 5475:     my $result;
 5476: 
 5477:     $ssi_error = 0;
 5478: 
 5479:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 5480:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 5481: 
 5482: 	# Chunk of form to prompt for a scantron file upload.
 5483: 
 5484:         $r->print('
 5485:     <br />
 5486:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5487:        '.&Apache::loncommon::start_data_table_header_row().'
 5488:             <th>
 5489:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
 5490:             </th>
 5491:        '.&Apache::loncommon::end_data_table_header_row().'
 5492:        '.&Apache::loncommon::start_data_table_row().'
 5493:             <td>
 5494: ');
 5495:     my $default_form_data=&defaultFormData($symb);
 5496:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5497:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 5498:     $r->print(&Apache::lonhtmlcommon::scripttag('
 5499:     function checkUpload(formname) {
 5500: 	if (formname.upfile.value == "") {
 5501: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
 5502: 	    return false;
 5503: 	}
 5504: 	formname.submit();
 5505:     }'));
 5506:     $r->print('
 5507:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 5508:                 '.$default_form_data.'
 5509:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 5510:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 5511:                 <input name="command" value="scantronupload_save" type="hidden" />
 5512:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
 5513:                 <br />
 5514:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 5515:               </form>
 5516: ');
 5517: 
 5518:         $r->print('
 5519:             </td>
 5520:        '.&Apache::loncommon::end_data_table_row().'
 5521:        '.&Apache::loncommon::end_data_table().'
 5522: ');
 5523:     }
 5524: 
 5525:     # Chunk of form to prompt for a file to grade and how:
 5526: 
 5527:     $result.= '
 5528:     <br />
 5529:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 5530:     <input type="hidden" name="command" value="scantron_warning" />
 5531:     '.$default_form_data.'
 5532:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5533:        '.&Apache::loncommon::start_data_table_header_row().'
 5534:             <th colspan="2">
 5535:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 5536:             </th>
 5537:        '.&Apache::loncommon::end_data_table_header_row().'
 5538:        '.&Apache::loncommon::start_data_table_row().'
 5539:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 5540:        '.&Apache::loncommon::end_data_table_row().'
 5541:        '.&Apache::loncommon::start_data_table_row().'
 5542:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
 5543:        '.&Apache::loncommon::end_data_table_row().'
 5544:        '.&Apache::loncommon::start_data_table_row().'
 5545:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
 5546:        '.&Apache::loncommon::end_data_table_row().'
 5547:        '.&Apache::loncommon::start_data_table_row().'
 5548:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 5549:        '.&Apache::loncommon::end_data_table_row().'
 5550:        '.&Apache::loncommon::start_data_table_row().'
 5551:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 5552:        '.&Apache::loncommon::end_data_table_row().'
 5553:        '.&Apache::loncommon::start_data_table_row().'
 5554: 	    <td> '.&mt('Options:').' </td>
 5555:             <td>
 5556: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 5557:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 5558:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 5559: 	    </td>
 5560:        '.&Apache::loncommon::end_data_table_row().'
 5561:        '.&Apache::loncommon::start_data_table_row().'
 5562:             <td colspan="2">
 5563:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
 5564:             </td>
 5565:        '.&Apache::loncommon::end_data_table_row().'
 5566:     '.&Apache::loncommon::end_data_table().'
 5567:     </form>
 5568: ';
 5569:    
 5570:     $r->print($result);
 5571: 
 5572: 
 5573: 
 5574:     # Chunk of the form that prompts to view a scoring office file,
 5575:     # corrected file, skipped records in a file.
 5576: 
 5577:     $r->print('
 5578:    <br />
 5579:    <form action="/adm/grades" name="scantron_download">
 5580:      '.$default_form_data.'
 5581:      <input type="hidden" name="command" value="scantron_download" />
 5582:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5583:        '.&Apache::loncommon::start_data_table_header_row().'
 5584:               <th>
 5585:                 &nbsp;'.&mt('Download a scoring office file').'
 5586:               </th>
 5587:        '.&Apache::loncommon::end_data_table_header_row().'
 5588:        '.&Apache::loncommon::start_data_table_row().'
 5589:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 5590:                 <br />
 5591:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 5592:        '.&Apache::loncommon::end_data_table_row().'
 5593:      '.&Apache::loncommon::end_data_table().'
 5594:    </form>
 5595:    <br />
 5596: ');
 5597: 
 5598:     &Apache::lonpickcode::code_list($r,2);
 5599: 
 5600:     $r->print('<br /><form method="post" name="checkscantron" action="">'.
 5601:              $default_form_data."\n".
 5602:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 5603:              &Apache::loncommon::start_data_table_header_row()."\n".
 5604:              '<th colspan="2">
 5605:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
 5606:              '</th>'."\n".
 5607:               &Apache::loncommon::end_data_table_header_row()."\n".
 5608:               &Apache::loncommon::start_data_table_row()."\n".
 5609:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 5610:               '<td> '.$sequence_selector.' </td>'.
 5611:               &Apache::loncommon::end_data_table_row()."\n".
 5612:               &Apache::loncommon::start_data_table_row()."\n".
 5613:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 5614:               '<td> '.$file_selector.' </td>'."\n".
 5615:               &Apache::loncommon::end_data_table_row()."\n".
 5616:               &Apache::loncommon::start_data_table_row()."\n".
 5617:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 5618:               '<td> '.$format_selector.' </td>'."\n".
 5619:               &Apache::loncommon::end_data_table_row()."\n".
 5620:               &Apache::loncommon::start_data_table_row()."\n".
 5621:               '<td> '.&mt('Options').' </td>'."\n".
 5622:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
 5623:               &Apache::loncommon::end_data_table_row()."\n".
 5624:               &Apache::loncommon::start_data_table_row()."\n".
 5625:               '<td colspan="2">'."\n".
 5626:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 5627:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
 5628:               '</td>'."\n".
 5629:               &Apache::loncommon::end_data_table_row()."\n".
 5630:               &Apache::loncommon::end_data_table()."\n".
 5631:               '</form><br />');
 5632:     return;
 5633: }
 5634: 
 5635: =pod
 5636: 
 5637: =item get_scantron_config
 5638: 
 5639:    Parse and return the bubblesheet configuration line selected as a
 5640:    hash of configuration file fields.
 5641: 
 5642:  Arguments:
 5643:     which - the name of the configuration to parse from the file.
 5644: 
 5645: 
 5646:  Returns:
 5647:             If the named configuration is not in the file, an empty
 5648:             hash is returned.
 5649:     a hash with the fields
 5650:       name         - internal name for the this configuration setup
 5651:       description  - text to display to operator that describes this config
 5652:       CODElocation - if 0 or the string 'none'
 5653:                           - no CODE exists for this config
 5654:                      if -1 || the string 'letter'
 5655:                           - a CODE exists for this config and is
 5656:                             a string of letters
 5657:                      Unsupported value (but planned for future support)
 5658:                           if a positive integer
 5659:                                - The CODE exists as the first n items from
 5660:                                  the question section of the form
 5661:                           if the string 'number'
 5662:                                - The CODE exists for this config and is
 5663:                                  a string of numbers
 5664:       CODEstart   - (only matter if a CODE exists) column in the line where
 5665:                      the CODE starts
 5666:       CODElength  - length of the CODE
 5667:       IDstart     - column where the student/employee ID starts
 5668:       IDlength    - length of the student/employee ID info
 5669:       Qstart      - column where the information from the bubbled
 5670:                     'questions' start
 5671:       Qlength     - number of columns comprising a single bubble line from
 5672:                     the sheet. (usually either 1 or 10)
 5673:       Qon         - either a single character representing the character used
 5674:                     to signal a bubble was chosen in the positional setup, or
 5675:                     the string 'letter' if the letter of the chosen bubble is
 5676:                     in the final, or 'number' if a number representing the
 5677:                     chosen bubble is in the file (1->A 0->J)
 5678:       Qoff        - the character used to represent that a bubble was
 5679:                     left blank
 5680:       PaperID     - if the scanning process generates a unique number for each
 5681:                     sheet scanned the column that this ID number starts in
 5682:       PaperIDlength - number of columns that comprise the unique ID number
 5683:                       for the sheet of paper
 5684:       FirstName   - column that the first name starts in
 5685:       FirstNameLength - number of columns that the first name spans
 5686:  
 5687:       LastName    - column that the last name starts in
 5688:       LastNameLength - number of columns that the last name spans
 5689:       BubblesPerRow - number of bubbles available in each row used to 
 5690:                       bubble an answer. (If not specified, 10 assumed).
 5691: 
 5692: =cut
 5693: 
 5694: sub get_scantron_config {
 5695:     my ($which) = @_;
 5696:     my @lines = &get_scantronformat_file();
 5697:     my %config;
 5698:     #FIXME probably should move to XML it has already gotten a bit much now
 5699:     foreach my $line (@lines) {
 5700: 	my ($name,$descrip)=split(/:/,$line);
 5701: 	if ($name ne $which ) { next; }
 5702: 	chomp($line);
 5703: 	my @config=split(/:/,$line);
 5704: 	$config{'name'}=$config[0];
 5705: 	$config{'description'}=$config[1];
 5706: 	$config{'CODElocation'}=$config[2];
 5707: 	$config{'CODEstart'}=$config[3];
 5708: 	$config{'CODElength'}=$config[4];
 5709: 	$config{'IDstart'}=$config[5];
 5710: 	$config{'IDlength'}=$config[6];
 5711: 	$config{'Qstart'}=$config[7];
 5712:  	$config{'Qlength'}=$config[8];
 5713: 	$config{'Qoff'}=$config[9];
 5714: 	$config{'Qon'}=$config[10];
 5715: 	$config{'PaperID'}=$config[11];
 5716: 	$config{'PaperIDlength'}=$config[12];
 5717: 	$config{'FirstName'}=$config[13];
 5718: 	$config{'FirstNamelength'}=$config[14];
 5719: 	$config{'LastName'}=$config[15];
 5720: 	$config{'LastNamelength'}=$config[16];
 5721:         $config{'BubblesPerRow'}=$config[17];
 5722: 	last;
 5723:     }
 5724:     return %config;
 5725: }
 5726: 
 5727: =pod 
 5728: 
 5729: =item username_to_idmap
 5730: 
 5731:     creates a hash keyed by student/employee ID with values of the corresponding
 5732:     student username:domain.
 5733: 
 5734:   Arguments:
 5735: 
 5736:     $classlist - reference to the class list hash. This is a hash
 5737:                  keyed by student name:domain  whose elements are references
 5738:                  to arrays containing various chunks of information
 5739:                  about the student. (See loncoursedata for more info).
 5740: 
 5741:   Returns
 5742:     %idmap - the constructed hash
 5743: 
 5744: =cut
 5745: 
 5746: sub username_to_idmap {
 5747:     my ($classlist)= @_;
 5748:     my %idmap;
 5749:     foreach my $student (keys(%$classlist)) {
 5750: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
 5751: 	    $student;
 5752:     }
 5753:     return %idmap;
 5754: }
 5755: 
 5756: =pod
 5757: 
 5758: =item scantron_fixup_scanline
 5759: 
 5760:    Process a requested correction to a scanline.
 5761: 
 5762:   Arguments:
 5763:     $scantron_config   - hash from &get_scantron_config()
 5764:     $scan_data         - hash of correction information 
 5765:                           (see &scantron_getfile())
 5766:     $line              - existing scanline
 5767:     $whichline         - line number of the passed in scanline
 5768:     $field             - type of change to process 
 5769:                          (either 
 5770:                           'ID'     -> correct the student/employee ID
 5771:                           'CODE'   -> correct the CODE
 5772:                           'answer' -> fixup the submitted answers)
 5773:     
 5774:    $args               - hash of additional info,
 5775:                           - 'ID' 
 5776:                                'newid' -> studentID to use in replacement
 5777:                                           of existing one
 5778:                           - 'CODE' 
 5779:                                'CODE_ignore_dup' - set to true if duplicates
 5780:                                                    should be ignored.
 5781: 	                       'CODE' - is new code or 'use_unfound'
 5782:                                         if the existing unfound code should
 5783:                                         be used as is
 5784:                           - 'answer'
 5785:                                'response' - new answer or 'none' if blank
 5786:                                'question' - the bubble line to change
 5787:                                'questionnum' - the question identifier,
 5788:                                                may include subquestion. 
 5789: 
 5790:   Returns:
 5791:     $line - the modified scanline
 5792: 
 5793:   Side effects: 
 5794:     $scan_data - may be updated
 5795: 
 5796: =cut
 5797: 
 5798: 
 5799: sub scantron_fixup_scanline {
 5800:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 5801:     if ($field eq 'ID') {
 5802: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 5803: 	    return ($line,1,'New value too large');
 5804: 	}
 5805: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 5806: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 5807: 				     $args->{'newid'});
 5808: 	}
 5809: 	substr($line,$$scantron_config{'IDstart'}-1,
 5810: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 5811: 	if ($args->{'newid'}=~/^\s*$/) {
 5812: 	    &scan_data($scan_data,"$whichline.user",
 5813: 		       $args->{'username'}.':'.$args->{'domain'});
 5814: 	}
 5815:     } elsif ($field eq 'CODE') {
 5816: 	if ($args->{'CODE_ignore_dup'}) {
 5817: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 5818: 	}
 5819: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 5820: 	if ($args->{'CODE'} ne 'use_unfound') {
 5821: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 5822: 		return ($line,1,'New CODE value too large');
 5823: 	    }
 5824: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 5825: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 5826: 	    }
 5827: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 5828: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 5829: 	}
 5830:     } elsif ($field eq 'answer') {
 5831: 	my $length=$scantron_config->{'Qlength'};
 5832: 	my $off=$scantron_config->{'Qoff'};
 5833: 	my $on=$scantron_config->{'Qon'};
 5834: 	my $answer=${off}x$length;
 5835: 	if ($args->{'response'} eq 'none') {
 5836: 	    &scan_data($scan_data,
 5837: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 5838: 	} else {
 5839: 	    if ($on eq 'letter') {
 5840: 		my @alphabet=('A'..'Z');
 5841: 		$answer=$alphabet[$args->{'response'}];
 5842: 	    } elsif ($on eq 'number') {
 5843: 		$answer=$args->{'response'}+1;
 5844: 		if ($answer == 10) { $answer = '0'; }
 5845: 	    } else {
 5846: 		substr($answer,$args->{'response'},1)=$on;
 5847: 	    }
 5848: 	    &scan_data($scan_data,
 5849: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 5850: 	}
 5851: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 5852: 	substr($line,$where-1,$length)=$answer;
 5853:     }
 5854:     return $line;
 5855: }
 5856: 
 5857: =pod
 5858: 
 5859: =item scan_data
 5860: 
 5861:     Edit or look up  an item in the scan_data hash.
 5862: 
 5863:   Arguments:
 5864:     $scan_data  - The hash (see scantron_getfile)
 5865:     $key        - shorthand of the key to edit (actual key is
 5866:                   scantronfilename_key).
 5867:     $data        - New value of the hash entry.
 5868:     $delete      - If true, the entry is removed from the hash.
 5869: 
 5870:   Returns:
 5871:     The new value of the hash table field (undefined if deleted).
 5872: 
 5873: =cut
 5874: 
 5875: 
 5876: sub scan_data {
 5877:     my ($scan_data,$key,$value,$delete)=@_;
 5878:     my $filename=$env{'form.scantron_selectfile'};
 5879:     if (defined($value)) {
 5880: 	$scan_data->{$filename.'_'.$key} = $value;
 5881:     }
 5882:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 5883:     return $scan_data->{$filename.'_'.$key};
 5884: }
 5885: 
 5886: # ----- These first few routines are general use routines.----
 5887: 
 5888: # Return the number of occurences of a pattern in a string.
 5889: 
 5890: sub occurence_count {
 5891:     my ($string, $pattern) = @_;
 5892: 
 5893:     my @matches = ($string =~ /$pattern/g);
 5894: 
 5895:     return scalar(@matches);
 5896: }
 5897: 
 5898: 
 5899: # Take a string known to have digits and convert all the
 5900: # digits into letters in the range J,A..I.
 5901: 
 5902: sub digits_to_letters {
 5903:     my ($input) = @_;
 5904: 
 5905:     my @alphabet = ('J', 'A'..'I');
 5906: 
 5907:     my @input    = split(//, $input);
 5908:     my $output ='';
 5909:     for (my $i = 0; $i < scalar(@input); $i++) {
 5910: 	if ($input[$i] =~ /\d/) {
 5911: 	    $output .= $alphabet[$input[$i]];
 5912: 	} else {
 5913: 	    $output .= $input[$i];
 5914: 	}
 5915:     }
 5916:     return $output;
 5917: }
 5918: 
 5919: =pod 
 5920: 
 5921: =item scantron_parse_scanline
 5922: 
 5923:   Decodes a scanline from the selected bubblesheet file
 5924: 
 5925:  Arguments:
 5926:     line             - The text of the bubblesheet file line to process
 5927:     whichline        - Line number
 5928:     scantron_config  - Hash describing the format of the bubblesheet lines.
 5929:     scan_data        - Hash of extra information about the scanline
 5930:                        (see scantron_getfile for more information)
 5931:     just_header      - True if should not process question answers but only
 5932:                        the stuff to the left of the answers.
 5933:     randomorder      - True if randomorder in use
 5934:     randompick       - True if randompick in use
 5935:     sequence         - Exam folder URL
 5936:     master_seq       - Ref to array containing symbs in exam folder
 5937:     symb_to_resource - Ref to hash of symbs for resources in exam folder
 5938:                        (corresponding values are resource objects)
 5939:     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
 5940:     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
 5941:                        are refs to an array of resource objects, ordered
 5942:                        according to order used for CODE, when randomorder
 5943:                        and or randompick are in use.
 5944:     respnumlookup    - Ref to hash mapping question numbers in bubble lines
 5945:                        for current line to question number used for same question
 5946:                         in "Master Sequence" (as seen by Course Coordinator).
 5947:     startline        - Ref to hash where key is question number (0 is first)
 5948:                        and value is number of first bubble line for current 
 5949:                        student or code-based randompick and/or randomorder.
 5950:     totalref         - Ref of scalar used to score total number of bubble
 5951:                        lines needed for responses in a scan line (used when
 5952:                        randompick in use. 
 5953:     
 5954:  Returns:
 5955:    Hash containing the result of parsing the scanline
 5956: 
 5957:    Keys are all proceeded by the string 'scantron.'
 5958: 
 5959:        CODE    - the CODE in use for this scanline
 5960:        useCODE - 1 if the CODE is invalid but it usage has been forced
 5961:                  by the operator
 5962:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 5963:                             CODEs were selected, but the usage has been
 5964:                             forced by the operator
 5965:        ID  - student/employee ID
 5966:        PaperID - if used, the ID number printed on the sheet when the 
 5967:                  paper was scanned
 5968:        FirstName - first name from the sheet
 5969:        LastName  - last name from the sheet
 5970: 
 5971:      if just_header was not true these key may also exist
 5972: 
 5973:        missingerror - a list of bubble ranges that are considered to be answers
 5974:                       to a single question that don't have any bubbles filled in.
 5975:                       Of the form questionnumber:firstbubblenumber:count.
 5976:        doubleerror  - a list of bubble ranges that are considered to be answers
 5977:                       to a single question that have more than one bubble filled in.
 5978:                       Of the form questionnumber::firstbubblenumber:count
 5979:    
 5980:                 In the above, count is the number of bubble responses in the
 5981:                 input line needed to represent the possible answers to the question.
 5982:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 5983:                 per line would have count = 2.
 5984: 
 5985:        maxquest     - the number of the last bubble line that was parsed
 5986: 
 5987:        (<number> starts at 1)
 5988:        <number>.answer - zero or more letters representing the selected
 5989:                          letters from the scanline for the bubble line 
 5990:                          <number>.
 5991:                          if blank there was either no bubble or there where
 5992:                          multiple bubbles, (consult the keys missingerror and
 5993:                          doubleerror if this is an error condition)
 5994: 
 5995: =cut
 5996: 
 5997: sub scantron_parse_scanline {
 5998:     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
 5999:         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
 6000:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
 6001: 
 6002:     my %record;
 6003:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
 6004:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 6005: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 6006: 	if ($$scantron_config{'CODElocation'} < 0 ||
 6007: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 6008: 	    $$scantron_config{'CODElocation'} eq 'number') {
 6009: 	    $record{'scantron.CODE'}=substr($data,
 6010: 					    $$scantron_config{'CODEstart'}-1,
 6011: 					    $$scantron_config{'CODElength'});
 6012: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 6013: 		$record{'scantron.useCODE'}=1;
 6014: 	    }
 6015: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 6016: 		$record{'scantron.CODE_ignore_dup'}=1;
 6017: 	    }
 6018: 	} else {
 6019: 	    #FIXME interpret first N questions
 6020: 	}
 6021:     }
 6022:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 6023: 				  $$scantron_config{'IDlength'});
 6024:     $record{'scantron.PaperID'}=
 6025: 	substr($data,$$scantron_config{'PaperID'}-1,
 6026: 	       $$scantron_config{'PaperIDlength'});
 6027:     $record{'scantron.FirstName'}=
 6028: 	substr($data,$$scantron_config{'FirstName'}-1,
 6029: 	       $$scantron_config{'FirstNamelength'});
 6030:     $record{'scantron.LastName'}=
 6031: 	substr($data,$$scantron_config{'LastName'}-1,
 6032: 	       $$scantron_config{'LastNamelength'});
 6033:     if ($just_header) { return \%record; }
 6034: 
 6035:     my @alphabet=('A'..'Z');
 6036:     my $questnum=0;
 6037:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 6038: 
 6039:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 6040:     if ($randompick || $randomorder) {
 6041:         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
 6042:                                          $master_seq,$symb_to_resource,
 6043:                                          $partids_by_symb,$orderedforcode,
 6044:                                          $respnumlookup,$startline);
 6045:         if ($total) {
 6046:             $lastpos = $total*$$scantron_config{'Qlength'}; 
 6047:         }
 6048:         if (ref($totalref)) {
 6049:             $$totalref = $total;
 6050:         }
 6051:     }
 6052:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 6053:     chomp($questions);		# Get rid of any trailing \n.
 6054:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 6055:     while (length($questions)) {
 6056:         my $answers_needed;
 6057:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6058:             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
 6059:         } else {
 6060: 	    $answers_needed = $bubble_lines_per_response{$questnum};
 6061:         }
 6062:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 6063:                              || 1;
 6064:         $questnum++;
 6065:         my $quest_id = $questnum;
 6066:         my $currentquest = substr($questions,0,$answer_length);
 6067:         $questions       = substr($questions,$answer_length);
 6068:         if (length($currentquest) < $answer_length) { next; }
 6069: 
 6070:         my $subdivided;
 6071:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6072:             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
 6073:         } else {
 6074:             $subdivided = $subdivided_bubble_lines{$questnum-1};
 6075:         }
 6076:         if ($subdivided =~ /,/) {
 6077:             my $subquestnum = 1;
 6078:             my $subquestions = $currentquest;
 6079:             my @subanswers_needed = split(/,/,$subdivided);
 6080:             foreach my $subans (@subanswers_needed) {
 6081:                 my $subans_length =
 6082:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 6083:                 my $currsubquest = substr($subquestions,0,$subans_length);
 6084:                 $subquestions   = substr($subquestions,$subans_length);
 6085:                 $quest_id = "$questnum.$subquestnum";
 6086:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 6087:                     ($$scantron_config{'Qon'} eq 'number')) {
 6088:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 6089:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6090:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6091:                         $randomorder,$randompick,$respnumlookup);
 6092:                 } else {
 6093:                     $ansnum = &scantron_validator_positional($ansnum,
 6094:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6095:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6096:                         $randomorder,$randompick,$respnumlookup);
 6097:                 }
 6098:                 $subquestnum ++;
 6099:             }
 6100:         } else {
 6101:             if (($$scantron_config{'Qon'} eq 'letter') ||
 6102:                 ($$scantron_config{'Qon'} eq 'number')) {
 6103:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 6104:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6105:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6106:                     $randomorder,$randompick,$respnumlookup);
 6107:             } else {
 6108:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 6109:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6110:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6111:                     $randomorder,$randompick,$respnumlookup);
 6112:             }
 6113:         }
 6114:     }
 6115:     $record{'scantron.maxquest'}=$questnum;
 6116:     return \%record;
 6117: }
 6118: 
 6119: sub get_master_seq {
 6120:     my ($resources,$master_seq,$symb_to_resource) = @_;
 6121:     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') && 
 6122:                    (ref($symb_to_resource) eq 'HASH'));
 6123:     my $resource_error;
 6124:     foreach my $resource (@{$resources}) {
 6125:         my $ressymb;
 6126:         if (ref($resource)) {
 6127:             $ressymb = $resource->symb();
 6128:             push(@{$master_seq},$ressymb);
 6129:             $symb_to_resource->{$ressymb} = $resource;
 6130:         } else {
 6131:             $resource_error = 1;
 6132:             last;
 6133:         }
 6134:     }
 6135:     return $resource_error;
 6136: }
 6137: 
 6138: sub get_respnum_lookups {
 6139:     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
 6140:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
 6141:     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
 6142:                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
 6143:                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
 6144:                    (ref($startline) eq 'HASH'));
 6145:     my ($user,$scancode);
 6146:     if ((exists($record->{'scantron.CODE'})) &&
 6147:         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
 6148:         $scancode = $record->{'scantron.CODE'};
 6149:     } else {
 6150:         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
 6151:     }
 6152:     my @mapresources =
 6153:         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
 6154:                      $orderedforcode);
 6155:     my $total = 0;
 6156:     my $count = 0;
 6157:     foreach my $resource (@mapresources) {
 6158:         my $id = $resource->id();
 6159:         my $symb = $resource->symb();
 6160:         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
 6161:             foreach my $partid (@{$partids_by_symb->{$symb}}) {
 6162:                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
 6163:                 if ($respnum ne '') {
 6164:                     $respnumlookup->{$count} = $respnum;
 6165:                     $startline->{$count} = $total;
 6166:                     $total += $bubble_lines_per_response{$respnum};
 6167:                     $count ++;
 6168:                 }
 6169:             }
 6170:         }
 6171:     }
 6172:     return $total;
 6173: }
 6174: 
 6175: sub scantron_validator_lettnum {
 6176:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 6177:         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
 6178:         $randompick,$respnumlookup) = @_;
 6179: 
 6180:     # Qon 'letter' implies for each slot in currquest we have:
 6181:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 6182:     #    about anything else (esp. a value of Qoff) for missing
 6183:     #    bubbles.
 6184:     #
 6185:     # Qon 'number' implies each slot gives a digit that indexes the
 6186:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 6187:     #    and * or ? for double bubbles on a single line.
 6188:     #
 6189: 
 6190:     my $matchon;
 6191:     if ($$scantron_config{'Qon'} eq 'letter') {
 6192:         $matchon = '[A-Z]';
 6193:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 6194:         $matchon = '\d';
 6195:     }
 6196:     my $occurrences = 0;
 6197:     my $responsenum = $questnum-1;
 6198:     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6199:        $responsenum = $respnumlookup->{$questnum-1} 
 6200:     }
 6201:     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6202:         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6203:         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6204:         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6205:         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6206:         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6207:         my @singlelines = split('',$currquest);
 6208:         foreach my $entry (@singlelines) {
 6209:             $occurrences = &occurence_count($entry,$matchon);
 6210:             if ($occurrences > 1) {
 6211:                 last;
 6212:             }
 6213:         }
 6214:     } else {
 6215:         $occurrences = &occurence_count($currquest,$matchon); 
 6216:     }
 6217:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 6218:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6219:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6220:             my $bubble = substr($currquest,$ans,1);
 6221:             if ($bubble =~ /$matchon/ ) {
 6222:                 if ($$scantron_config{'Qon'} eq 'number') {
 6223:                     if ($bubble == 0) {
 6224:                         $bubble = 10; 
 6225:                     }
 6226:                     $record->{"scantron.$ansnum.answer"} = 
 6227:                         $alphabet->[$bubble-1];
 6228:                 } else {
 6229:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 6230:                 }
 6231:             } else {
 6232:                 $record->{"scantron.$ansnum.answer"}='';
 6233:             }
 6234:             $ansnum++;
 6235:         }
 6236:     } elsif (!defined($currquest)
 6237:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 6238:             || (&occurence_count($currquest,$matchon) == 0)) {
 6239:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6240:             $record->{"scantron.$ansnum.answer"}='';
 6241:             $ansnum++;
 6242:         }
 6243:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6244:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 6245:         }
 6246:     } else {
 6247:         if ($$scantron_config{'Qon'} eq 'number') {
 6248:             $currquest = &digits_to_letters($currquest);            
 6249:         }
 6250:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6251:             my $bubble = substr($currquest,$ans,1);
 6252:             $record->{"scantron.$ansnum.answer"} = $bubble;
 6253:             $ansnum++;
 6254:         }
 6255:     }
 6256:     return $ansnum;
 6257: }
 6258: 
 6259: sub scantron_validator_positional {
 6260:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 6261:         $whichline,$alphabet,$record,$scantron_config,$scan_data,
 6262:         $randomorder,$randompick,$respnumlookup) = @_;
 6263: 
 6264:     # Otherwise there's a positional notation;
 6265:     # each bubble line requires Qlength items, and there are filled in
 6266:     # bubbles for each case where there 'Qon' characters.
 6267:     #
 6268: 
 6269:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 6270: 
 6271:     # If the split only gives us one element.. the full length of the
 6272:     # answer string, no bubbles are filled in:
 6273: 
 6274:     if ($answers_needed eq '') {
 6275:         return;
 6276:     }
 6277: 
 6278:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 6279:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6280:             $record->{"scantron.$ansnum.answer"}='';
 6281:             $ansnum++;
 6282:         }
 6283:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6284:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 6285:         }
 6286:     } elsif (scalar(@array) == 2) {
 6287:         my $location = length($array[0]);
 6288:         my $line_num = int($location / $$scantron_config{'Qlength'});
 6289:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 6290:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6291:             if ($ans eq $line_num) {
 6292:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 6293:             } else {
 6294:                 $record->{"scantron.$ansnum.answer"} = ' ';
 6295:             }
 6296:             $ansnum++;
 6297:          }
 6298:     } else {
 6299:         #  If there's more than one instance of a bubble character
 6300:         #  That's a double bubble; with positional notation we can
 6301:         #  record all the bubbles filled in as well as the
 6302:         #  fact this response consists of multiple bubbles.
 6303:         #
 6304:         my $responsenum = $questnum-1;
 6305:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6306:             $responsenum = $respnumlookup->{$questnum-1}
 6307:         }
 6308:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6309:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6310:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6311:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6312:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6313:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6314:             my $doubleerror = 0;
 6315:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 6316:                    (!$doubleerror)) {
 6317:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 6318:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 6319:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 6320:                if (length(@currarray) > 2) {
 6321:                    $doubleerror = 1;
 6322:                } 
 6323:             }
 6324:             if ($doubleerror) {
 6325:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6326:             }
 6327:         } else {
 6328:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6329:         }
 6330:         my $item = $ansnum;
 6331:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6332:             $record->{"scantron.$item.answer"} = '';
 6333:             $item ++;
 6334:         }
 6335: 
 6336:         my @ans=@array;
 6337:         my $i=0;
 6338:         my $increment = 0;
 6339:         while ($#ans) {
 6340:             $i+=length($ans[0]) + $increment;
 6341:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 6342:             my $bubble = $i%$$scantron_config{'Qlength'};
 6343:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 6344:             shift(@ans);
 6345:             $increment = 1;
 6346:         }
 6347:         $ansnum += $answers_needed;
 6348:     }
 6349:     return $ansnum;
 6350: }
 6351: 
 6352: =pod
 6353: 
 6354: =item scantron_add_delay
 6355: 
 6356:    Adds an error message that occurred during the grading phase to a
 6357:    queue of messages to be shown after grading pass is complete
 6358: 
 6359:  Arguments:
 6360:    $delayqueue  - arrary ref of hash ref of error messages
 6361:    $scanline    - the scanline that caused the error
 6362:    $errormesage - the error message
 6363:    $errorcode   - a numeric code for the error
 6364: 
 6365:  Side Effects:
 6366:    updates the $delayqueue to have a new hash ref of the error
 6367: 
 6368: =cut
 6369: 
 6370: sub scantron_add_delay {
 6371:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 6372:     push(@$delayqueue,
 6373: 	 {'line' => $scanline, 'emsg' => $errormessage,
 6374: 	  'ecode' => $errorcode }
 6375: 	 );
 6376: }
 6377: 
 6378: =pod
 6379: 
 6380: =item scantron_find_student
 6381: 
 6382:    Finds the username for the current scanline
 6383: 
 6384:   Arguments:
 6385:    $scantron_record - hash result from scantron_parse_scanline
 6386:    $scan_data       - hash of correction information 
 6387:                       (see &scantron_getfile() form more information)
 6388:    $idmap           - hash from &username_to_idmap()
 6389:    $line            - number of current scanline
 6390:  
 6391:   Returns:
 6392:    Either 'username:domain' or undef if unknown
 6393: 
 6394: =cut
 6395: 
 6396: sub scantron_find_student {
 6397:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 6398:     my $scanID=$$scantron_record{'scantron.ID'};
 6399:     if ($scanID =~ /^\s*$/) {
 6400:  	return &scan_data($scan_data,"$line.user");
 6401:     }
 6402:     foreach my $id (keys(%$idmap)) {
 6403:  	if (lc($id) eq lc($scanID)) {
 6404:  	    return $$idmap{$id};
 6405:  	}
 6406:     }
 6407:     return undef;
 6408: }
 6409: 
 6410: =pod
 6411: 
 6412: =item scantron_filter
 6413: 
 6414:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 6415:    hidden resources was selected
 6416: 
 6417: =cut
 6418: 
 6419: sub scantron_filter {
 6420:     my ($curres)=@_;
 6421: 
 6422:     if (ref($curres) && $curres->is_problem()) {
 6423: 	# if the user has asked to not have either hidden
 6424: 	# or 'randomout' controlled resources to be graded
 6425: 	# don't include them
 6426: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6427: 	    && $curres->randomout) {
 6428: 	    return 0;
 6429: 	}
 6430: 	return 1;
 6431:     }
 6432:     return 0;
 6433: }
 6434: 
 6435: =pod
 6436: 
 6437: =item scantron_process_corrections
 6438: 
 6439:    Gets correction information out of submitted form data and corrects
 6440:    the scanline
 6441: 
 6442: =cut
 6443: 
 6444: sub scantron_process_corrections {
 6445:     my ($r) = @_;
 6446:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6447:     my ($scanlines,$scan_data)=&scantron_getfile();
 6448:     my $classlist=&Apache::loncoursedata::get_classlist();
 6449:     my $which=$env{'form.scantron_line'};
 6450:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 6451:     my ($skip,$err,$errmsg);
 6452:     if ($env{'form.scantron_skip_record'}) {
 6453: 	$skip=1;
 6454:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 6455: 	my $newstudent=$env{'form.scantron_username'}.':'.
 6456: 	    $env{'form.scantron_domain'};
 6457: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 6458: 	($line,$err,$errmsg)=
 6459: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6460: 				     'ID',{'newid'=>$newid,
 6461: 				    'username'=>$env{'form.scantron_username'},
 6462: 				    'domain'=>$env{'form.scantron_domain'}});
 6463:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 6464: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 6465: 	my $newCODE;
 6466: 	my %args;
 6467: 	if      ($resolution eq 'use_unfound') {
 6468: 	    $newCODE='use_unfound';
 6469: 	} elsif ($resolution eq 'use_found') {
 6470: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 6471: 	} elsif ($resolution eq 'use_typed') {
 6472: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 6473: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 6474: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 6475: 	}
 6476: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 6477: 	    $args{'CODE_ignore_dup'}=1;
 6478: 	}
 6479: 	$args{'CODE'}=$newCODE;
 6480: 	($line,$err,$errmsg)=
 6481: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6482: 				     'CODE',\%args);
 6483:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 6484: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 6485: 	    ($line,$err,$errmsg)=
 6486: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 6487: 					 $which,'answer',
 6488: 					 { 'question'=>$question,
 6489: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 6490:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 6491: 	    if ($err) { last; }
 6492: 	}
 6493:     }
 6494:     if ($err) {
 6495:         $r->print(
 6496:             '<p class="LC_error">'
 6497:            .&mt('Unable to accept last correction, an error occurred: [_1]',
 6498:                 $errmsg)
 6499:            .'</p>');
 6500:     } else {
 6501: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 6502: 	&scantron_putfile($scanlines,$scan_data);
 6503:     }
 6504: }
 6505: 
 6506: =pod
 6507: 
 6508: =item reset_skipping_status
 6509: 
 6510:    Forgets the current set of remember skipped scanlines (and thus
 6511:    reverts back to considering all lines in the
 6512:    scantron_skipped_<filename> file)
 6513: 
 6514: =cut
 6515: 
 6516: sub reset_skipping_status {
 6517:     my ($scanlines,$scan_data)=&scantron_getfile();
 6518:     &scan_data($scan_data,'remember_skipping',undef,1);
 6519:     &scantron_putfile(undef,$scan_data);
 6520: }
 6521: 
 6522: =pod
 6523: 
 6524: =item start_skipping
 6525: 
 6526:    Marks a scanline to be skipped. 
 6527: 
 6528: =cut
 6529: 
 6530: sub start_skipping {
 6531:     my ($scan_data,$i)=@_;
 6532:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6533:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 6534: 	$remembered{$i}=2;
 6535:     } else {
 6536: 	$remembered{$i}=1;
 6537:     }
 6538:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 6539: }
 6540: 
 6541: =pod
 6542: 
 6543: =item should_be_skipped
 6544: 
 6545:    Checks whether a scanline should be skipped.
 6546: 
 6547: =cut
 6548: 
 6549: sub should_be_skipped {
 6550:     my ($scanlines,$scan_data,$i)=@_;
 6551:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 6552: 	# not redoing old skips
 6553: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 6554: 	return 0;
 6555:     }
 6556:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6557: 
 6558:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 6559: 	return 0;
 6560:     }
 6561:     return 1;
 6562: }
 6563: 
 6564: =pod
 6565: 
 6566: =item remember_current_skipped
 6567: 
 6568:    Discovers what scanlines are in the scantron_skipped_<filename>
 6569:    file and remembers them into scan_data for later use.
 6570: 
 6571: =cut
 6572: 
 6573: sub remember_current_skipped {
 6574:     my ($scanlines,$scan_data)=&scantron_getfile();
 6575:     my %to_remember;
 6576:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6577: 	if ($scanlines->{'skipped'}[$i]) {
 6578: 	    $to_remember{$i}=1;
 6579: 	}
 6580:     }
 6581: 
 6582:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 6583:     &scantron_putfile(undef,$scan_data);
 6584: }
 6585: 
 6586: =pod
 6587: 
 6588: =item check_for_error
 6589: 
 6590:     Checks if there was an error when attempting to remove a specific
 6591:     scantron_.. bubblesheet data file. Prints out an error if
 6592:     something went wrong.
 6593: 
 6594: =cut
 6595: 
 6596: sub check_for_error {
 6597:     my ($r,$result)=@_;
 6598:     if ($result ne 'ok' && $result ne 'not_found' ) {
 6599: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 6600:     }
 6601: }
 6602: 
 6603: =pod
 6604: 
 6605: =item scantron_warning_screen
 6606: 
 6607:    Interstitial screen to make sure the operator has selected the
 6608:    correct options before we start the validation phase.
 6609: 
 6610: =cut
 6611: 
 6612: sub scantron_warning_screen {
 6613:     my ($button_text,$symb)=@_;
 6614:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 6615:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6616:     my $CODElist;
 6617:     if ($scantron_config{'CODElocation'} &&
 6618: 	$scantron_config{'CODEstart'} &&
 6619: 	$scantron_config{'CODElength'}) {
 6620: 	$CODElist=$env{'form.scantron_CODElist'};
 6621: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
 6622: 	$CODElist=
 6623: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 6624: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 6625:     }
 6626:     my $lastbubblepoints;
 6627:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 6628:         $lastbubblepoints =
 6629:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
 6630:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
 6631:     }
 6632:     return ('
 6633: <p>
 6634: <span class="LC_warning">
 6635: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
 6636: </p>
 6637: <table>
 6638: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 6639: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 6640: '.$CODElist.$lastbubblepoints.'
 6641: </table>
 6642: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
 6643: '.&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>
 6644: 
 6645: <br />
 6646: ');
 6647: }
 6648: 
 6649: =pod
 6650: 
 6651: =item scantron_do_warning
 6652: 
 6653:    Check if the operator has picked something for all required
 6654:    fields. Error out if something is missing.
 6655: 
 6656: =cut
 6657: 
 6658: sub scantron_do_warning {
 6659:     my ($r,$symb)=@_;
 6660:     if (!$symb) {return '';}
 6661:     my $default_form_data=&defaultFormData($symb);
 6662:     $r->print(&scantron_form_start().$default_form_data);
 6663:     if ( $env{'form.selectpage'} eq '' ||
 6664: 	 $env{'form.scantron_selectfile'} eq '' ||
 6665: 	 $env{'form.scantron_format'} eq '' ) {
 6666: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
 6667: 	if ( $env{'form.selectpage'} eq '') {
 6668: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 6669: 	} 
 6670: 	if ( $env{'form.scantron_selectfile'} eq '') {
 6671: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected a file that contains the student's response data.").'</span></p>');
 6672: 	} 
 6673: 	if ( $env{'form.scantron_format'} eq '') {
 6674: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected the format of the student's response data.").'</span></p>');
 6675: 	} 
 6676:     } else {
 6677: 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
 6678:         my $bubbledbyhand=&hand_bubble_option();
 6679: 	$r->print('
 6680: '.$warning.$bubbledbyhand.'
 6681: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 6682: <input type="hidden" name="command" value="scantron_validate" />
 6683: ');
 6684:     }
 6685:     $r->print("</form><br />");
 6686:     return '';
 6687: }
 6688: 
 6689: =pod
 6690: 
 6691: =item scantron_form_start
 6692: 
 6693:     html hidden input for remembering all selected grading options
 6694: 
 6695: =cut
 6696: 
 6697: sub scantron_form_start {
 6698:     my ($max_bubble)=@_;
 6699:     my $result= <<SCANTRONFORM;
 6700: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 6701:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 6702:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 6703:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 6704:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 6705:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 6706:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 6707:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 6708:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 6709:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 6710: SCANTRONFORM
 6711: 
 6712:   my $line = 0;
 6713:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 6714:        my $chunk =
 6715: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 6716:        $chunk .=
 6717: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 6718:        $chunk .= 
 6719:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 6720:        $chunk .=
 6721:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 6722:        $chunk .=
 6723:            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
 6724:        $result .= $chunk;
 6725:        $line++;
 6726:     }
 6727:     return $result;
 6728: }
 6729: 
 6730: =pod
 6731: 
 6732: =item scantron_validate_file
 6733: 
 6734:     Dispatch routine for doing validation of a bubblesheet data file.
 6735: 
 6736:     Also processes any necessary information resets that need to
 6737:     occur before validation begins (ignore previous corrections,
 6738:     restarting the skipped records processing)
 6739: 
 6740: =cut
 6741: 
 6742: sub scantron_validate_file {
 6743:     my ($r,$symb) = @_;
 6744:     if (!$symb) {return '';}
 6745:     my $default_form_data=&defaultFormData($symb);
 6746:     
 6747:     # do the detection of only doing skipped records first before we delete
 6748:     # them when doing the corrections reset
 6749:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 6750: 	&reset_skipping_status();
 6751:     }
 6752:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 6753: 	&remember_current_skipped();
 6754: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 6755:     }
 6756: 
 6757:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 6758: 	&check_for_error($r,&scantron_remove_file('corrected'));
 6759: 	&check_for_error($r,&scantron_remove_file('skipped'));
 6760: 	&check_for_error($r,&scantron_remove_scan_data());
 6761: 	$env{'form.scantron_options_ignore'}='done';
 6762:     }
 6763: 
 6764:     if ($env{'form.scantron_corrections'}) {
 6765: 	&scantron_process_corrections($r);
 6766:     }
 6767:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 6768:     #get the student pick code ready
 6769:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 6770:     my $nav_error;
 6771:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6772:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 6773:     if ($nav_error) {
 6774:         $r->print(&navmap_errormsg());
 6775:         return '';
 6776:     }
 6777:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 6778:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 6779:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
 6780:     }
 6781:     $r->print($result);
 6782:     
 6783:     my @validate_phases=( 'sequence',
 6784: 			  'ID',
 6785: 			  'CODE',
 6786: 			  'doublebubble',
 6787: 			  'missingbubbles');
 6788:     if (!$env{'form.validatepass'}) {
 6789: 	$env{'form.validatepass'} = 0;
 6790:     }
 6791:     my $currentphase=$env{'form.validatepass'};
 6792: 
 6793: 
 6794:     my $stop=0;
 6795:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 6796: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 6797: 	$r->rflush();
 6798:      
 6799: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 6800: 	{
 6801: 	    no strict 'refs';
 6802: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 6803: 	}
 6804:     }
 6805:     if (!$stop) {
 6806: 	my $warning=&scantron_warning_screen('Start Grading',$symb);
 6807: 	$r->print(&mt('Validation process complete.').'<br />'.
 6808:                   $warning.
 6809:                   &mt('Perform verification for each student after storage of submissions?').
 6810:                   '&nbsp;<span class="LC_nobreak"><label>'.
 6811:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 6812:                   ('&nbsp;'x3).'<label>'.
 6813:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 6814:                   '</label></span><br />'.
 6815:                   &mt('Grading will take longer if you use verification.').'<br />'.
 6816:                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
 6817:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 6818:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 6819:     } else {
 6820: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 6821: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 6822:     }
 6823:     if ($stop) {
 6824: 	if ($validate_phases[$currentphase] eq 'sequence') {
 6825: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 6826: 	    $r->print(' '.&mt('this error').' <br />');
 6827: 
 6828: 	    $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>');
 6829: 	} else {
 6830:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 6831: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 6832:             } else {
 6833:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 6834:             }
 6835: 	    $r->print(' '.&mt('using corrected info').' <br />');
 6836: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 6837: 	    $r->print(" ".&mt("this scanline saving it for later."));
 6838: 	}
 6839:     }
 6840:     $r->print(" </form><br />");
 6841:     return '';
 6842: }
 6843: 
 6844: 
 6845: =pod
 6846: 
 6847: =item scantron_remove_file
 6848: 
 6849:    Removes the requested bubblesheet data file, makes sure that
 6850:    scantron_original_<filename> is never removed
 6851: 
 6852: 
 6853: =cut
 6854: 
 6855: sub scantron_remove_file {
 6856:     my ($which)=@_;
 6857:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6858:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6859:     my $file='scantron_';
 6860:     if ($which eq 'corrected' || $which eq 'skipped') {
 6861: 	$file.=$which.'_';
 6862:     } else {
 6863: 	return 'refused';
 6864:     }
 6865:     $file.=$env{'form.scantron_selectfile'};
 6866:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 6867: }
 6868: 
 6869: 
 6870: =pod
 6871: 
 6872: =item scantron_remove_scan_data
 6873: 
 6874:    Removes all scan_data correction for the requested bubblesheet
 6875:    data file.  (In the case that both the are doing skipped records we need
 6876:    to remember the old skipped lines for the time being so that element
 6877:    persists for a while.)
 6878: 
 6879: =cut
 6880: 
 6881: sub scantron_remove_scan_data {
 6882:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6883:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6884:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 6885:     my @todelete;
 6886:     my $filename=$env{'form.scantron_selectfile'};
 6887:     foreach my $key (@keys) {
 6888: 	if ($key=~/^\Q$filename\E_/) {
 6889: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 6890: 		$key=~/remember_skipping/) {
 6891: 		next;
 6892: 	    }
 6893: 	    push(@todelete,$key);
 6894: 	}
 6895:     }
 6896:     my $result;
 6897:     if (@todelete) {
 6898: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 6899: 				       \@todelete,$cdom,$cname);
 6900:     } else {
 6901: 	$result = 'ok';
 6902:     }
 6903:     return $result;
 6904: }
 6905: 
 6906: 
 6907: =pod
 6908: 
 6909: =item scantron_getfile
 6910: 
 6911:     Fetches the requested bubblesheet data file (all 3 versions), and
 6912:     the scan_data hash
 6913:   
 6914:   Arguments:
 6915:     None
 6916: 
 6917:   Returns:
 6918:     2 hash references
 6919: 
 6920:      - first one has 
 6921:          orig      -
 6922:          corrected -
 6923:          skipped   -  each of which points to an array ref of the specified
 6924:                       file broken up into individual lines
 6925:          count     - number of scanlines
 6926:  
 6927:      - second is the scan_data hash possible keys are
 6928:        ($number refers to scanline numbered $number and thus the key affects
 6929:         only that scanline
 6930:         $bubline refers to the specific bubble line element and the aspects
 6931:         refers to that specific bubble line element)
 6932: 
 6933:        $number.user - username:domain to use
 6934:        $number.CODE_ignore_dup 
 6935:                     - ignore the duplicate CODE error 
 6936:        $number.useCODE
 6937:                     - use the CODE in the scanline as is
 6938:        $number.no_bubble.$bubline
 6939:                     - it is valid that there is no bubbled in bubble
 6940:                       at $number $bubline
 6941:        remember_skipping
 6942:                     - a frozen hash containing keys of $number and values
 6943:                       of either 
 6944:                         1 - we are on a 'do skipped records pass' and plan
 6945:                             on processing this line
 6946:                         2 - we are on a 'do skipped records pass' and this
 6947:                             scanline has been marked to skip yet again
 6948: 
 6949: =cut
 6950: 
 6951: sub scantron_getfile {
 6952:     #FIXME really would prefer a scantron directory
 6953:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6954:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6955:     my $lines;
 6956:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6957: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 6958:     my %scanlines;
 6959:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 6960:     my $temp=$scanlines{'orig'};
 6961:     $scanlines{'count'}=$#$temp;
 6962: 
 6963:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6964: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 6965:     if ($lines eq '-1') {
 6966: 	$scanlines{'corrected'}=[];
 6967:     } else {
 6968: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 6969:     }
 6970:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6971: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 6972:     if ($lines eq '-1') {
 6973: 	$scanlines{'skipped'}=[];
 6974:     } else {
 6975: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 6976:     }
 6977:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 6978:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 6979:     my %scan_data = @tmp;
 6980:     return (\%scanlines,\%scan_data);
 6981: }
 6982: 
 6983: =pod
 6984: 
 6985: =item lonnet_putfile
 6986: 
 6987:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 6988: 
 6989:  Arguments:
 6990:    $contents - data to store
 6991:    $filename - filename to store $contents into
 6992: 
 6993:  Returns:
 6994:    result value from &Apache::lonnet::finishuserfileupload
 6995: 
 6996: =cut
 6997: 
 6998: sub lonnet_putfile {
 6999:     my ($contents,$filename)=@_;
 7000:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7001:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7002:     $env{'form.sillywaytopassafilearound'}=$contents;
 7003:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 7004: 
 7005: }
 7006: 
 7007: =pod
 7008: 
 7009: =item scantron_putfile
 7010: 
 7011:     Stores the current version of the bubblesheet data files, and the
 7012:     scan_data hash. (Does not modify the original version only the
 7013:     corrected and skipped versions.
 7014: 
 7015:  Arguments:
 7016:     $scanlines - hash ref that looks like the first return value from
 7017:                  &scantron_getfile()
 7018:     $scan_data - hash ref that looks like the second return value from
 7019:                  &scantron_getfile()
 7020: 
 7021: =cut
 7022: 
 7023: sub scantron_putfile {
 7024:     my ($scanlines,$scan_data) = @_;
 7025:     #FIXME really would prefer a scantron directory
 7026:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7027:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7028:     if ($scanlines) {
 7029: 	my $prefix='scantron_';
 7030: # no need to update orig, shouldn't change
 7031: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 7032: #		    $env{'form.scantron_selectfile'});
 7033: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 7034: 			$prefix.'corrected_'.
 7035: 			$env{'form.scantron_selectfile'});
 7036: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 7037: 			$prefix.'skipped_'.
 7038: 			$env{'form.scantron_selectfile'});
 7039:     }
 7040:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 7041: }
 7042: 
 7043: =pod
 7044: 
 7045: =item scantron_get_line
 7046: 
 7047:    Returns the correct version of the scanline
 7048: 
 7049:  Arguments:
 7050:     $scanlines - hash ref that looks like the first return value from
 7051:                  &scantron_getfile()
 7052:     $scan_data - hash ref that looks like the second return value from
 7053:                  &scantron_getfile()
 7054:     $i         - number of the requested line (starts at 0)
 7055: 
 7056:  Returns:
 7057:    A scanline, (either the original or the corrected one if it
 7058:    exists), or undef if the requested scanline should be
 7059:    skipped. (Either because it's an skipped scanline, or it's an
 7060:    unskipped scanline and we are not doing a 'do skipped scanlines'
 7061:    pass.
 7062: 
 7063: =cut
 7064: 
 7065: sub scantron_get_line {
 7066:     my ($scanlines,$scan_data,$i)=@_;
 7067:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 7068:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 7069:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 7070:     return $scanlines->{'orig'}[$i]; 
 7071: }
 7072: 
 7073: =pod
 7074: 
 7075: =item scantron_todo_count
 7076: 
 7077:     Counts the number of scanlines that need processing.
 7078: 
 7079:  Arguments:
 7080:     $scanlines - hash ref that looks like the first return value from
 7081:                  &scantron_getfile()
 7082:     $scan_data - hash ref that looks like the second return value from
 7083:                  &scantron_getfile()
 7084: 
 7085:  Returns:
 7086:     $count - number of scanlines to process
 7087: 
 7088: =cut
 7089: 
 7090: sub get_todo_count {
 7091:     my ($scanlines,$scan_data)=@_;
 7092:     my $count=0;
 7093:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7094: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7095: 	if ($line=~/^[\s\cz]*$/) { next; }
 7096: 	$count++;
 7097:     }
 7098:     return $count;
 7099: }
 7100: 
 7101: =pod
 7102: 
 7103: =item scantron_put_line
 7104: 
 7105:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
 7106:     data file.
 7107: 
 7108:  Arguments:
 7109:     $scanlines - hash ref that looks like the first return value from
 7110:                  &scantron_getfile()
 7111:     $scan_data - hash ref that looks like the second return value from
 7112:                  &scantron_getfile()
 7113:     $i         - line number to update
 7114:     $newline   - contents of the updated scanline
 7115:     $skip      - if true make the line for skipping and update the
 7116:                  'skipped' file
 7117: 
 7118: =cut
 7119: 
 7120: sub scantron_put_line {
 7121:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 7122:     if ($skip) {
 7123: 	$scanlines->{'skipped'}[$i]=$newline;
 7124: 	&start_skipping($scan_data,$i);
 7125: 	return;
 7126:     }
 7127:     $scanlines->{'corrected'}[$i]=$newline;
 7128: }
 7129: 
 7130: =pod
 7131: 
 7132: =item scantron_clear_skip
 7133: 
 7134:    Remove a line from the 'skipped' file
 7135: 
 7136:  Arguments:
 7137:     $scanlines - hash ref that looks like the first return value from
 7138:                  &scantron_getfile()
 7139:     $scan_data - hash ref that looks like the second return value from
 7140:                  &scantron_getfile()
 7141:     $i         - line number to update
 7142: 
 7143: =cut
 7144: 
 7145: sub scantron_clear_skip {
 7146:     my ($scanlines,$scan_data,$i)=@_;
 7147:     if (exists($scanlines->{'skipped'}[$i])) {
 7148: 	undef($scanlines->{'skipped'}[$i]);
 7149: 	return 1;
 7150:     }
 7151:     return 0;
 7152: }
 7153: 
 7154: =pod
 7155: 
 7156: =item scantron_filter_not_exam
 7157: 
 7158:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 7159:    filter out resources that are not marked as 'exam' mode
 7160: 
 7161: =cut
 7162: 
 7163: sub scantron_filter_not_exam {
 7164:     my ($curres)=@_;
 7165:     
 7166:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 7167: 	# if the user has asked to not have either hidden
 7168: 	# or 'randomout' controlled resources to be graded
 7169: 	# don't include them
 7170: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 7171: 	    && $curres->randomout) {
 7172: 	    return 0;
 7173: 	}
 7174: 	return 1;
 7175:     }
 7176:     return 0;
 7177: }
 7178: 
 7179: =pod
 7180: 
 7181: =item scantron_validate_sequence
 7182: 
 7183:     Validates the selected sequence, checking for resource that are
 7184:     not set to exam mode.
 7185: 
 7186: =cut
 7187: 
 7188: sub scantron_validate_sequence {
 7189:     my ($r,$currentphase) = @_;
 7190: 
 7191:     my $navmap=Apache::lonnavmaps::navmap->new();
 7192:     unless (ref($navmap)) {
 7193:         $r->print(&navmap_errormsg());
 7194:         return (1,$currentphase);
 7195:     }
 7196:     my (undef,undef,$sequence)=
 7197: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7198: 
 7199:     my $map=$navmap->getResourceByUrl($sequence);
 7200: 
 7201:     $r->print('<input type="hidden" name="validate_sequence_exam"
 7202:                                     value="ignore" />');
 7203:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 7204: 	my @resources=
 7205: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 7206: 	if (@resources) {
 7207: 	    $r->print(
 7208:                 '<p class="LC_warning">'
 7209:                .&mt('Some resources in the sequence currently are not set to'
 7210:                    .' bubblesheet exam mode. Grading these resources currently may not'
 7211:                    .' work correctly.')
 7212:                .'</p>'
 7213:             );
 7214: 	    return (1,$currentphase);
 7215: 	}
 7216:     }
 7217: 
 7218:     return (0,$currentphase+1);
 7219: }
 7220: 
 7221: 
 7222: 
 7223: sub scantron_validate_ID {
 7224:     my ($r,$currentphase) = @_;
 7225:     
 7226:     #get student info
 7227:     my $classlist=&Apache::loncoursedata::get_classlist();
 7228:     my %idmap=&username_to_idmap($classlist);
 7229: 
 7230:     #get scantron line setup
 7231:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7232:     my ($scanlines,$scan_data)=&scantron_getfile();
 7233: 
 7234:     my $nav_error;
 7235:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
 7236:     if ($nav_error) {
 7237:         $r->print(&navmap_errormsg());
 7238:         return(1,$currentphase);
 7239:     }
 7240: 
 7241:     my %found=('ids'=>{},'usernames'=>{});
 7242:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7243: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7244: 	if ($line=~/^[\s\cz]*$/) { next; }
 7245: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7246: 						 $scan_data);
 7247: 	my $id=$$scan_record{'scantron.ID'};
 7248: 	my $found;
 7249: 	foreach my $checkid (keys(%idmap)) {
 7250: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 7251: 	}
 7252: 	if ($found) {
 7253: 	    my $username=$idmap{$found};
 7254: 	    if ($found{'ids'}{$found}) {
 7255: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7256: 					 $line,'duplicateID',$found);
 7257: 		return(1,$currentphase);
 7258: 	    } elsif ($found{'usernames'}{$username}) {
 7259: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7260: 					 $line,'duplicateID',$username);
 7261: 		return(1,$currentphase);
 7262: 	    }
 7263: 	    #FIXME store away line we previously saw the ID on to use above
 7264: 	    $found{'ids'}{$found}++;
 7265: 	    $found{'usernames'}{$username}++;
 7266: 	} else {
 7267: 	    if ($id =~ /^\s*$/) {
 7268: 		my $username=&scan_data($scan_data,"$i.user");
 7269: 		if (defined($username) && $found{'usernames'}{$username}) {
 7270: 		    &scantron_get_correction($r,$i,$scan_record,
 7271: 					     \%scantron_config,
 7272: 					     $line,'duplicateID',$username);
 7273: 		    return(1,$currentphase);
 7274: 		} elsif (!defined($username)) {
 7275: 		    &scantron_get_correction($r,$i,$scan_record,
 7276: 					     \%scantron_config,
 7277: 					     $line,'incorrectID');
 7278: 		    return(1,$currentphase);
 7279: 		}
 7280: 		$found{'usernames'}{$username}++;
 7281: 	    } else {
 7282: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7283: 					 $line,'incorrectID');
 7284: 		return(1,$currentphase);
 7285: 	    }
 7286: 	}
 7287:     }
 7288: 
 7289:     return (0,$currentphase+1);
 7290: }
 7291: 
 7292: 
 7293: sub scantron_get_correction {
 7294:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
 7295:         $randomorder,$randompick,$respnumlookup,$startline)=@_;
 7296: #FIXME in the case of a duplicated ID the previous line, probably need
 7297: #to show both the current line and the previous one and allow skipping
 7298: #the previous one or the current one
 7299: 
 7300:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 7301:         $r->print(
 7302:             '<p class="LC_warning">'
 7303:            .&mt('An error was detected ([_1]) for PaperID [_2]',
 7304:                 "<b>$error</b>",
 7305:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
 7306:            ."</p> \n");
 7307:     } else {
 7308:         $r->print(
 7309:             '<p class="LC_warning">'
 7310:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
 7311:                 "<b>$error</b>", $i, "<pre>$line</pre>")
 7312:            ."</p> \n");
 7313:     }
 7314:     my $message =
 7315:         '<p>'
 7316:        .&mt('The ID on the form is [_1]',
 7317:             "<tt>$$scan_record{'scantron.ID'}</tt>")
 7318:        .'<br />'
 7319:        .&mt('The name on the paper is [_1], [_2]',
 7320:             $$scan_record{'scantron.LastName'},
 7321:             $$scan_record{'scantron.FirstName'})
 7322:        .'</p>';
 7323: 
 7324:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 7325:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 7326:                            # Array populated for doublebubble or
 7327:     my @lines_to_correct;  # missingbubble errors to build javascript
 7328:                            # to validate radio button checking   
 7329: 
 7330:     if ($error =~ /ID$/) {
 7331: 	if ($error eq 'incorrectID') {
 7332:             $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
 7333: 		      "</p>\n");
 7334: 	} elsif ($error eq 'duplicateID') {
 7335:             $r->print('<p class="LC_warning">'.&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 7336: 	}
 7337: 	$r->print($message);
 7338: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 7339: 	$r->print("\n<ul><li> ");
 7340: 	#FIXME it would be nice if this sent back the user ID and
 7341: 	#could do partial userID matches
 7342: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 7343: 				       'scantron_username','scantron_domain'));
 7344: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 7345: 	$r->print("\n:\n".
 7346: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 7347: 
 7348: 	$r->print('</li>');
 7349:     } elsif ($error =~ /CODE$/) {
 7350: 	if ($error eq 'incorrectCODE') {
 7351: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 7352: 	} elsif ($error eq 'duplicateCODE') {
 7353: 	    $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");
 7354: 	}
 7355: 	$r->print("<p>".&mt('The CODE on the form is [_1]',
 7356: 			    "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
 7357:                  ."</p>\n");
 7358: 	$r->print($message);
 7359: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
 7360: 	$r->print("\n<br /> ");
 7361: 	my $i=0;
 7362: 	if ($error eq 'incorrectCODE' 
 7363: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 7364: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 7365: 	    if ($closest > 0) {
 7366: 		foreach my $testcode (@{$closest}) {
 7367: 		    my $checked='';
 7368: 		    if (!$i) { $checked=' checked="checked"'; }
 7369: 		    $r->print("
 7370:    <label>
 7371:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
 7372:        ".&mt("Use the similar CODE [_1] instead.",
 7373: 	    "<b><tt>".$testcode."</tt></b>")."
 7374:     </label>
 7375:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 7376: 		    $r->print("\n<br />");
 7377: 		    $i++;
 7378: 		}
 7379: 	    }
 7380: 	}
 7381: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 7382: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
 7383: 	    $r->print("
 7384:     <label>
 7385:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
 7386:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
 7387: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 7388:     </label>");
 7389: 	    $r->print("\n<br />");
 7390: 	}
 7391: 
 7392: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
 7393: function change_radio(field) {
 7394:     var slct=document.scantronupload.scantron_CODE_resolution;
 7395:     var i;
 7396:     for (i=0;i<slct.length;i++) {
 7397:         if (slct[i].value==field) { slct[i].checked=true; }
 7398:     }
 7399: }
 7400: ENDSCRIPT
 7401: 	my $href="/adm/pickcode?".
 7402: 	   "form=".&escape("scantronupload").
 7403: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 7404: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 7405: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 7406: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 7407: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 7408: 	    $r->print("
 7409:     <label>
 7410:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 7411:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 7412: 	     "<a target='_blank' href='$href'>","</a>")."
 7413:     </label> 
 7414:     ".&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\')" />'));
 7415: 	    $r->print("\n<br />");
 7416: 	}
 7417: 	$r->print("
 7418:     <label>
 7419:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 7420:        ".&mt("Use [_1] as the CODE.",
 7421: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 7422: 	$r->print("\n<br /><br />");
 7423:     } elsif ($error eq 'doublebubble') {
 7424: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 7425: 
 7426: 	# The form field scantron_questions is acutally a list of line numbers.
 7427: 	# represented by this form so:
 7428: 
 7429: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 7430:                                                 $respnumlookup,$startline);
 7431: 
 7432: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7433: 		  $line_list.'" />');
 7434: 	$r->print($message);
 7435: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 7436: 	foreach my $question (@{$arg}) {
 7437: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7438:                                                    $scan_record, $error,
 7439:                                                    $randomorder,$randompick,
 7440:                                                    $respnumlookup,$startline);
 7441:             push(@lines_to_correct,@linenums);
 7442: 	}
 7443:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7444:     } elsif ($error eq 'missingbubble') {
 7445: 	$r->print('<p class="LC_warning">'.&mt("There have been [_1]no[_2] bubbles scanned for some question(s)",'<b>','</b>')."</p>\n");
 7446: 	$r->print($message);
 7447: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 7448: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 7449: 
 7450: 	# The form field scantron_questions is actually a list of line numbers not
 7451: 	# a list of question numbers. Therefore:
 7452: 	#
 7453: 
 7454: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 7455:                                                 $respnumlookup,$startline);
 7456: 
 7457: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7458: 		  $line_list.'" />');
 7459: 	foreach my $question (@{$arg}) {
 7460: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7461:                                                    $scan_record, $error,
 7462:                                                    $randomorder,$randompick,
 7463:                                                    $respnumlookup,$startline);
 7464:             push(@lines_to_correct,@linenums);
 7465: 	}
 7466:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7467:     } else {
 7468: 	$r->print("\n<ul>");
 7469:     }
 7470:     $r->print("\n</li></ul>");
 7471: }
 7472: 
 7473: sub verify_bubbles_checked {
 7474:     my (@ansnums) = @_;
 7475:     my $ansnumstr = join('","',@ansnums);
 7476:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 7477:     my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
 7478: function verify_bubble_radio(form) {
 7479:     var ansnumArray = new Array ("$ansnumstr");
 7480:     var need_bubble_count = 0;
 7481:     for (var i=0; i<ansnumArray.length; i++) {
 7482:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 7483:             var bubble_picked = 0; 
 7484:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 7485:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 7486:                     bubble_picked = 1;
 7487:                 }
 7488:             }
 7489:             if (bubble_picked == 0) {
 7490:                 need_bubble_count ++;
 7491:             }
 7492:         }
 7493:     }
 7494:     if (need_bubble_count) {
 7495:         alert("$warning");
 7496:         return;
 7497:     }
 7498:     form.submit(); 
 7499: }
 7500: ENDSCRIPT
 7501:     return $output;
 7502: }
 7503: 
 7504: =pod
 7505: 
 7506: =item  questions_to_line_list
 7507: 
 7508: Converts a list of questions into a string of comma separated
 7509: line numbers in the answer sheet used by the questions.  This is
 7510: used to fill in the scantron_questions form field.
 7511: 
 7512:   Arguments:
 7513:      questions    - Reference to an array of questions.
 7514:      randomorder  - True if randomorder in use.
 7515:      randompick   - True if randompick in use.
 7516:      respnumlookup - Reference to HASH mapping question numbers in bubble lines
 7517:                      for current line to question number used for same question
 7518:                      in "Master Seqence" (as seen by Course Coordinator).
 7519:      startline    - Reference to hash where key is question number (0 is first)
 7520:                     and key is number of first bubble line for current student
 7521:                     or code-based randompick and/or randomorder.
 7522: 
 7523: =cut
 7524: 
 7525: 
 7526: sub questions_to_line_list {
 7527:     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
 7528:     my @lines;
 7529: 
 7530:     foreach my $item (@{$questions}) {
 7531:         my $question = $item;
 7532:         my ($first,$count,$last);
 7533:         if ($item =~ /^(\d+)\.(\d+)$/) {
 7534:             $question = $1;
 7535:             my $subquestion = $2;
 7536:             my $responsenum = $question-1;
 7537:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7538:                 $responsenum = $respnumlookup->{$question-1};
 7539:                 if (ref($startline) eq 'HASH') {
 7540:                     $first = $startline->{$question-1} + 1;
 7541:                 }
 7542:             } else {
 7543:                 $first = $first_bubble_line{$responsenum} + 1;
 7544:             }
 7545:             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 7546:             my $subcount = 1;
 7547:             while ($subcount<$subquestion) {
 7548:                 $first += $subans[$subcount-1];
 7549:                 $subcount ++;
 7550:             }
 7551:             $count = $subans[$subquestion-1];
 7552:         } else {
 7553:             my $responsenum = $question-1;
 7554:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7555:                 $responsenum = $respnumlookup->{$question-1};
 7556:                 if (ref($startline) eq 'HASH') {
 7557:                     $first = $startline->{$question-1} + 1;
 7558:                 }
 7559:             } else {
 7560:                 $first = $first_bubble_line{$responsenum} + 1;
 7561:             }
 7562: 	    $count   = $bubble_lines_per_response{$responsenum};
 7563:         }
 7564:         $last = $first+$count-1;
 7565:         push(@lines, ($first..$last));
 7566:     }
 7567:     return join(',', @lines);
 7568: }
 7569: 
 7570: =pod 
 7571: 
 7572: =item prompt_for_corrections
 7573: 
 7574: Prompts for a potentially multiline correction to the
 7575: user's bubbling (factors out common code from scantron_get_correction
 7576: for multi and missing bubble cases).
 7577: 
 7578:  Arguments:
 7579:    $r           - Apache request object.
 7580:    $question    - The question number to prompt for.
 7581:    $scan_config - The scantron file configuration hash.
 7582:    $scan_record - Reference to the hash that has the the parsed scanlines.
 7583:    $error       - Type of error
 7584:    $randomorder - True if randomorder in use.
 7585:    $randompick  - True if randompick in use.
 7586:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
 7587:                     for current line to question number used for same question
 7588:                     in "Master Seqence" (as seen by Course Coordinator).
 7589:    $startline   - Reference to hash where key is question number (0 is first)
 7590:                   and value is number of first bubble line for current student
 7591:                   or code-based randompick and/or randomorder.
 7592: 
 7593: 
 7594:  Implicit inputs:
 7595:    %bubble_lines_per_response   - Starting line numbers for each question.
 7596:                                   Numbered from 0 (but question numbers are from
 7597:                                   1.
 7598:    %first_bubble_line           - Starting bubble line for each question.
 7599:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 7600:                                   type problems render as separate sub-questions, 
 7601:                                   in exam mode. This hash contains a 
 7602:                                   comma-separated list of the lines per 
 7603:                                   sub-question.
 7604:    %responsetype_per_response   - essayresponse, formularesponse,
 7605:                                   stringresponse, imageresponse, reactionresponse,
 7606:                                   and organicresponse type problem parts can have
 7607:                                   multiple lines per response if the weight
 7608:                                   assigned exceeds 10.  In this case, only
 7609:                                   one bubble per line is permitted, but more 
 7610:                                   than one line might contain bubbles, e.g.
 7611:                                   bubbling of: line 1 - J, line 2 - J, 
 7612:                                   line 3 - B would assign 22 points.  
 7613: 
 7614: =cut
 7615: 
 7616: sub prompt_for_corrections {
 7617:     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
 7618:         $randompick, $respnumlookup, $startline) = @_;
 7619:     my ($current_line,$lines);
 7620:     my @linenums;
 7621:     my $questionnum = $question;
 7622:     my ($first,$responsenum);
 7623:     if ($question =~ /^(\d+)\.(\d+)$/) {
 7624:         $question = $1;
 7625:         my $subquestion = $2;
 7626:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7627:             $responsenum = $respnumlookup->{$question-1};
 7628:             if (ref($startline) eq 'HASH') {
 7629:                 $first = $startline->{$question-1};
 7630:             }
 7631:         } else {
 7632:             $responsenum = $question-1;
 7633:             $first = $first_bubble_line{$responsenum};
 7634:         }
 7635:         $current_line = $first + 1 ;
 7636:         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 7637:         my $subcount = 1;
 7638:         while ($subcount<$subquestion) {
 7639:             $current_line += $subans[$subcount-1];
 7640:             $subcount ++;
 7641:         }
 7642:         $lines = $subans[$subquestion-1];
 7643:     } else {
 7644:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7645:             $responsenum = $respnumlookup->{$question-1};
 7646:             if (ref($startline) eq 'HASH') { 
 7647:                 $first = $startline->{$question-1};
 7648:             }
 7649:         } else {
 7650:             $responsenum = $question-1;
 7651:             $first = $first_bubble_line{$responsenum};
 7652:         }
 7653:         $current_line = $first + 1;
 7654:         $lines        = $bubble_lines_per_response{$responsenum};
 7655:     }
 7656:     if ($lines > 1) {
 7657:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 7658:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 7659:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 7660:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 7661:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 7662:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 7663:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 7664:             $r->print(
 7665:                 &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)
 7666:                .'<br /><br />'
 7667:                .&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.')
 7668:                .'<br />'
 7669:                .&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.')
 7670:                .'<br />'
 7671:                .&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.")
 7672:                .'<br /><br />'
 7673:             );
 7674:         } else {
 7675:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 7676:         }
 7677:     }
 7678:     for (my $i =0; $i < $lines; $i++) {
 7679:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 7680: 	&scantron_bubble_selector($r,$scan_config,$current_line,
 7681: 	        		  $questionnum,$error,split('', $selected));
 7682:         push(@linenums,$current_line);
 7683: 	$current_line++;
 7684:     }
 7685:     if ($lines > 1) {
 7686: 	$r->print("<hr /><br />");
 7687:     }
 7688:     return @linenums;
 7689: }
 7690: 
 7691: =pod
 7692: 
 7693: =item scantron_bubble_selector
 7694:   
 7695:    Generates the html radiobuttons to correct a single bubble line
 7696:    possibly showing the existing the selected bubbles if known
 7697: 
 7698:  Arguments:
 7699:     $r           - Apache request object
 7700:     $scan_config - hash from &get_scantron_config()
 7701:     $line        - Number of the line being displayed.
 7702:     $questionnum - Question number (may include subquestion)
 7703:     $error       - Type of error.
 7704:     @selected    - Array of bubbles picked on this line.
 7705: 
 7706: =cut
 7707: 
 7708: sub scantron_bubble_selector {
 7709:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 7710:     my $max=$$scan_config{'Qlength'};
 7711: 
 7712:     my $scmode=$$scan_config{'Qon'};
 7713:     if ($scmode eq 'number' || $scmode eq 'letter') { 
 7714:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
 7715:             ($$scan_config{'BubblesPerRow'} > 0)) {
 7716:             $max=$$scan_config{'BubblesPerRow'};
 7717:             if (($scmode eq 'number') && ($max > 10)) {
 7718:                 $max = 10;
 7719:             } elsif (($scmode eq 'letter') && $max > 26) {
 7720:                 $max = 26;
 7721:             }
 7722:         } else {
 7723:             $max = 10;
 7724:         }
 7725:     }
 7726: 
 7727:     my @alphabet=('A'..'Z');
 7728:     $r->print(&Apache::loncommon::start_data_table().
 7729:               &Apache::loncommon::start_data_table_row());
 7730:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 7731:     for (my $i=0;$i<$max+1;$i++) {
 7732: 	$r->print("\n".'<td align="center">');
 7733: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 7734: 	else { $r->print('&nbsp;'); }
 7735: 	$r->print('</td>');
 7736:     }
 7737:     $r->print(&Apache::loncommon::end_data_table_row().
 7738:               &Apache::loncommon::start_data_table_row());
 7739:     for (my $i=0;$i<$max;$i++) {
 7740: 	$r->print("\n".
 7741: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 7742: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 7743:     }
 7744:     my $nobub_checked = ' ';
 7745:     if ($error eq 'missingbubble') {
 7746:         $nobub_checked = ' checked = "checked" ';
 7747:     }
 7748:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 7749: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 7750:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 7751:               $line.'" value="'.$questionnum.'" /></td>');
 7752:     $r->print(&Apache::loncommon::end_data_table_row().
 7753:               &Apache::loncommon::end_data_table());
 7754: }
 7755: 
 7756: =pod
 7757: 
 7758: =item num_matches
 7759: 
 7760:    Counts the number of characters that are the same between the two arguments.
 7761: 
 7762:  Arguments:
 7763:    $orig - CODE from the scanline
 7764:    $code - CODE to match against
 7765: 
 7766:  Returns:
 7767:    $count - integer count of the number of same characters between the
 7768:             two arguments
 7769: 
 7770: =cut
 7771: 
 7772: sub num_matches {
 7773:     my ($orig,$code) = @_;
 7774:     my @code=split(//,$code);
 7775:     my @orig=split(//,$orig);
 7776:     my $same=0;
 7777:     for (my $i=0;$i<scalar(@code);$i++) {
 7778: 	if ($code[$i] eq $orig[$i]) { $same++; }
 7779:     }
 7780:     return $same;
 7781: }
 7782: 
 7783: =pod
 7784: 
 7785: =item scantron_get_closely_matching_CODEs
 7786: 
 7787:    Cycles through all CODEs and finds the set that has the greatest
 7788:    number of same characters as the provided CODE
 7789: 
 7790:  Arguments:
 7791:    $allcodes - hash ref returned by &get_codes()
 7792:    $CODE     - CODE from the current scanline
 7793: 
 7794:  Returns:
 7795:    2 element list
 7796:     - first elements is number of how closely matching the best fit is 
 7797:       (5 means best set has 5 matching characters)
 7798:     - second element is an arrary ref containing the set of valid CODEs
 7799:       that best fit the passed in CODE
 7800: 
 7801: =cut
 7802: 
 7803: sub scantron_get_closely_matching_CODEs {
 7804:     my ($allcodes,$CODE)=@_;
 7805:     my @CODEs;
 7806:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 7807: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 7808:     }
 7809: 
 7810:     return ($#CODEs,$CODEs[-1]);
 7811: }
 7812: 
 7813: =pod
 7814: 
 7815: =item get_codes
 7816: 
 7817:    Builds a hash which has keys of all of the valid CODEs from the selected
 7818:    set of remembered CODEs.
 7819: 
 7820:  Arguments:
 7821:   $old_name - name of the set of remembered CODEs
 7822:   $cdom     - domain of the course
 7823:   $cnum     - internal course name
 7824: 
 7825:  Returns:
 7826:   %allcodes - keys are the valid CODEs, values are all 1
 7827: 
 7828: =cut
 7829: 
 7830: sub get_codes {
 7831:     my ($old_name, $cdom, $cnum) = @_;
 7832:     if (!$old_name) {
 7833: 	$old_name=$env{'form.scantron_CODElist'};
 7834:     }
 7835:     if (!$cdom) {
 7836: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 7837:     }
 7838:     if (!$cnum) {
 7839: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 7840:     }
 7841:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 7842: 				    $cdom,$cnum);
 7843:     my %allcodes;
 7844:     if ($result{"type\0$old_name"} eq 'number') {
 7845: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 7846:     } else {
 7847: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 7848:     }
 7849:     return %allcodes;
 7850: }
 7851: 
 7852: =pod
 7853: 
 7854: =item scantron_validate_CODE
 7855: 
 7856:    Validates all scanlines in the selected file to not have any
 7857:    invalid or underspecified CODEs and that none of the codes are
 7858:    duplicated if this was requested.
 7859: 
 7860: =cut
 7861: 
 7862: sub scantron_validate_CODE {
 7863:     my ($r,$currentphase) = @_;
 7864:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7865:     if ($scantron_config{'CODElocation'} &&
 7866: 	$scantron_config{'CODEstart'} &&
 7867: 	$scantron_config{'CODElength'}) {
 7868: 	if (!defined($env{'form.scantron_CODElist'})) {
 7869: 	    &FIXME_blow_up()
 7870: 	}
 7871:     } else {
 7872: 	return (0,$currentphase+1);
 7873:     }
 7874:     
 7875:     my %usedCODEs;
 7876: 
 7877:     my %allcodes=&get_codes();
 7878: 
 7879:     my $nav_error;
 7880:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
 7881:     if ($nav_error) {
 7882:         $r->print(&navmap_errormsg());
 7883:         return(1,$currentphase);
 7884:     }
 7885: 
 7886:     my ($scanlines,$scan_data)=&scantron_getfile();
 7887:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7888: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7889: 	if ($line=~/^[\s\cz]*$/) { next; }
 7890: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7891: 						 $scan_data);
 7892: 	my $CODE=$$scan_record{'scantron.CODE'};
 7893: 	my $error=0;
 7894: 	if (!&Apache::lonnet::validCODE($CODE)) {
 7895: 	    &scantron_get_correction($r,$i,$scan_record,
 7896: 				     \%scantron_config,
 7897: 				     $line,'incorrectCODE',\%allcodes);
 7898: 	    return(1,$currentphase);
 7899: 	}
 7900: 	if (%allcodes && !exists($allcodes{$CODE}) 
 7901: 	    && !$$scan_record{'scantron.useCODE'}) {
 7902: 	    &scantron_get_correction($r,$i,$scan_record,
 7903: 				     \%scantron_config,
 7904: 				     $line,'incorrectCODE',\%allcodes);
 7905: 	    return(1,$currentphase);
 7906: 	}
 7907: 	if (exists($usedCODEs{$CODE}) 
 7908: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 7909: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 7910: 	    &scantron_get_correction($r,$i,$scan_record,
 7911: 				     \%scantron_config,
 7912: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 7913: 	    return(1,$currentphase);
 7914: 	}
 7915: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 7916:     }
 7917:     return (0,$currentphase+1);
 7918: }
 7919: 
 7920: =pod
 7921: 
 7922: =item scantron_validate_doublebubble
 7923: 
 7924:    Validates all scanlines in the selected file to not have any
 7925:    bubble lines with multiple bubbles marked.
 7926: 
 7927: =cut
 7928: 
 7929: sub scantron_validate_doublebubble {
 7930:     my ($r,$currentphase) = @_;
 7931:     #get student info
 7932:     my $classlist=&Apache::loncoursedata::get_classlist();
 7933:     my %idmap=&username_to_idmap($classlist);
 7934:     my (undef,undef,$sequence)=
 7935:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 7936: 
 7937:     #get scantron line setup
 7938:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7939:     my ($scanlines,$scan_data)=&scantron_getfile();
 7940: 
 7941:     my $navmap = Apache::lonnavmaps::navmap->new();
 7942:     unless (ref($navmap)) {
 7943:         $r->print(&navmap_errormsg());
 7944:         return(1,$currentphase);
 7945:     }
 7946:     my $map=$navmap->getResourceByUrl($sequence);
 7947:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7948:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 7949:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 7950:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 7951: 
 7952:     my $nav_error;
 7953:     if (ref($map)) {
 7954:         $randomorder = $map->randomorder();
 7955:         $randompick = $map->randompick();
 7956:         if ($randomorder || $randompick) {
 7957:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 7958:             if ($nav_error) {
 7959:                 $r->print(&navmap_errormsg());
 7960:                 return(1,$currentphase);
 7961:             }
 7962:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 7963:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 7964:         }
 7965:     } else {
 7966:         $r->print(&navmap_errormsg());
 7967:         return(1,$currentphase);
 7968:     }
 7969: 
 7970:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
 7971:     if ($nav_error) {
 7972:         $r->print(&navmap_errormsg());
 7973:         return(1,$currentphase);
 7974:     }
 7975: 
 7976:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7977: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7978: 	if ($line=~/^[\s\cz]*$/) { next; }
 7979: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7980: 						 $scan_data,undef,\%idmap,$randomorder,
 7981:                                                  $randompick,$sequence,\@master_seq,
 7982:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 7983:                                                  \%orderedforcode,\%respnumlookup,\%startline);
 7984: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 7985: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 7986: 				 'doublebubble',
 7987: 				 $$scan_record{'scantron.doubleerror'},
 7988:                                  $randomorder,$randompick,\%respnumlookup,\%startline);
 7989:     	return (1,$currentphase);
 7990:     }
 7991:     return (0,$currentphase+1);
 7992: }
 7993: 
 7994: 
 7995: sub scantron_get_maxbubble {
 7996:     my ($nav_error,$scantron_config) = @_;
 7997:     if (defined($env{'form.scantron_maxbubble'}) &&
 7998: 	$env{'form.scantron_maxbubble'}) {
 7999: 	&restore_bubble_lines();
 8000: 	return $env{'form.scantron_maxbubble'};
 8001:     }
 8002: 
 8003:     my (undef, undef, $sequence) =
 8004: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8005: 
 8006:     my $navmap=Apache::lonnavmaps::navmap->new();
 8007:     unless (ref($navmap)) {
 8008:         if (ref($nav_error)) {
 8009:             $$nav_error = 1;
 8010:         }
 8011:         return;
 8012:     }
 8013:     my $map=$navmap->getResourceByUrl($sequence);
 8014:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8015:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
 8016: 
 8017:     &Apache::lonxml::clear_problem_counter();
 8018: 
 8019:     my $uname       = $env{'user.name'};
 8020:     my $udom        = $env{'user.domain'};
 8021:     my $cid         = $env{'request.course.id'};
 8022:     my $total_lines = 0;
 8023:     %bubble_lines_per_response = ();
 8024:     %first_bubble_line         = ();
 8025:     %subdivided_bubble_lines   = ();
 8026:     %responsetype_per_response = ();
 8027:     %masterseq_id_responsenum  = ();
 8028: 
 8029:     my $response_number = 0;
 8030:     my $bubble_line     = 0;
 8031:     foreach my $resource (@resources) {
 8032:         my $resid = $resource->id(); 
 8033:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
 8034:                                                           $udom,undef,$bubbles_per_row);
 8035:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 8036: 	    foreach my $part_id (@{$parts}) {
 8037:                 my $lines;
 8038: 
 8039: 	        # TODO - make this a persistent hash not an array.
 8040: 
 8041:                 # optionresponse, matchresponse and rankresponse type items 
 8042:                 # render as separate sub-questions in exam mode.
 8043:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 8044:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 8045:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 8046:                     my ($numbub,$numshown);
 8047:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 8048:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 8049:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 8050:                         }
 8051:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 8052:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 8053:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 8054:                         }
 8055:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 8056:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 8057:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 8058:                         }
 8059:                     }
 8060:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 8061:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 8062:                     }
 8063:                     my $bubbles_per_row =
 8064:                         &bubblesheet_bubbles_per_row($scantron_config);
 8065:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
 8066:                     if (($numbub % $bubbles_per_row) != 0) {
 8067:                         $inner_bubble_lines++;
 8068:                     }
 8069:                     for (my $i=0; $i<$numshown; $i++) {
 8070:                         $subdivided_bubble_lines{$response_number} .= 
 8071:                             $inner_bubble_lines.',';
 8072:                     }
 8073:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 8074:                     $lines = $numshown * $inner_bubble_lines;
 8075:                 } else {
 8076:                     $lines = $analysis->{"$part_id.bubble_lines"};
 8077:                 }
 8078: 
 8079:                 $first_bubble_line{$response_number} = $bubble_line;
 8080: 	        $bubble_lines_per_response{$response_number} = $lines;
 8081:                 $responsetype_per_response{$response_number} = 
 8082:                     $analysis->{$part_id.'.type'};
 8083:                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;  
 8084: 	        $response_number++;
 8085: 
 8086: 	        $bubble_line +=  $lines;
 8087: 	        $total_lines +=  $lines;
 8088: 	    }
 8089:         }
 8090:     }
 8091:     &Apache::lonnet::delenv('scantron.');
 8092: 
 8093:     &save_bubble_lines();
 8094:     $env{'form.scantron_maxbubble'} =
 8095: 	$total_lines;
 8096:     return $env{'form.scantron_maxbubble'};
 8097: }
 8098: 
 8099: sub bubblesheet_bubbles_per_row {
 8100:     my ($scantron_config) = @_;
 8101:     my $bubbles_per_row;
 8102:     if (ref($scantron_config) eq 'HASH') {
 8103:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
 8104:     }
 8105:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
 8106:         $bubbles_per_row = 10;
 8107:     }
 8108:     return $bubbles_per_row;
 8109: }
 8110: 
 8111: sub scantron_validate_missingbubbles {
 8112:     my ($r,$currentphase) = @_;
 8113:     #get student info
 8114:     my $classlist=&Apache::loncoursedata::get_classlist();
 8115:     my %idmap=&username_to_idmap($classlist);
 8116:     my (undef,undef,$sequence)=
 8117:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8118: 
 8119:     #get scantron line setup
 8120:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8121:     my ($scanlines,$scan_data)=&scantron_getfile();
 8122: 
 8123:     my $navmap = Apache::lonnavmaps::navmap->new();
 8124:     unless (ref($navmap)) {
 8125:         $r->print(&navmap_errormsg());
 8126:         return(1,$currentphase);
 8127:     }
 8128: 
 8129:     my $map=$navmap->getResourceByUrl($sequence);
 8130:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8131:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8132:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 8133:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8134: 
 8135:     my $nav_error;
 8136:     if (ref($map)) {
 8137:         $randomorder = $map->randomorder();
 8138:         $randompick = $map->randompick();
 8139:         if ($randomorder || $randompick) {
 8140:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8141:             if ($nav_error) {
 8142:                 $r->print(&navmap_errormsg());
 8143:                 return(1,$currentphase);
 8144:             }
 8145:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8146:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 8147:         }
 8148:     } else {
 8149:         $r->print(&navmap_errormsg());
 8150:         return(1,$currentphase);
 8151:     }
 8152: 
 8153: 
 8154:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 8155:     if ($nav_error) {
 8156:         $r->print(&navmap_errormsg());
 8157:         return(1,$currentphase);
 8158:     }
 8159: 
 8160:     if (!$max_bubble) { $max_bubble=2**31; }
 8161:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8162: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8163: 	if ($line=~/^[\s\cz]*$/) { next; }
 8164: 	my $scan_record =
 8165:             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
 8166: 				     $randomorder,$randompick,$sequence,\@master_seq,
 8167:                                      \%symb_to_resource,\%grader_partids_by_symb,
 8168:                                      \%orderedforcode,\%respnumlookup,\%startline);
 8169: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 8170: 	my @to_correct;
 8171: 	
 8172: 	# Probably here's where the error is...
 8173: 
 8174: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 8175:             my $lastbubble;
 8176:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 8177:                my $question = $1;
 8178:                my $subquestion = $2;
 8179:                my ($first,$responsenum);
 8180:                if ($randomorder || $randompick) {
 8181:                    $responsenum = $respnumlookup{$question-1};
 8182:                    $first = $startline{$question-1};
 8183:                } else {
 8184:                    $responsenum = $question-1; 
 8185:                    $first = $first_bubble_line{$responsenum};
 8186:                }
 8187:                if (!defined($first)) { next; }
 8188:                my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8189:                my $subcount = 1;
 8190:                while ($subcount<$subquestion) {
 8191:                    $first += $subans[$subcount-1];
 8192:                    $subcount ++;
 8193:                }
 8194:                my $count = $subans[$subquestion-1];
 8195:                $lastbubble = $first + $count;
 8196:             } else {
 8197:                my ($first,$responsenum);
 8198:                if ($randomorder || $randompick) {
 8199:                    $responsenum = $respnumlookup{$missing-1};
 8200:                    $first = $startline{$missing-1};
 8201:                } else {
 8202:                    $responsenum = $missing-1;
 8203:                    $first = $first_bubble_line{$responsenum};
 8204:                }
 8205:                if (!defined($first)) { next; }
 8206:                $lastbubble = $first + $bubble_lines_per_response{$responsenum};
 8207:             }
 8208:             if ($lastbubble > $max_bubble) { next; }
 8209: 	    push(@to_correct,$missing);
 8210: 	}
 8211: 	if (@to_correct) {
 8212: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 8213: 				     $line,'missingbubble',\@to_correct,
 8214:                                      $randomorder,$randompick,\%respnumlookup,
 8215:                                      \%startline);
 8216: 	    return (1,$currentphase);
 8217: 	}
 8218: 
 8219:     }
 8220:     return (0,$currentphase+1);
 8221: }
 8222: 
 8223: sub hand_bubble_option {
 8224:     my (undef, undef, $sequence) =
 8225:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8226:     return if ($sequence eq '');
 8227:     my $navmap = Apache::lonnavmaps::navmap->new();
 8228:     unless (ref($navmap)) {
 8229:         return;
 8230:     }
 8231:     my $needs_hand_bubbles;
 8232:     my $map=$navmap->getResourceByUrl($sequence);
 8233:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8234:     foreach my $res (@resources) {
 8235:         if (ref($res)) {
 8236:             if ($res->is_problem()) {
 8237:                 my $partlist = $res->parts();
 8238:                 foreach my $part (@{ $partlist }) {
 8239:                     my @types = $res->responseType($part);
 8240:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
 8241:                         $needs_hand_bubbles = 1;
 8242:                         last;
 8243:                     }
 8244:                 }
 8245:             }
 8246:         }
 8247:     }
 8248:     if ($needs_hand_bubbles) {
 8249:         my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8250:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8251:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
 8252:                &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 />').
 8253:                '<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;'.
 8254:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0"/>'.&mt('0 points').'</label></p>';
 8255:     }
 8256:     return;
 8257: }
 8258: 
 8259: sub scantron_process_students {
 8260:     my ($r,$symb) = @_;
 8261: 
 8262:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8263:     if (!$symb) {
 8264: 	return '';
 8265:     }
 8266:     my $default_form_data=&defaultFormData($symb);
 8267: 
 8268:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8269:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config); 
 8270:     my ($scanlines,$scan_data)=&scantron_getfile();
 8271:     my $classlist=&Apache::loncoursedata::get_classlist();
 8272:     my %idmap=&username_to_idmap($classlist);
 8273:     my $navmap=Apache::lonnavmaps::navmap->new();
 8274:     unless (ref($navmap)) {
 8275:         $r->print(&navmap_errormsg());
 8276:         return '';
 8277:     }
 8278:     my $map=$navmap->getResourceByUrl($sequence);
 8279:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8280:         %grader_randomlists_by_symb);
 8281:     if (ref($map)) {
 8282:         $randomorder = $map->randomorder();
 8283:         $randompick = $map->randompick();
 8284:     } else {
 8285:         $r->print(&navmap_errormsg());
 8286:         return '';
 8287:     }
 8288:     my $nav_error;
 8289:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8290:     if ($randomorder || $randompick) {
 8291:         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8292:         if ($nav_error) {
 8293:             $r->print(&navmap_errormsg());
 8294:             return '';
 8295:         }
 8296:     }
 8297:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8298:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 8299: 
 8300:     my ($uname,$udom);
 8301:     my $result= <<SCANTRONFORM;
 8302: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 8303:   <input type="hidden" name="command" value="scantron_configphase" />
 8304:   $default_form_data
 8305: SCANTRONFORM
 8306:     $r->print($result);
 8307: 
 8308:     my @delayqueue;
 8309:     my (%completedstudents,%scandata);
 8310:     
 8311:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 8312:     my $count=&get_todo_count($scanlines,$scan_data);
 8313:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 8314:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
 8315:     $r->print('<br />');
 8316:     my $start=&Time::HiRes::time();
 8317:     my $i=-1;
 8318:     my $started;
 8319: 
 8320:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 8321:     if ($nav_error) {
 8322:         $r->print(&navmap_errormsg());
 8323:         return '';
 8324:     }
 8325: 
 8326:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 8327:     # the user and return.
 8328: 
 8329:     if ($ssi_error) {
 8330: 	$r->print("</form>");
 8331: 	&ssi_print_error($r);
 8332:         &Apache::lonnet::remove_lock($lock);
 8333: 	return '';		# Dunno why the other returns return '' rather than just returning.
 8334:     }
 8335: 
 8336:     my %lettdig = &letter_to_digits();
 8337:     my $numletts = scalar(keys(%lettdig));
 8338:     my %orderedforcode;
 8339: 
 8340:     while ($i<$scanlines->{'count'}) {
 8341:  	($uname,$udom)=('','');
 8342:  	$i++;
 8343:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8344:  	if ($line=~/^[\s\cz]*$/) { next; }
 8345: 	if ($started) {
 8346: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
 8347: 	}
 8348: 	$started=1;
 8349:         my %respnumlookup = ();
 8350:         my %startline = ();
 8351:         my $total;
 8352:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8353:                                                  $scan_data,undef,\%idmap,$randomorder,
 8354:                                                  $randompick,$sequence,\@master_seq,
 8355:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 8356:                                                  \%orderedforcode,\%respnumlookup,\%startline,
 8357:                                                  \$total);
 8358:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 8359:  					      \%idmap,$i)) {
 8360:   	    &scantron_add_delay(\@delayqueue,$line,
 8361:  				'Unable to find a student that matches',1);
 8362:  	    next;
 8363:   	}
 8364:  	if (exists $completedstudents{$uname}) {
 8365:  	    &scantron_add_delay(\@delayqueue,$line,
 8366:  				'Student '.$uname.' has multiple sheets',2);
 8367:  	    next;
 8368:  	}
 8369:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 8370:         my $user = $uname.':'.$usec;
 8371:   	($uname,$udom)=split(/:/,$uname);
 8372: 
 8373:         my $scancode;
 8374:         if ((exists($scan_record->{'scantron.CODE'})) &&
 8375:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 8376:             $scancode = $scan_record->{'scantron.CODE'};
 8377:         } else {
 8378:             $scancode = '';
 8379:         }
 8380: 
 8381:         my @mapresources = @resources;
 8382:         if ($randomorder || $randompick) {
 8383:             @mapresources = 
 8384:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
 8385:                              \%orderedforcode);
 8386:         }
 8387:         my (%partids_by_symb,$res_error);
 8388:         foreach my $resource (@mapresources) {
 8389:             my $ressymb;
 8390:             if (ref($resource)) {
 8391:                 $ressymb = $resource->symb();
 8392:             } else {
 8393:                 $res_error = 1;
 8394:                 last;
 8395:             }
 8396:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 8397:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 8398:                 my ($analysis,$parts) =
 8399:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 8400:                                               $uname,$udom,undef,$bubbles_per_row);
 8401:                 $partids_by_symb{$ressymb} = $parts;
 8402:             } else {
 8403:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
 8404:             }
 8405:         }
 8406: 
 8407:         if ($res_error) {
 8408:             &scantron_add_delay(\@delayqueue,$line,
 8409:                                 'An error occurred while grading student '.$uname,2);
 8410:             next;
 8411:         }
 8412: 
 8413: 	&Apache::lonxml::clear_problem_counter();
 8414:   	&Apache::lonnet::appenv($scan_record);
 8415: 
 8416: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 8417: 	    &scantron_putfile($scanlines,$scan_data);
 8418: 	}
 8419: 	
 8420:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 8421:                                    \@mapresources,\%partids_by_symb,
 8422:                                    $bubbles_per_row,$randomorder,$randompick,
 8423:                                    \%respnumlookup,\%startline) 
 8424:             eq 'ssi_error') {
 8425:             $ssi_error = 0; # So end of handler error message does not trigger.
 8426:             $r->print("</form>");
 8427:             &ssi_print_error($r);
 8428:             &Apache::lonnet::remove_lock($lock);
 8429:             return '';      # Why return ''?  Beats me.
 8430:         }
 8431: 
 8432:         if (($scancode) && ($randomorder || $randompick)) {
 8433:             my $parmresult =
 8434:                 &Apache::lonparmset::storeparm_by_symb($symb,
 8435:                                                        '0_examcode',2,$scancode,
 8436:                                                        'string_examcode',$uname,
 8437:                                                        $udom);
 8438:         }
 8439: 	$completedstudents{$uname}={'line'=>$line};
 8440:         if ($env{'form.verifyrecord'}) {
 8441:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 8442:             if ($randompick) {
 8443:                 if ($total) {
 8444:                     $lastpos = $total*$scantron_config{'Qlength'};
 8445:                 }
 8446:             }
 8447: 
 8448:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 8449:             chomp($studentdata);
 8450:             $studentdata =~ s/\r$//;
 8451:             my $studentrecord = '';
 8452:             my $counter = -1;
 8453:             foreach my $resource (@mapresources) {
 8454:                 my $ressymb = $resource->symb();
 8455:                 ($counter,my $recording) =
 8456:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 8457:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
 8458:                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
 8459:                                              $randompick,\%respnumlookup,\%startline);
 8460:                 $studentrecord .= $recording;
 8461:             }
 8462:             if ($studentrecord ne $studentdata) {
 8463:                 &Apache::lonxml::clear_problem_counter();
 8464:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 8465:                                            \@mapresources,\%partids_by_symb,
 8466:                                            $bubbles_per_row,$randomorder,$randompick,
 8467:                                            \%respnumlookup,\%startline) 
 8468:                     eq 'ssi_error') {
 8469:                     $ssi_error = 0; # So end of handler error message does not trigger.
 8470:                     $r->print("</form>");
 8471:                     &ssi_print_error($r);
 8472:                     &Apache::lonnet::remove_lock($lock);
 8473:                     delete($completedstudents{$uname});
 8474:                     return '';
 8475:                 }
 8476:                 $counter = -1;
 8477:                 $studentrecord = '';
 8478:                 foreach my $resource (@mapresources) {
 8479:                     my $ressymb = $resource->symb();
 8480:                     ($counter,my $recording) =
 8481:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 8482:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 8483:                                                  \%scantron_config,\%lettdig,$numletts,
 8484:                                                  $randomorder,$randompick,\%respnumlookup,
 8485:                                                  \%startline);
 8486:                     $studentrecord .= $recording;
 8487:                 }
 8488:                 if ($studentrecord ne $studentdata) {
 8489:                     $r->print('<p><span class="LC_warning">');
 8490:                     if ($scancode eq '') {
 8491:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
 8492:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 8493:                     } else {
 8494:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
 8495:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 8496:                     }
 8497:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 8498:                               &Apache::loncommon::start_data_table_header_row()."\n".
 8499:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 8500:                               &Apache::loncommon::end_data_table_header_row()."\n".
 8501:                               &Apache::loncommon::start_data_table_row().
 8502:                               '<td>'.&mt('Bubblesheet').'</td>'.
 8503:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
 8504:                               &Apache::loncommon::end_data_table_row().
 8505:                               &Apache::loncommon::start_data_table_row().
 8506:                               '<td>'.&mt('Stored submissions').'</td>'.
 8507:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
 8508:                               &Apache::loncommon::end_data_table_row().
 8509:                               &Apache::loncommon::end_data_table().'</p>');
 8510:                 } else {
 8511:                     $r->print('<br /><span class="LC_warning">'.
 8512:                              &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 />'.
 8513:                              &mt("As a consequence, this user's submission history records two tries.").
 8514:                                  '</span><br />');
 8515:                 }
 8516:             }
 8517:         }
 8518:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 8519:     } continue {
 8520: 	&Apache::lonxml::clear_problem_counter();
 8521: 	&Apache::lonnet::delenv('scantron.');
 8522:     }
 8523:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 8524:     &Apache::lonnet::remove_lock($lock);
 8525: #    my $lasttime = &Time::HiRes::time()-$start;
 8526: #    $r->print("<p>took $lasttime</p>");
 8527: 
 8528:     $r->print("</form>");
 8529:     return '';
 8530: }
 8531: 
 8532: sub graders_resources_pass {
 8533:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
 8534:         $bubbles_per_row) = @_;
 8535:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
 8536:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
 8537:         foreach my $resource (@{$resources}) {
 8538:             my $ressymb = $resource->symb();
 8539:             my ($analysis,$parts) =
 8540:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
 8541:                                           $env{'user.name'},$env{'user.domain'},
 8542:                                           1,$bubbles_per_row);
 8543:             $grader_partids_by_symb->{$ressymb} = $parts;
 8544:             if (ref($analysis) eq 'HASH') {
 8545:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 8546:                     $grader_randomlists_by_symb->{$ressymb} =
 8547:                         $analysis->{'parts_withrandomlist'};
 8548:                 }
 8549:             }
 8550:         }
 8551:     }
 8552:     return;
 8553: }
 8554: 
 8555: =pod
 8556: 
 8557: =item users_order
 8558: 
 8559:   Returns array of resources in current map, ordered based on either CODE,
 8560:   if this is a CODEd exam, or based on student's identity if this is a 
 8561:   "NAMEd" exam.
 8562: 
 8563:   Should be used when randomorder and/or randompick applied when the 
 8564:   corresponding exam was printed, prior to students completing bubblesheets 
 8565:   for the version of the exam the student received.
 8566: 
 8567: =cut
 8568: 
 8569: sub users_order  {
 8570:     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
 8571:     my @mapresources;
 8572:     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
 8573:         return @mapresources;
 8574:     }
 8575:     if ($scancode) {
 8576:         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
 8577:             @mapresources = @{$orderedforcode->{$scancode}};
 8578:         } else {
 8579:             $env{'form.CODE'} = $scancode;
 8580:             my $actual_seq =
 8581:                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 8582:                                                                $master_seq,
 8583:                                                                $user,$scancode,1);
 8584:             if (ref($actual_seq) eq 'ARRAY') {
 8585:                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
 8586:                 if (ref($orderedforcode) eq 'HASH') {
 8587:                     if (@mapresources > 0) { 
 8588:                         $orderedforcode->{$scancode} = \@mapresources;
 8589:                     }
 8590:                 }
 8591:             }
 8592:             delete($env{'form.CODE'});
 8593:         }
 8594:     } else {
 8595:         my $actual_seq =
 8596:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 8597:                                                            $master_seq,
 8598:                                                            $user,undef,1);
 8599:         if (ref($actual_seq) eq 'ARRAY') {
 8600:             @mapresources = 
 8601:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
 8602:         }
 8603:     }
 8604:     return @mapresources;
 8605: }
 8606: 
 8607: sub grade_student_bubbles {
 8608:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
 8609:         $randomorder,$randompick,$respnumlookup,$startline) = @_;
 8610:     my $uselookup = 0;
 8611:     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
 8612:         (ref($startline) eq 'HASH')) {
 8613:         $uselookup = 1;
 8614:     }
 8615: 
 8616:     if (ref($resources) eq 'ARRAY') {
 8617:         my $count = 0;
 8618:         foreach my $resource (@{$resources}) {
 8619:             my $ressymb = $resource->symb();
 8620:             my %form = ('submitted'      => 'scantron',
 8621:                         'grade_target'   => 'grade',
 8622:                         'grade_username' => $uname,
 8623:                         'grade_domain'   => $udom,
 8624:                         'grade_courseid' => $env{'request.course.id'},
 8625:                         'grade_symb'     => $ressymb,
 8626:                         'CODE'           => $scancode
 8627:                        );
 8628:             if ($bubbles_per_row ne '') {
 8629:                 $form{'bubbles_per_row'} = $bubbles_per_row;
 8630:             }
 8631:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
 8632:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
 8633:             }
 8634:             if (ref($parts) eq 'HASH') {
 8635:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 8636:                     foreach my $part (@{$parts->{$ressymb}}) {
 8637:                         if ($uselookup) {
 8638:                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
 8639:                         } else {
 8640:                             $form{'scantron_questnum_start.'.$part} =
 8641:                                 1+$env{'form.scantron.first_bubble_line.'.$count};
 8642:                         }
 8643:                         $count++;
 8644:                     }
 8645:                 }
 8646:             }
 8647:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 8648:             return 'ssi_error' if ($ssi_error);
 8649:             last if (&Apache::loncommon::connection_aborted($r));
 8650:         }
 8651:     }
 8652:     return;
 8653: }
 8654: 
 8655: sub scantron_upload_scantron_data {
 8656:     my ($r,$symb)=@_;
 8657:     my $dom = $env{'request.role.domain'};
 8658:     my $domdesc = &Apache::lonnet::domain($dom,'description');
 8659:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
 8660:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 8661: 							  'domainid',
 8662: 							  'coursename',$dom);
 8663:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
 8664:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
 8665:     my $default_form_data=&defaultFormData($symb);
 8666:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
 8667:     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.");
 8668:     $r->print(&Apache::lonhtmlcommon::scripttag('
 8669:     function checkUpload(formname) {
 8670: 	if (formname.upfile.value == "") {
 8671: 	    alert("'.$nofile_alert.'");
 8672: 	    return false;
 8673: 	}
 8674:         if (formname.courseid.value == "") {
 8675:             alert("'.$nocourseid_alert.'");
 8676:             return false;
 8677:         }
 8678: 	formname.submit();
 8679:     }
 8680: 
 8681:     function ToSyllabus() {
 8682:         var cdom = '."'$dom'".';
 8683:         var cnum = document.rules.courseid.value;
 8684:         if (cdom == "" || cdom == null) {
 8685:             return;
 8686:         }
 8687:         if (cnum == "" || cnum == null) {
 8688:            return;
 8689:         }
 8690:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
 8691:                             "height=350,width=350,scrollbars=yes,menubar=no");
 8692:         return;
 8693:     }
 8694: 
 8695: '));
 8696:     $r->print('
 8697: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
 8698: 
 8699: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 8700: '.$default_form_data.
 8701:   &Apache::lonhtmlcommon::start_pick_box().
 8702:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
 8703:   '<input name="courseid" type="text" size="30" />'.$select_link.
 8704:   &Apache::lonhtmlcommon::row_closure().
 8705:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
 8706:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
 8707:   &Apache::lonhtmlcommon::row_closure().
 8708:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
 8709:   '<input name="domainid" type="hidden" />'.$domdesc.
 8710:   &Apache::lonhtmlcommon::row_closure().
 8711:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
 8712:   '<input type="file" name="upfile" size="50" />'.
 8713:   &Apache::lonhtmlcommon::row_closure(1).
 8714:   &Apache::lonhtmlcommon::end_pick_box().'<br />
 8715: 
 8716: <input name="command" value="scantronupload_save" type="hidden" />
 8717: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 8718: </form>
 8719: ');
 8720:     return '';
 8721: }
 8722: 
 8723: 
 8724: sub scantron_upload_scantron_data_save {
 8725:     my($r,$symb)=@_;
 8726:     my $doanotherupload=
 8727: 	'<br /><form action="/adm/grades" method="post">'."\n".
 8728: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 8729: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 8730: 	'</form>'."\n";
 8731:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 8732: 	!&Apache::lonnet::allowed('usc',
 8733: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 8734: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
 8735: 	unless ($symb) {
 8736: 	    $r->print($doanotherupload);
 8737: 	}
 8738: 	return '';
 8739:     }
 8740:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 8741:     my $uploadedfile;
 8742:     $r->print('<p>'.&mt('Uploading file to [_1]','"'.$coursedata{'description'}.'"').'</p>');
 8743:     if (length($env{'form.upfile'}) < 2) {
 8744:         $r->print(
 8745:             &Apache::lonhtmlcommon::confirm_success(
 8746:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
 8747:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
 8748:     } else {
 8749:         my $result = 
 8750:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
 8751:                                             $env{'form.courseid'},$env{'form.domainid'});
 8752:         if ($result =~ m{^/uploaded/}) {
 8753:             $r->print(
 8754:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
 8755:                 &mt('Uploaded [_1] bytes of data into location: [_2]',
 8756:                         (length($env{'form.upfile'})-1),
 8757:                         '<span class="LC_filename">'.$result.'</span>'));
 8758:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
 8759:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
 8760:                                                        $env{'form.courseid'},$uploadedfile));
 8761:         } else {
 8762:             $r->print(
 8763:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
 8764:                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
 8765:                           $result,
 8766: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 8767: 	}
 8768:     }
 8769:     if ($symb) {
 8770: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
 8771:     } else {
 8772: 	$r->print($doanotherupload);
 8773:     }
 8774:     return '';
 8775: }
 8776: 
 8777: sub validate_uploaded_scantron_file {
 8778:     my ($cdom,$cname,$fname) = @_;
 8779:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
 8780:     my @lines;
 8781:     if ($scanlines ne '-1') {
 8782:         @lines=split("\n",$scanlines,-1);
 8783:     }
 8784:     my $output;
 8785:     if (@lines) {
 8786:         my (%counts,$max_match_format);
 8787:         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
 8788:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
 8789:         my %idmap = &username_to_idmap($classlist);
 8790:         foreach my $key (keys(%idmap)) {
 8791:             my $lckey = lc($key);
 8792:             $idmap{$lckey} = $idmap{$key};
 8793:         }
 8794:         my %unique_formats;
 8795:         my @formatlines = &get_scantronformat_file();
 8796:         foreach my $line (@formatlines) {
 8797:             chomp($line);
 8798:             my @config = split(/:/,$line);
 8799:             my $idstart = $config[5];
 8800:             my $idlength = $config[6];
 8801:             if (($idstart ne '') && ($idlength > 0)) {
 8802:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
 8803:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
 8804:                 } else {
 8805:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
 8806:                 }
 8807:             }
 8808:         }
 8809:         foreach my $key (keys(%unique_formats)) {
 8810:             my ($idstart,$idlength) = split(':',$key);
 8811:             %{$counts{$key}} = (
 8812:                                'found'   => 0,
 8813:                                'total'   => 0,
 8814:                               );
 8815:             foreach my $line (@lines) {
 8816:                 next if ($line =~ /^#/);
 8817:                 next if ($line =~ /^[\s\cz]*$/);
 8818:                 my $id = substr($line,$idstart-1,$idlength);
 8819:                 $id = lc($id);
 8820:                 if (exists($idmap{$id})) {
 8821:                     $counts{$key}{'found'} ++;
 8822:                 }
 8823:                 $counts{$key}{'total'} ++;
 8824:             }
 8825:             if ($counts{$key}{'total'}) {
 8826:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
 8827:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
 8828:                     $max_match_pct = $percent_match;
 8829:                     $max_match_format = $key;
 8830:                     $found_match_count = $counts{$key}{'found'};
 8831:                     $max_match_count = $counts{$key}{'total'};
 8832:                 }
 8833:             }
 8834:         }
 8835:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
 8836:             my $format_descs;
 8837:             my $numwithformat = @{$unique_formats{$max_match_format}};
 8838:             for (my $i=0; $i<$numwithformat; $i++) {
 8839:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
 8840:                 if ($i<$numwithformat-2) {
 8841:                     $format_descs .= '"<i>'.$desc.'</i>", ';
 8842:                 } elsif ($i==$numwithformat-2) {
 8843:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
 8844:                 } elsif ($i==$numwithformat-1) {
 8845:                     $format_descs .= '"<i>'.$desc.'</i>"';
 8846:                 }
 8847:             }
 8848:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
 8849:             $output .= '<br />';
 8850:             if ($found_match_count == $max_match_count) {
 8851:                 # 100% matching entries
 8852:                 $output .= &Apache::lonhtmlcommon::confirm_success(
 8853:                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
 8854:                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
 8855:                 &mt('Comparison of student IDs in the uploaded file with'.
 8856:                     ' the course roster found matches for [_1] of the [_2] entries'.
 8857:                     ' in the file (for the format defined for [_3]).',
 8858:                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
 8859:             } else {
 8860:                 # Not all entries matching? -> Show warning and additional info
 8861:                 $output .=
 8862:                     &Apache::lonhtmlcommon::confirm_success(
 8863:                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
 8864:                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
 8865:                         &mt('Not all entries could be matched!'),1).'<br />'.
 8866:                     &mt('Comparison of student IDs in the uploaded file with'.
 8867:                         ' the course roster found matches for [_1] of the [_2] entries'.
 8868:                         ' in the file (for the format defined for [_3]).',
 8869:                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
 8870:                     '<p class="LC_info">'.
 8871:                     &mt('A low percentage of matches results from one of the following:').
 8872:                     '</p><ul>'.
 8873:                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
 8874:                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
 8875:                                '<i>'.$cdom.'</i>').'</li>'.
 8876:                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
 8877:                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
 8878:                     '</ul>';
 8879:             }
 8880:         }
 8881:     } else {
 8882:         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
 8883:     }
 8884:     return $output;
 8885: }
 8886: 
 8887: sub valid_file {
 8888:     my ($requested_file)=@_;
 8889:     foreach my $filename (sort(&scantron_filenames())) {
 8890: 	if ($requested_file eq $filename) { return 1; }
 8891:     }
 8892:     return 0;
 8893: }
 8894: 
 8895: sub scantron_download_scantron_data {
 8896:     my ($r,$symb)=@_;
 8897:     my $default_form_data=&defaultFormData($symb);
 8898:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 8899:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8900:     my $file=$env{'form.scantron_selectfile'};
 8901:     if (! &valid_file($file)) {
 8902: 	$r->print('
 8903: 	<p>
 8904: 	    '.&mt('The requested filename was invalid.').'
 8905:         </p>
 8906: ');
 8907: 	return;
 8908:     }
 8909:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 8910:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 8911:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 8912:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 8913:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 8914:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 8915:     $r->print('
 8916:     <p>
 8917: 	'.&mt('[_1]Original[_2] file as uploaded by the bubblesheet office.',
 8918: 	      '<a href="'.$orig.'">','</a>').'
 8919:     </p>
 8920:     <p>
 8921: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 8922: 	      '<a href="'.$corrected.'">','</a>').'
 8923:     </p>
 8924:     <p>
 8925: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 8926: 	      '<a href="'.$skipped.'">','</a>').'
 8927:     </p>
 8928: ');
 8929:     return '';
 8930: }
 8931: 
 8932: sub checkscantron_results {
 8933:     my ($r,$symb) = @_;
 8934:     if (!$symb) {return '';}
 8935:     my $cid = $env{'request.course.id'};
 8936:     my %lettdig = &letter_to_digits();
 8937:     my $numletts = scalar(keys(%lettdig));
 8938:     my $cnum = $env{'course.'.$cid.'.num'};
 8939:     my $cdom = $env{'course.'.$cid.'.domain'};
 8940:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8941:     my %record;
 8942:     my %scantron_config =
 8943:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
 8944:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8945:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
 8946:     my $classlist=&Apache::loncoursedata::get_classlist();
 8947:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 8948:     my $navmap=Apache::lonnavmaps::navmap->new();
 8949:     unless (ref($navmap)) {
 8950:         $r->print(&navmap_errormsg());
 8951:         return '';
 8952:     }
 8953:     my $map=$navmap->getResourceByUrl($sequence);
 8954:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8955:         %grader_randomlists_by_symb,%orderedforcode);
 8956:     if (ref($map)) { 
 8957:         $randomorder=$map->randomorder();
 8958:         $randompick=$map->randompick();
 8959:     }
 8960:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8961:     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8962:     if ($nav_error) {
 8963:         $r->print(&navmap_errormsg());
 8964:         return '';
 8965:     }
 8966:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8967:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 8968:     my ($uname,$udom);
 8969:     my (%scandata,%lastname,%bylast);
 8970:     $r->print('
 8971: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 8972: 
 8973:     my @delayqueue;
 8974:     my %completedstudents;
 8975: 
 8976:     my $count=&get_todo_count($scanlines,$scan_data);
 8977:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 8978:     my ($username,$domain,$started);
 8979:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 8980:     if ($nav_error) {
 8981:         $r->print(&navmap_errormsg());
 8982:         return '';
 8983:     }
 8984: 
 8985:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
 8986:     my $start=&Time::HiRes::time();
 8987:     my $i=-1;
 8988: 
 8989:     while ($i<$scanlines->{'count'}) {
 8990:         ($username,$domain,$uname)=('','','');
 8991:         $i++;
 8992:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 8993:         if ($line=~/^[\s\cz]*$/) { next; }
 8994:         if ($started) {
 8995:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
 8996:         }
 8997:         $started=1;
 8998:         my $scan_record=
 8999:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 9000:                                                      $scan_data);
 9001:         unless ($uname=&scantron_find_student($scan_record,$scan_data,
 9002:                                               \%idmap,$i)) {
 9003:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 9004:                                 'Unable to find a student that matches',1);
 9005:             next;
 9006:         }
 9007:         if (exists $completedstudents{$uname}) {
 9008:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 9009:                                 'Student '.$uname.' has multiple sheets',2);
 9010:             next;
 9011:         }
 9012:         my $pid = $scan_record->{'scantron.ID'};
 9013:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 9014:         push(@{$bylast{$lastname{$pid}}},$pid);
 9015:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 9016:         my $user = $uname.':'.$usec;
 9017:         ($username,$domain)=split(/:/,$uname);
 9018: 
 9019:         my $scancode;
 9020:         if ((exists($scan_record->{'scantron.CODE'})) &&
 9021:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 9022:             $scancode = $scan_record->{'scantron.CODE'};
 9023:         } else {
 9024:             $scancode = '';
 9025:         }
 9026: 
 9027:         my @mapresources = @resources;
 9028:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 9029:         my %respnumlookup=();
 9030:         my %startline=();
 9031:         if ($randomorder || $randompick) {
 9032:             @mapresources =
 9033:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
 9034:                              \%orderedforcode);
 9035:             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
 9036:                                              $scan_record,\@master_seq,\%symb_to_resource,
 9037:                                              \%grader_partids_by_symb,\%orderedforcode,
 9038:                                              \%respnumlookup,\%startline);
 9039:             if ($randompick && $total) {
 9040:                 $lastpos = $total*$scantron_config{'Qlength'};
 9041:             }
 9042:         }
 9043:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 9044:         chomp($scandata{$pid});
 9045:         $scandata{$pid} =~ s/\r$//;
 9046: 
 9047:         my $counter = -1;
 9048:         foreach my $resource (@mapresources) {
 9049:             my $parts;
 9050:             my $ressymb = $resource->symb();
 9051:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 9052:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 9053:                 (my $analysis,$parts) =
 9054:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 9055:                                               $username,$domain,undef,
 9056:                                               $bubbles_per_row);
 9057:             } else {
 9058:                 $parts = $grader_partids_by_symb{$ressymb};
 9059:             }
 9060:             ($counter,my $recording) =
 9061:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
 9062:                                          $scandata{$pid},$parts,
 9063:                                          \%scantron_config,\%lettdig,$numletts,
 9064:                                          $randomorder,$randompick,
 9065:                                          \%respnumlookup,\%startline);
 9066:             $record{$pid} .= $recording;
 9067:         }
 9068:     }
 9069:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 9070:     $r->print('<br />');
 9071:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 9072:     $passed = 0;
 9073:     $failed = 0;
 9074:     $numstudents = 0;
 9075:     foreach my $last (sort(keys(%bylast))) {
 9076:         if (ref($bylast{$last}) eq 'ARRAY') {
 9077:             foreach my $pid (sort(@{$bylast{$last}})) {
 9078:                 my $showscandata = $scandata{$pid};
 9079:                 my $showrecord = $record{$pid};
 9080:                 $showscandata =~ s/\s/&nbsp;/g;
 9081:                 $showrecord =~ s/\s/&nbsp;/g;
 9082:                 if ($scandata{$pid} eq $record{$pid}) {
 9083:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 9084:                     $okstudents .= '<tr class="'.$css_class.'">'.
 9085: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 9086: '</tr>'."\n".
 9087: '<tr class="'.$css_class.'">'."\n".
 9088: '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
 9089:                     $passed ++;
 9090:                 } else {
 9091:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
 9092:                     $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".
 9093: '</tr>'."\n".
 9094: '<tr class="'.$css_class.'">'."\n".
 9095: '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
 9096: '</tr>'."\n";
 9097:                     $failed ++;
 9098:                 }
 9099:                 $numstudents ++;
 9100:             }
 9101:         }
 9102:     }
 9103:     $r->print(
 9104:         '<p>'
 9105:        .&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).',
 9106:             '<b>',
 9107:             $numstudents,
 9108:             '</b>',
 9109:             $env{'form.scantron_maxbubble'})
 9110:        .'</p>'
 9111:     );
 9112:     $r->print('<p>'
 9113:              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
 9114:              .'<br />'
 9115:              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
 9116:              .'</p>'
 9117:     );
 9118:     if ($passed) {
 9119:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
 9120:         $r->print(&Apache::loncommon::start_data_table()."\n".
 9121:                  &Apache::loncommon::start_data_table_header_row()."\n".
 9122:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 9123:                  &Apache::loncommon::end_data_table_header_row()."\n".
 9124:                  $okstudents."\n".
 9125:                  &Apache::loncommon::end_data_table().'<br />');
 9126:     }
 9127:     if ($failed) {
 9128:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
 9129:         $r->print(&Apache::loncommon::start_data_table()."\n".
 9130:                  &Apache::loncommon::start_data_table_header_row()."\n".
 9131:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 9132:                  &Apache::loncommon::end_data_table_header_row()."\n".
 9133:                  $badstudents."\n".
 9134:                  &Apache::loncommon::end_data_table()).'<br />'.
 9135:                  &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.');  
 9136:     }
 9137:     $r->print('</form><br />');
 9138:     return;
 9139: }
 9140: 
 9141: sub verify_scantron_grading {
 9142:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
 9143:         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
 9144:         $respnumlookup,$startline) = @_;
 9145:     my ($record,%expected,%startpos);
 9146:     return ($counter,$record) if (!ref($resource));
 9147:     return ($counter,$record) if (!$resource->is_problem());
 9148:     my $symb = $resource->symb();
 9149:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
 9150:     foreach my $part_id (@{$partids}) {
 9151:         $counter ++;
 9152:         $expected{$part_id} = 0;
 9153:         my $respnum = $counter;
 9154:         if ($randomorder || $randompick) {
 9155:             $respnum = $respnumlookup->{$counter};
 9156:             $startpos{$part_id} = $startline->{$counter} + 1;
 9157:         } else {
 9158:             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
 9159:         }
 9160:         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
 9161:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
 9162:             foreach my $item (@sub_lines) {
 9163:                 $expected{$part_id} += $item;
 9164:             }
 9165:         } else {
 9166:             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
 9167:         }
 9168:     }
 9169:     if ($symb) {
 9170:         my %recorded;
 9171:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
 9172:         if ($returnhash{'version'}) {
 9173:             my %lasthash=();
 9174:             my $version;
 9175:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 9176:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 9177:                     $lasthash{$key}=$returnhash{$version.':'.$key};
 9178:                 }
 9179:             }
 9180:             foreach my $key (keys(%lasthash)) {
 9181:                 if ($key =~ /\.scantron$/) {
 9182:                     my $value = &unescape($lasthash{$key});
 9183:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
 9184:                     if ($value eq '') {
 9185:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
 9186:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
 9187:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9188:                             }
 9189:                         }
 9190:                     } else {
 9191:                         my @tocheck;
 9192:                         my @items = split(//,$value);
 9193:                         if (($scantron_config->{'Qon'} eq 'letter') ||
 9194:                             ($scantron_config->{'Qon'} eq 'number')) {
 9195:                             if (@items < $expected{$part_id}) {
 9196:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
 9197:                                 my @singles = split(//,$fragment);
 9198:                                 foreach my $pos (@singles) {
 9199:                                     if ($pos eq ' ') {
 9200:                                         push(@tocheck,$pos);
 9201:                                     } else {
 9202:                                         my $next = shift(@items);
 9203:                                         push(@tocheck,$next);
 9204:                                     }
 9205:                                 }
 9206:                             } else {
 9207:                                 @tocheck = @items;
 9208:                             }
 9209:                             foreach my $letter (@tocheck) {
 9210:                                 if ($scantron_config->{'Qon'} eq 'letter') {
 9211:                                     if ($letter !~ /^[A-J]$/) {
 9212:                                         $letter = $scantron_config->{'Qoff'};
 9213:                                     }
 9214:                                     $recorded{$part_id} .= $letter;
 9215:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
 9216:                                     my $digit;
 9217:                                     if ($letter !~ /^[A-J]$/) {
 9218:                                         $digit = $scantron_config->{'Qoff'};
 9219:                                     } else {
 9220:                                         $digit = $lettdig->{$letter};
 9221:                                     }
 9222:                                     $recorded{$part_id} .= $digit;
 9223:                                 }
 9224:                             }
 9225:                         } else {
 9226:                             @tocheck = @items;
 9227:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
 9228:                                 my $curr_sub = shift(@tocheck);
 9229:                                 my $digit;
 9230:                                 if ($curr_sub =~ /^[A-J]$/) {
 9231:                                     $digit = $lettdig->{$curr_sub}-1;
 9232:                                 }
 9233:                                 if ($curr_sub eq 'J') {
 9234:                                     $digit += scalar($numletts);
 9235:                                 }
 9236:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 9237:                                     if ($j == $digit) {
 9238:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
 9239:                                     } else {
 9240:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9241:                                     }
 9242:                                 }
 9243:                             }
 9244:                         }
 9245:                     }
 9246:                 }
 9247:             }
 9248:         }
 9249:         foreach my $part_id (@{$partids}) {
 9250:             if ($recorded{$part_id} eq '') {
 9251:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
 9252:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 9253:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9254:                     }
 9255:                 }
 9256:             }
 9257:             $record .= $recorded{$part_id};
 9258:         }
 9259:     }
 9260:     return ($counter,$record);
 9261: }
 9262: 
 9263: sub letter_to_digits {
 9264:     my %lettdig = (
 9265:                     A => 1,
 9266:                     B => 2,
 9267:                     C => 3,
 9268:                     D => 4,
 9269:                     E => 5,
 9270:                     F => 6,
 9271:                     G => 7,
 9272:                     H => 8,
 9273:                     I => 9,
 9274:                     J => 0,
 9275:                   );
 9276:     return %lettdig;
 9277: }
 9278: 
 9279: 
 9280: #-------- end of section for handling grading scantron forms -------
 9281: #
 9282: #-------------------------------------------------------------------
 9283: 
 9284: #-------------------------- Menu interface -------------------------
 9285: #
 9286: #--- Href with symb and command ---
 9287: 
 9288: sub href_symb_cmd {
 9289:     my ($symb,$cmd)=@_;
 9290:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
 9291: }
 9292: 
 9293: sub grading_menu {
 9294:     my ($request,$symb) = @_;
 9295:     if (!$symb) {return '';}
 9296: 
 9297:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 9298:                   'command'=>'individual');
 9299:     
 9300:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9301: 
 9302:     $fields{'command'}='ungraded';
 9303:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9304: 
 9305:     $fields{'command'}='table';
 9306:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9307: 
 9308:     $fields{'command'}='all_for_one';
 9309:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9310: 
 9311:     $fields{'command'}='downloadfilesselect';
 9312:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9313: 
 9314:     $fields{'command'} = 'csvform';
 9315:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9316:     
 9317:     $fields{'command'} = 'processclicker';
 9318:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9319:     
 9320:     $fields{'command'} = 'scantron_selectphase';
 9321:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9322: 
 9323:     $fields{'command'} = 'initialverifyreceipt';
 9324:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9325:     
 9326:     my @menu = ({	categorytitle=>'Hand Grading',
 9327:             items =>[
 9328:                         {	linktext => 'Select individual students to grade',
 9329:                     		url => $url1a,
 9330:                     		permission => 'F',
 9331:                     		icon => 'grade_students.png',
 9332:                     		linktitle => 'Grade current resource for a selection of students.'
 9333:                         }, 
 9334:                         {       linktext => 'Grade ungraded submissions.',
 9335:                                 url => $url1b,
 9336:                                 permission => 'F',
 9337:                                 icon => 'ungrade_sub.png',
 9338:                                 linktitle => 'Grade all submissions that have not been graded yet.'
 9339:                         },
 9340: 
 9341:                         {       linktext => 'Grading table',
 9342:                                 url => $url1c,
 9343:                                 permission => 'F',
 9344:                                 icon => 'grading_table.png',
 9345:                                 linktitle => 'Grade current resource for all students.'
 9346:                         },
 9347:                         {       linktext => 'Grade page/folder for one student',
 9348:                                 url => $url1d,
 9349:                                 permission => 'F',
 9350:                                 icon => 'grade_PageFolder.png',
 9351:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
 9352:                         },
 9353:                         {       linktext => 'Download submissions',
 9354:                                 url => $url1e,
 9355:                                 permission => 'F',
 9356:                                 icon => 'download_sub.png',
 9357:                                 linktitle => 'Download all students submissions.'
 9358:                         }]},
 9359:                          { categorytitle=>'Automated Grading',
 9360:                items =>[
 9361: 
 9362:                 	    {	linktext => 'Upload Scores',
 9363:                     		url => $url2,
 9364:                     		permission => 'F',
 9365:                     		icon => 'uploadscores.png',
 9366:                     		linktitle => 'Specify a file containing the class scores for current resource.'
 9367:                 	    },
 9368:                 	    {	linktext => 'Process Clicker',
 9369:                     		url => $url3,
 9370:                     		permission => 'F',
 9371:                     		icon => 'addClickerInfoFile.png',
 9372:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
 9373:                 	    },
 9374:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
 9375:                     		url => $url4,
 9376:                     		permission => 'F',
 9377:                     		icon => 'bubblesheet.png',
 9378:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
 9379:                 	    },
 9380:                             {   linktext => 'Verify Receipt Number',
 9381:                                 url => $url5,
 9382:                                 permission => 'F',
 9383:                                 icon => 'receipt_number.png',
 9384:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
 9385:                             }
 9386: 
 9387:                     ]
 9388:             });
 9389: 
 9390:     # Create the menu
 9391:     my $Str;
 9392:     $Str .= '<form method="post" action="" name="gradingMenu">';
 9393:     $Str .= '<input type="hidden" name="command" value="" />'.
 9394:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 9395: 
 9396:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
 9397:     return $Str;    
 9398: }
 9399: 
 9400: 
 9401: sub ungraded {
 9402:     my ($request)=@_;
 9403:     &submit_options($request);
 9404: }
 9405: 
 9406: sub submit_options_sequence {
 9407:     my ($request,$symb) = @_;
 9408:     if (!$symb) {return '';}
 9409:     &commonJSfunctions($request);
 9410:     my $result;
 9411: 
 9412:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 9413:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 9414:     $result.=&selectfield(0).
 9415:             '<input type="hidden" name="command" value="pickStudentPage" />
 9416:             <div>
 9417:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 9418:             </div>
 9419:         </div>
 9420:   </form>';
 9421:     return $result;
 9422: }
 9423: 
 9424: sub submit_options_table {
 9425:     my ($request,$symb) = @_;
 9426:     if (!$symb) {return '';}
 9427:     &commonJSfunctions($request);
 9428:     my $result;
 9429: 
 9430:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 9431:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 9432: 
 9433:     $result.=&selectfield(0).
 9434:             '<input type="hidden" name="command" value="viewgrades" />
 9435:             <div>
 9436:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 9437:             </div>
 9438:         </div>
 9439:   </form>';
 9440:     return $result;
 9441: }
 9442: 
 9443: sub submit_options_download {
 9444:     my ($request,$symb) = @_;
 9445:     if (!$symb) {return '';}
 9446: 
 9447:     &commonJSfunctions($request);
 9448: 
 9449:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 9450:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 9451:     $result.='
 9452: <h2>
 9453:   '.&mt('Select Students for Which to Download Submissions').'
 9454: </h2>'.&selectfield(1).'
 9455:                 <input type="hidden" name="command" value="downloadfileslink" /> 
 9456:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 9457:             </div>
 9458:           </div>
 9459: 
 9460: 
 9461:   </form>';
 9462:     return $result;
 9463: }
 9464: 
 9465: #--- Displays the submissions first page -------
 9466: sub submit_options {
 9467:     my ($request,$symb) = @_;
 9468:     if (!$symb) {return '';}
 9469: 
 9470:     &commonJSfunctions($request);
 9471:     my $result;
 9472: 
 9473:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 9474: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 9475:     $result.=&selectfield(1).'
 9476:                 <input type="hidden" name="command" value="submission" /> 
 9477: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
 9478:             </div>
 9479:           </div>
 9480: 
 9481: 
 9482:   </form>';
 9483:     return $result;
 9484: }
 9485: 
 9486: sub selectfield {
 9487:    my ($full)=@_;
 9488:    my %options = 
 9489:           (&Apache::lonlocal::texthash(
 9490:              'yes'       => 'with submissions',
 9491:              'queued'    => 'in grading queue',
 9492:              'graded'    => 'with ungraded submissions',
 9493:              'incorrect' => 'with incorrect submissions',
 9494:              'all'       => 'with any status'),
 9495:              'select_form_order' => ['yes','queued','graded','incorrect','all']);
 9496:    my $result='<div class="LC_columnSection">
 9497:   
 9498:     <fieldset>
 9499:       <legend>
 9500:        '.&mt('Sections').'
 9501:       </legend>
 9502:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
 9503:     </fieldset>
 9504:   
 9505:     <fieldset>
 9506:       <legend>
 9507:         '.&mt('Groups').'
 9508:       </legend>
 9509:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
 9510:     </fieldset>
 9511:   
 9512:     <fieldset>
 9513:       <legend>
 9514:         '.&mt('Access Status').'
 9515:       </legend>
 9516:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
 9517:     </fieldset>';
 9518:     if ($full) {
 9519:        $result.='
 9520:     <fieldset>
 9521:       <legend>
 9522:         '.&mt('Submission Status').'
 9523:       </legend>'.
 9524:        &Apache::loncommon::select_form('all','submitonly',\%options).
 9525:    '</fieldset>';
 9526:     }
 9527:     $result.='</div><br />';
 9528:     return $result;
 9529: }
 9530: 
 9531: sub reset_perm {
 9532:     undef(%perm);
 9533: }
 9534: 
 9535: sub init_perm {
 9536:     &reset_perm();
 9537:     foreach my $test_perm ('vgr','mgr','opa') {
 9538: 
 9539: 	my $scope = $env{'request.course.id'};
 9540: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
 9541: 
 9542: 	    $scope .= '/'.$env{'request.course.sec'};
 9543: 	    if ( $perm{$test_perm}=
 9544: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
 9545: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
 9546: 	    } else {
 9547: 		delete($perm{$test_perm});
 9548: 	    }
 9549: 	}
 9550:     }
 9551: }
 9552: 
 9553: sub init_old_essays {
 9554:     my ($symb,$apath,$adom,$aname) = @_;
 9555:     if ($symb ne '') {
 9556:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
 9557:         if (keys(%essays) > 0) {
 9558:             $old_essays{$symb} = \%essays;
 9559:         }
 9560:     }
 9561:     return;
 9562: }
 9563: 
 9564: sub reset_old_essays {
 9565:     undef(%old_essays);
 9566: }
 9567: 
 9568: sub gather_clicker_ids {
 9569:     my %clicker_ids;
 9570: 
 9571:     my $classlist = &Apache::loncoursedata::get_classlist();
 9572: 
 9573:     # Set up a couple variables.
 9574:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
 9575:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
 9576:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
 9577: 
 9578:     foreach my $student (keys(%$classlist)) {
 9579:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
 9580:         my $username = $classlist->{$student}->[$username_idx];
 9581:         my $domain   = $classlist->{$student}->[$domain_idx];
 9582:         my $clickers =
 9583: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
 9584:         foreach my $id (split(/\,/,$clickers)) {
 9585:             $id=~s/^[\#0]+//;
 9586:             $id=~s/[\-\:]//g;
 9587:             if (exists($clicker_ids{$id})) {
 9588: 		$clicker_ids{$id}.=','.$username.':'.$domain;
 9589:             } else {
 9590: 		$clicker_ids{$id}=$username.':'.$domain;
 9591:             }
 9592:         }
 9593:     }
 9594:     return %clicker_ids;
 9595: }
 9596: 
 9597: sub gather_adv_clicker_ids {
 9598:     my %clicker_ids;
 9599:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 9600:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9601:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
 9602:     foreach my $element (sort(keys(%coursepersonnel))) {
 9603:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
 9604:             my ($puname,$pudom)=split(/\:/,$person);
 9605:             my $clickers =
 9606: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
 9607:             foreach my $id (split(/\,/,$clickers)) {
 9608: 		$id=~s/^[\#0]+//;
 9609:                 $id=~s/[\-\:]//g;
 9610: 		if (exists($clicker_ids{$id})) {
 9611: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
 9612: 		} else {
 9613: 		    $clicker_ids{$id}=$puname.':'.$pudom;
 9614: 		}
 9615:             }
 9616:         }
 9617:     }
 9618:     return %clicker_ids;
 9619: }
 9620: 
 9621: sub clicker_grading_parameters {
 9622:     return ('gradingmechanism' => 'scalar',
 9623:             'upfiletype' => 'scalar',
 9624:             'specificid' => 'scalar',
 9625:             'pcorrect' => 'scalar',
 9626:             'pincorrect' => 'scalar');
 9627: }
 9628: 
 9629: sub process_clicker {
 9630:     my ($r,$symb)=@_;
 9631:     if (!$symb) {return '';}
 9632:     my $result=&checkforfile_js();
 9633:     $result.=&Apache::loncommon::start_data_table().
 9634:              &Apache::loncommon::start_data_table_header_row().
 9635:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
 9636:              &Apache::loncommon::end_data_table_header_row().
 9637:              &Apache::loncommon::start_data_table_row()."<td>\n";
 9638: # Attempt to restore parameters from last session, set defaults if not present
 9639:     my %Saveable_Parameters=&clicker_grading_parameters();
 9640:     &Apache::loncommon::restore_course_settings('grades_clicker',
 9641:                                                  \%Saveable_Parameters);
 9642:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
 9643:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
 9644:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
 9645:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
 9646: 
 9647:     my %checked;
 9648:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
 9649:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
 9650:           $checked{$gradingmechanism}=' checked="checked"';
 9651:        }
 9652:     }
 9653: 
 9654:     my $upload=&mt("Evaluate File");
 9655:     my $type=&mt("Type");
 9656:     my $attendance=&mt("Award points just for participation");
 9657:     my $personnel=&mt("Correctness determined from response by course personnel");
 9658:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
 9659:     my $given=&mt("Correctness determined from given list of answers").' '.
 9660:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
 9661:     my $pcorrect=&mt("Percentage points for correct solution");
 9662:     my $pincorrect=&mt("Percentage points for incorrect solution");
 9663:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
 9664: 						   {'iclicker' => 'i>clicker',
 9665:                                                     'interwrite' => 'interwrite PRS',
 9666:                                                     'turning' => 'Turning Technologies'});
 9667:     $symb = &Apache::lonenc::check_encrypt($symb);
 9668:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
 9669: function sanitycheck() {
 9670: // Accept only integer percentages
 9671:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
 9672:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
 9673: // Find out grading choice
 9674:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 9675:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
 9676:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
 9677:       }
 9678:    }
 9679: // By default, new choice equals user selection
 9680:    newgradingchoice=gradingchoice;
 9681: // Not good to give more points for false answers than correct ones
 9682:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
 9683:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
 9684:    }
 9685: // If new choice is attendance only, and old choice was correctness-based, restore defaults
 9686:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
 9687:       document.forms.gradesupload.pcorrect.value=100;
 9688:       document.forms.gradesupload.pincorrect.value=100;
 9689:    }
 9690: // If the values are different, cannot be attendance only
 9691:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
 9692:        (gradingchoice=='attendance')) {
 9693:        newgradingchoice='personnel';
 9694:    }
 9695: // Change grading choice to new one
 9696:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 9697:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
 9698:          document.forms.gradesupload.gradingmechanism[i].checked=true;
 9699:       } else {
 9700:          document.forms.gradesupload.gradingmechanism[i].checked=false;
 9701:       }
 9702:    }
 9703: // Remember the old state
 9704:    document.forms.gradesupload.waschecked.value=newgradingchoice;
 9705: }
 9706: ENDUPFORM
 9707:     $result.= <<ENDUPFORM;
 9708: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 9709: <input type="hidden" name="symb" value="$symb" />
 9710: <input type="hidden" name="command" value="processclickerfile" />
 9711: <input type="file" name="upfile" size="50" />
 9712: <br /><label>$type: $selectform</label>
 9713: ENDUPFORM
 9714:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
 9715:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
 9716:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
 9717: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
 9718: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
 9719: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
 9720: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
 9721: <br />&nbsp;&nbsp;&nbsp;
 9722: <input type="text" name="givenanswer" size="50" />
 9723: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
 9724: ENDGRADINGFORM
 9725:          $result.='</td>'.&Apache::loncommon::end_data_table_row().
 9726:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
 9727:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
 9728: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
 9729: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 9730: </form>'
 9731: ENDPERCFORM
 9732:     $result.='</td>'.
 9733:              &Apache::loncommon::end_data_table_row().
 9734:              &Apache::loncommon::end_data_table();
 9735:     return $result;
 9736: }
 9737: 
 9738: sub process_clicker_file {
 9739:     my ($r,$symb)=@_;
 9740:     if (!$symb) {return '';}
 9741: 
 9742:     my %Saveable_Parameters=&clicker_grading_parameters();
 9743:     &Apache::loncommon::store_course_settings('grades_clicker',
 9744:                                               \%Saveable_Parameters);
 9745:     my $result='';
 9746:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
 9747: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
 9748: 	return $result;
 9749:     }
 9750:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
 9751:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
 9752:         return $result;
 9753:     }
 9754:     my $foundgiven=0;
 9755:     if ($env{'form.gradingmechanism'} eq 'given') {
 9756:         $env{'form.givenanswer'}=~s/^\s*//gs;
 9757:         $env{'form.givenanswer'}=~s/\s*$//gs;
 9758:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
 9759:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
 9760:         my @answers=split(/\,/,$env{'form.givenanswer'});
 9761:         $foundgiven=$#answers+1;
 9762:     }
 9763:     my %clicker_ids=&gather_clicker_ids();
 9764:     my %correct_ids;
 9765:     if ($env{'form.gradingmechanism'} eq 'personnel') {
 9766: 	%correct_ids=&gather_adv_clicker_ids();
 9767:     }
 9768:     if ($env{'form.gradingmechanism'} eq 'specific') {
 9769: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
 9770: 	   $correct_id=~tr/a-z/A-Z/;
 9771: 	   $correct_id=~s/\s//gs;
 9772: 	   $correct_id=~s/^[\#0]+//;
 9773:            $correct_id=~s/[\-\:]//g;
 9774:            if ($correct_id) {
 9775: 	      $correct_ids{$correct_id}='specified';
 9776:            }
 9777:         }
 9778:     }
 9779:     if ($env{'form.gradingmechanism'} eq 'attendance') {
 9780: 	$result.=&mt('Score based on attendance only');
 9781:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
 9782:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
 9783:     } else {
 9784: 	my $number=0;
 9785: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
 9786: 	foreach my $id (sort(keys(%correct_ids))) {
 9787: 	    $result.='<br /><tt>'.$id.'</tt> - ';
 9788: 	    if ($correct_ids{$id} eq 'specified') {
 9789: 		$result.=&mt('specified');
 9790: 	    } else {
 9791: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
 9792: 		$result.=&Apache::loncommon::plainname($uname,$udom);
 9793: 	    }
 9794: 	    $number++;
 9795: 	}
 9796:         $result.="</p>\n";
 9797:         if ($number==0) {
 9798:             $result .=
 9799:                  &Apache::lonhtmlcommon::confirm_success(
 9800:                      &mt('No IDs found to determine correct answer'),1);
 9801:             return $result;
 9802:         }
 9803:     }
 9804:     if (length($env{'form.upfile'}) < 2) {
 9805:         $result .=
 9806:             &Apache::lonhtmlcommon::confirm_success(
 9807:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
 9808:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
 9809:         return $result;
 9810:     }
 9811: 
 9812: # Were able to get all the info needed, now analyze the file
 9813: 
 9814:     $result.=&Apache::loncommon::studentbrowser_javascript();
 9815:     $symb = &Apache::lonenc::check_encrypt($symb);
 9816:     $result.=&Apache::loncommon::start_data_table().
 9817:              &Apache::loncommon::start_data_table_header_row().
 9818:              '<th>'.&mt('Evaluate clicker file').'</th>'.
 9819:              &Apache::loncommon::end_data_table_header_row().
 9820:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
 9821: <td>
 9822: <form method="post" action="/adm/grades" name="clickeranalysis">
 9823: <input type="hidden" name="symb" value="$symb" />
 9824: <input type="hidden" name="command" value="assignclickergrades" />
 9825: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
 9826: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
 9827: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
 9828: ENDHEADER
 9829:     if ($env{'form.gradingmechanism'} eq 'given') {
 9830:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
 9831:     } 
 9832:     my %responses;
 9833:     my @questiontitles;
 9834:     my $errormsg='';
 9835:     my $number=0;
 9836:     if ($env{'form.upfiletype'} eq 'iclicker') {
 9837: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
 9838:     }
 9839:     if ($env{'form.upfiletype'} eq 'interwrite') {
 9840:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
 9841:     }
 9842:     if ($env{'form.upfiletype'} eq 'turning') {
 9843:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
 9844:     }
 9845:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
 9846:              '<input type="hidden" name="number" value="'.$number.'" />'.
 9847:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
 9848:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
 9849:              '<br />';
 9850:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
 9851:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
 9852:        return $result;
 9853:     } 
 9854: # Remember Question Titles
 9855: # FIXME: Possibly need delimiter other than ":"
 9856:     for (my $i=0;$i<$number;$i++) {
 9857:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
 9858:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
 9859:     }
 9860:     my $correct_count=0;
 9861:     my $student_count=0;
 9862:     my $unknown_count=0;
 9863: # Match answers with usernames
 9864: # FIXME: Possibly need delimiter other than ":"
 9865:     foreach my $id (keys(%responses)) {
 9866:        if ($correct_ids{$id}) {
 9867:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
 9868:           $correct_count++;
 9869:        } elsif ($clicker_ids{$id}) {
 9870:           if ($clicker_ids{$id}=~/\,/) {
 9871: # More than one user with the same clicker!
 9872:              $result.="</td>".&Apache::loncommon::end_data_table_row().
 9873:                            &Apache::loncommon::start_data_table_row()."<td>".
 9874:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
 9875:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 9876:                            "<select name='multi".$id."'>";
 9877:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
 9878:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
 9879:              }
 9880:              $result.='</select>';
 9881:              $unknown_count++;
 9882:           } else {
 9883: # Good: found one and only one user with the right clicker
 9884:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
 9885:              $student_count++;
 9886:           }
 9887:        } else {
 9888:           $result.="</td>".&Apache::loncommon::end_data_table_row().
 9889:                            &Apache::loncommon::start_data_table_row()."<td>".
 9890:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
 9891:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 9892:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
 9893:                    "\n".&mt("Domain").": ".
 9894:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
 9895:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,0,$id);
 9896:           $unknown_count++;
 9897:        }
 9898:     }
 9899:     $result.='<hr />'.
 9900:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
 9901:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
 9902:        if ($correct_count==0) {
 9903:           $errormsg.="Found no correct answers for grading!";
 9904:        } elsif ($correct_count>1) {
 9905:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
 9906:        }
 9907:     }
 9908:     if ($number<1) {
 9909:        $errormsg.="Found no questions.";
 9910:     }
 9911:     if ($errormsg) {
 9912:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
 9913:     } else {
 9914:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
 9915:     }
 9916:     $result.='</form></td>'.
 9917:              &Apache::loncommon::end_data_table_row().
 9918:              &Apache::loncommon::end_data_table();
 9919:     return $result;
 9920: }
 9921: 
 9922: sub iclicker_eval {
 9923:     my ($questiontitles,$responses)=@_;
 9924:     my $number=0;
 9925:     my $errormsg='';
 9926:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 9927:         my %components=&Apache::loncommon::record_sep($line);
 9928:         my @entries=map {$components{$_}} (sort(keys(%components)));
 9929: 	if ($entries[0] eq 'Question') {
 9930: 	    for (my $i=3;$i<$#entries;$i+=6) {
 9931: 		$$questiontitles[$number]=$entries[$i];
 9932: 		$number++;
 9933: 	    }
 9934: 	}
 9935: 	if ($entries[0]=~/^\#/) {
 9936: 	    my $id=$entries[0];
 9937: 	    my @idresponses;
 9938: 	    $id=~s/^[\#0]+//;
 9939: 	    for (my $i=0;$i<$number;$i++) {
 9940: 		my $idx=3+$i*6;
 9941:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
 9942: 		push(@idresponses,$entries[$idx]);
 9943: 	    }
 9944: 	    $$responses{$id}=join(',',@idresponses);
 9945: 	}
 9946:     }
 9947:     return ($errormsg,$number);
 9948: }
 9949: 
 9950: sub interwrite_eval {
 9951:     my ($questiontitles,$responses)=@_;
 9952:     my $number=0;
 9953:     my $errormsg='';
 9954:     my $skipline=1;
 9955:     my $questionnumber=0;
 9956:     my %idresponses=();
 9957:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 9958:         my %components=&Apache::loncommon::record_sep($line);
 9959:         my @entries=map {$components{$_}} (sort(keys(%components)));
 9960:         if ($entries[1] eq 'Time') { $skipline=0; next; }
 9961:         if ($entries[1] eq 'Response') { $skipline=1; }
 9962:         next if $skipline;
 9963:         if ($entries[0]!=$questionnumber) {
 9964:            $questionnumber=$entries[0];
 9965:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
 9966:            $number++;
 9967:         }
 9968:         my $id=$entries[4];
 9969:         $id=~s/^[\#0]+//;
 9970:         $id=~s/^v\d*\://i;
 9971:         $id=~s/[\-\:]//g;
 9972:         $idresponses{$id}[$number]=$entries[6];
 9973:     }
 9974:     foreach my $id (keys(%idresponses)) {
 9975:        $$responses{$id}=join(',',@{$idresponses{$id}});
 9976:        $$responses{$id}=~s/^\s*\,//;
 9977:     }
 9978:     return ($errormsg,$number);
 9979: }
 9980: 
 9981: sub turning_eval {
 9982:     my ($questiontitles,$responses)=@_;
 9983:     my $number=0;
 9984:     my $errormsg='';
 9985:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 9986:         my %components=&Apache::loncommon::record_sep($line);
 9987:         my @entries=map {$components{$_}} (sort(keys(%components)));
 9988:         if ($#entries>$number) { $number=$#entries; }
 9989:         my $id=$entries[0];
 9990:         my @idresponses;
 9991:         $id=~s/^[\#0]+//;
 9992:         unless ($id) { next; }
 9993:         for (my $idx=1;$idx<=$#entries;$idx++) {
 9994:             $entries[$idx]=~s/\,/\;/g;
 9995:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
 9996:             push(@idresponses,$entries[$idx]);
 9997:         }
 9998:         $$responses{$id}=join(',',@idresponses);
 9999:     }
10000:     for (my $i=1; $i<=$number; $i++) {
10001:         $$questiontitles[$i]=&mt('Question [_1]',$i);
10002:     }
10003:     return ($errormsg,$number);
10004: }
10005: 
10006: 
10007: sub assign_clicker_grades {
10008:     my ($r,$symb)=@_;
10009:     if (!$symb) {return '';}
10010: # See which part we are saving to
10011:     my $res_error;
10012:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
10013:     if ($res_error) {
10014:         return &navmap_errormsg();
10015:     }
10016: # FIXME: This should probably look for the first handgradeable part
10017:     my $part=$$partlist[0];
10018: # Start screen output
10019:     my $result=&Apache::loncommon::start_data_table().
10020:              &Apache::loncommon::start_data_table_header_row().
10021:              '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
10022:              &Apache::loncommon::end_data_table_header_row().
10023:              &Apache::loncommon::start_data_table_row().'<td>';
10024: # Get correct result
10025: # FIXME: Possibly need delimiter other than ":"
10026:     my @correct=();
10027:     my $gradingmechanism=$env{'form.gradingmechanism'};
10028:     my $number=$env{'form.number'};
10029:     if ($gradingmechanism ne 'attendance') {
10030:        foreach my $key (keys(%env)) {
10031:           if ($key=~/^form\.correct\:/) {
10032:              my @input=split(/\,/,$env{$key});
10033:              for (my $i=0;$i<=$#input;$i++) {
10034:                  if (($correct[$i]) && ($input[$i]) &&
10035:                      ($correct[$i] ne $input[$i])) {
10036:                     $result.='<br /><span class="LC_warning">'.
10037:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
10038:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
10039:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
10040:                     $correct[$i]=$input[$i];
10041:                  }
10042:              }
10043:           }
10044:        }
10045:        for (my $i=0;$i<$number;$i++) {
10046:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
10047:              $result.='<br /><span class="LC_error">'.
10048:                       &mt('No correct result given for question "[_1]"!',
10049:                           $env{'form.question:'.$i}).'</span>';
10050:           }
10051:        }
10052:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
10053:     }
10054: # Start grading
10055:     my $pcorrect=$env{'form.pcorrect'};
10056:     my $pincorrect=$env{'form.pincorrect'};
10057:     my $storecount=0;
10058:     my %users=();
10059:     foreach my $key (keys(%env)) {
10060:        my $user='';
10061:        if ($key=~/^form\.student\:(.*)$/) {
10062:           $user=$1;
10063:        }
10064:        if ($key=~/^form\.unknown\:(.*)$/) {
10065:           my $id=$1;
10066:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
10067:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
10068:           } elsif ($env{'form.multi'.$id}) {
10069:              $user=$env{'form.multi'.$id};
10070:           }
10071:        }
10072:        if ($user) {
10073:           if ($users{$user}) {
10074:              $result.='<br /><span class="LC_warning">'.
10075:                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
10076:                       '</span><br />';
10077:           }
10078:           $users{$user}=1; 
10079:           my @answer=split(/\,/,$env{$key});
10080:           my $sum=0;
10081:           my $realnumber=$number;
10082:           for (my $i=0;$i<$number;$i++) {
10083:              if  ($correct[$i] eq '-') {
10084:                 $realnumber--;
10085:              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/))  {
10086:                 if ($gradingmechanism eq 'attendance') {
10087:                    $sum+=$pcorrect;
10088:                 } elsif ($correct[$i] eq '*') {
10089:                    $sum+=$pcorrect;
10090:                 } else {
10091: # We actually grade if correct or not
10092:                    my $increment=$pincorrect;
10093: # Special case: numerical answer "0"
10094:                    if ($correct[$i] eq '0') {
10095:                       if ($answer[$i]=~/^[0\.]+$/) {
10096:                          $increment=$pcorrect;
10097:                       }
10098: # General numerical answer, both evaluate to something non-zero
10099:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
10100:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
10101:                          $increment=$pcorrect;
10102:                       }
10103: # Must be just alphanumeric
10104:                    } elsif ($answer[$i] eq $correct[$i]) {
10105:                       $increment=$pcorrect;
10106:                    }
10107:                    $sum+=$increment;
10108:                 }
10109:              }
10110:           }
10111:           my $ave=$sum/(100*$realnumber);
10112: # Store
10113:           my ($username,$domain)=split(/\:/,$user);
10114:           my %grades=();
10115:           $grades{"resource.$part.solved"}='correct_by_override';
10116:           $grades{"resource.$part.awarded"}=$ave;
10117:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
10118:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
10119:                                                  $env{'request.course.id'},
10120:                                                  $domain,$username);
10121:           if ($returncode ne 'ok') {
10122:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
10123:           } else {
10124:              $storecount++;
10125:           }
10126:        }
10127:     }
10128: # We are done
10129:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
10130:              '</td>'.
10131:              &Apache::loncommon::end_data_table_row().
10132:              &Apache::loncommon::end_data_table();
10133:     return $result;
10134: }
10135: 
10136: sub navmap_errormsg {
10137:     return '<div class="LC_error">'.
10138:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
10139:            &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>').
10140:            '</div>';
10141: }
10142: 
10143: sub startpage {
10144:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$js) = @_;
10145:     if ($nomenu) {
10146:         $r->print(&Apache::loncommon::start_page("Student's Version",$js,{'only_body' => '1'}));
10147:     } else {
10148:         unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
10149:         $r->print(&Apache::loncommon::start_page('Grading',$js,
10150:                                                  {'bread_crumbs' => $crumbs}));
10151:         &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
10152:     }
10153:     unless ($nodisplayflag) {
10154:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp));
10155:     }
10156: }
10157: 
10158: sub select_problem {
10159:     my ($r)=@_;
10160:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
10161:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1));
10162:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
10163:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
10164: }
10165: 
10166: sub handler {
10167:     my $request=$_[0];
10168:     &reset_caches();
10169:     if ($request->header_only) {
10170:         &Apache::loncommon::content_type($request,'text/html');
10171:         $request->send_http_header;
10172:         return OK;
10173:     }
10174:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
10175: 
10176: # see what command we need to execute
10177: 
10178:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
10179:     my $command=$commands[0];
10180: 
10181:     &init_perm();
10182:     if (!$env{'request.course.id'}) {
10183:         unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
10184:                 ($command =~ /^scantronupload/)) {
10185:             # Not in a course.
10186:             $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
10187:             return HTTP_NOT_ACCEPTABLE;
10188:         }
10189:     } elsif (!%perm) {
10190:         $request->internal_redirect('/adm/quickgrades');
10191:         return OK;
10192:     }
10193:     &Apache::loncommon::content_type($request,'text/html');
10194:     $request->send_http_header;
10195: 
10196:     if ($#commands > 0) {
10197: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
10198:     }
10199: 
10200: # see what the symb is
10201: 
10202:     my $symb=$env{'form.symb'};
10203:     unless ($symb) {
10204:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
10205:        $symb=&Apache::lonnet::symbread($url);
10206:     }
10207:     &Apache::lonenc::check_decrypt(\$symb);
10208: 
10209:     $ssi_error = 0;
10210:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
10211: #
10212: # Not called from a resource, but inside a course
10213: #    
10214:         &startpage($request,undef,[],1,1);
10215:         &select_problem($request);
10216:     } else {
10217: 	if ($command eq 'submission' && $perm{'vgr'}) {
10218:             my ($stuvcurrent,$stuvdisp,$versionform,$js);
10219:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
10220:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
10221:                     &choose_task_version_form($symb,$env{'form.student'},
10222:                                               $env{'form.userdom'});
10223:             }
10224:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,$stuvcurrent,$stuvdisp,undef,$js);
10225:             if ($versionform) {
10226:                 $request->print($versionform);
10227:             }
10228:             $request->print('<br clear="all" />');
10229: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
10230:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
10231:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
10232:                 &choose_task_version_form($symb,$env{'form.student'},
10233:                                           $env{'form.userdom'},
10234:                                           $env{'form.inhibitmenu'});
10235:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,$stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$js);
10236:             if ($versionform) {
10237:                 $request->print($versionform);
10238:             }
10239:             $request->print('<br clear="all" />');
10240:             $request->print(&show_previous_task_version($request,$symb));
10241: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
10242:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
10243:                                        {href=>'',text=>'Select student'}],1,1);
10244: 	    &pickStudentPage($request,$symb);
10245: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
10246:             &startpage($request,$symb,
10247:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
10248:                                        {href=>'',text=>'Select student'},
10249:                                        {href=>'',text=>'Grade student'}],1,1);
10250: 	    &displayPage($request,$symb);
10251: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
10252:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
10253:                                        {href=>'',text=>'Select student'},
10254:                                        {href=>'',text=>'Grade student'},
10255:                                        {href=>'',text=>'Store grades'}],1,1);
10256: 	    &updateGradeByPage($request,$symb);
10257: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
10258:             &startpage($request,$symb,[{href=>'',text=>'...'},
10259:                                        {href=>'',text=>'Modify grades'}]);
10260: 	    &processGroup($request,$symb);
10261: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
10262:             &startpage($request,$symb);
10263: 	    $request->print(&grading_menu($request,$symb));
10264: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
10265:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
10266: 	    $request->print(&submit_options($request,$symb));
10267:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
10268:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}]);
10269:             $request->print(&listStudents($request,$symb,'graded'));
10270:         } elsif ($command eq 'table' && $perm{'vgr'}) {
10271:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
10272:             $request->print(&submit_options_table($request,$symb));
10273:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
10274:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
10275:             $request->print(&submit_options_sequence($request,$symb));
10276: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
10277:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
10278: 	    $request->print(&viewgrades($request,$symb));
10279: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
10280:             &startpage($request,$symb,[{href=>'',text=>'...'},
10281:                                        {href=>'',text=>'Store grades'}]);
10282: 	    $request->print(&processHandGrade($request,$symb));
10283: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
10284:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
10285:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
10286:                                                                              text=>"Modify grades"},
10287:                                        {href=>'', text=>"Store grades"}]);
10288: 	    $request->print(&editgrades($request,$symb));
10289:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
10290:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
10291:             $request->print(&initialverifyreceipt($request,$symb));
10292: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
10293:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
10294:                                        {href=>'',text=>'Verification Result'}]);
10295: 	    $request->print(&verifyreceipt($request,$symb));
10296:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
10297:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
10298:             $request->print(&process_clicker($request,$symb));
10299:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
10300:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
10301:                                        {href=>'', text=>'Process clicker file'}]);
10302:             $request->print(&process_clicker_file($request,$symb));
10303:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
10304:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
10305:                                        {href=>'', text=>'Process clicker file'},
10306:                                        {href=>'', text=>'Store grades'}]);
10307:             $request->print(&assign_clicker_grades($request,$symb));
10308: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
10309:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10310: 	    $request->print(&upcsvScores_form($request,$symb));
10311: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
10312:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10313: 	    $request->print(&csvupload($request,$symb));
10314: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
10315:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10316: 	    $request->print(&csvuploadmap($request,$symb));
10317: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
10318: 	    if ($env{'form.associate'} ne 'Reverse Association') {
10319:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10320: 		$request->print(&csvuploadoptions($request,$symb));
10321: 	    } else {
10322: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
10323: 		    $env{'form.upfile_associate'} = 'reverse';
10324: 		} else {
10325: 		    $env{'form.upfile_associate'} = 'forward';
10326: 		}
10327:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10328: 		$request->print(&csvuploadmap($request,$symb));
10329: 	    }
10330: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
10331:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10332: 	    $request->print(&csvuploadassign($request,$symb));
10333: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
10334:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10335: 	    $request->print(&scantron_selectphase($request,undef,$symb));
10336:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
10337:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10338:  	    $request->print(&scantron_do_warning($request,$symb));
10339: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
10340:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10341: 	    $request->print(&scantron_validate_file($request,$symb));
10342: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
10343:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10344: 	    $request->print(&scantron_process_students($request,$symb));
10345:  	} elsif ($command eq 'scantronupload' && 
10346:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
10347: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
10348:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10349:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
10350:  	} elsif ($command eq 'scantronupload_save' &&
10351:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
10352: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
10353:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10354:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
10355:  	} elsif ($command eq 'scantron_download' &&
10356: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
10357:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10358:  	    $request->print(&scantron_download_scantron_data($request,$symb));
10359:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
10360:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10361:             $request->print(&checkscantron_results($request,$symb));
10362:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
10363:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}]);
10364:             $request->print(&submit_options_download($request,$symb));
10365:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
10366:             &startpage($request,$symb,
10367:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
10368:     {href=>'', text=>'Download submissions'}]);
10369:             &submit_download_link($request,$symb);
10370: 	} elsif ($command) {
10371:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
10372: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
10373: 	}
10374:     }
10375:     if ($ssi_error) {
10376: 	&ssi_print_error($request);
10377:     }
10378:     if ($env{'form.inhibitmenu'}) {
10379:         $request->print(&Apache::loncommon::end_page());
10380:     } else {
10381:         &Apache::lonquickgrades::endGradeScreen($request);
10382:     }
10383:     &reset_caches();
10384:     return OK;
10385: }
10386: 
10387: 1;
10388: 
10389: __END__;
10390: 
10391: 
10392: =head1 NAME
10393: 
10394: Apache::grades
10395: 
10396: =head1 SYNOPSIS
10397: 
10398: Handles the viewing of grades.
10399: 
10400: This is part of the LearningOnline Network with CAPA project
10401: described at http://www.lon-capa.org.
10402: 
10403: =head1 OVERVIEW
10404: 
10405: Do an ssi with retries:
10406: While I'd love to factor out this with the version in lonprintout,
10407: 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
10408: I'm not quite ready to invent (e.g. an ssi_with_retry object).
10409: 
10410: At least the logic that drives this has been pulled out into loncommon.
10411: 
10412: 
10413: 
10414: ssi_with_retries - Does the server side include of a resource.
10415:                      if the ssi call returns an error we'll retry it up to
10416:                      the number of times requested by the caller.
10417:                      If we still have a problem, no text is appended to the
10418:                      output and we set some global variables.
10419:                      to indicate to the caller an SSI error occurred.  
10420:                      All of this is supposed to deal with the issues described
10421:                      in LON-CAPA BZ 5631 see:
10422:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
10423:                      by informing the user that this happened.
10424: 
10425: Parameters:
10426:   resource   - The resource to include.  This is passed directly, without
10427:                interpretation to lonnet::ssi.
10428:   form       - The form hash parameters that guide the interpretation of the resource
10429:                
10430:   retries    - Number of retries allowed before giving up completely.
10431: Returns:
10432:   On success, returns the rendered resource identified by the resource parameter.
10433: Side Effects:
10434:   The following global variables can be set:
10435:    ssi_error                - If an unrecoverable error occurred this becomes true.
10436:                               It is up to the caller to initialize this to false
10437:                               if desired.
10438:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
10439:                               of the resource that could not be rendered by the ssi
10440:                               call.
10441:    ssi_error_message   - The error string fetched from the ssi response
10442:                               in the event of an error.
10443: 
10444: 
10445: =head1 HANDLER SUBROUTINE
10446: 
10447: ssi_with_retries()
10448: 
10449: =head1 SUBROUTINES
10450: 
10451: =over
10452: 
10453: =head1 Routines to display previous version of a Task for a specific student
10454: 
10455: Tasks are graded pass/fail. Students who have yet to pass a particular Task
10456: can receive another opportunity. Access to tasks is slot-based. If a slot
10457: requires a proctor to check-in the student, a new version of the Task will
10458: be created when the student is checked in to the new opportunity.
10459: 
10460: If a particular student has tried two or more versions of a particular task,
10461: the submission screen provides a user with vgr privileges (e.g., a Course
10462: Coordinator) the ability to display a previous version worked on by the
10463: student.  By default, the current version is displayed. If a previous version
10464: has been selected for display, submission data are only shown that pertain
10465: to that particular version, and the interface to submit grades is not shown.
10466: 
10467: =over 4
10468: 
10469: =item show_previous_task_version()
10470: 
10471: Displays a specified version of a student's Task, as the student sees it.
10472: 
10473: Inputs: 2
10474:         request - request object
10475:         symb    - unique symb for current instance of resource
10476: 
10477: Output: None.
10478: 
10479: Side Effects: calls &show_problem() to print version of Task, with
10480:               version contained in form item: $env{'form.previousversion'}
10481: 
10482: =item choose_task_version_form()
10483: 
10484: Displays a web form used to select which version of a student's view of a
10485: Task should be displayed.  Either launches a pop-up window, or replaces
10486: content in existing pop-up, or replaces page in main window.
10487: 
10488: Inputs: 4
10489:         symb    - unique symb for current instance of resource
10490:         uname   - username of student
10491:         udom    - domain of student
10492:         nomenu  - 1 if display is in a pop-up window, and hence no menu
10493:                   breadcrumbs etc., are displayed
10494: 
10495: Output: 4
10496:         current   - student's current version
10497:         displayed - student's version being displayed
10498:         result    - scalar containing HTML for web form used to switch to
10499:                     a different version (or a link to close window, if pop-up).
10500:         js        - javascript for processing selection in versions web form
10501: 
10502: Side Effects: None.
10503: 
10504: =item previous_display_javascript()
10505: 
10506: Inputs: 2
10507:         nomenu  - 1 if display is in a pop-up window, and hence no menu
10508:                   breadcrumbs etc., are displayed.
10509:         current - student's current version number.
10510: 
10511: Output: 1
10512:         js      - javascript for processing selection in versions web form.
10513: 
10514: Side Effects: None.
10515: 
10516: =back
10517: 
10518: =head1 Routines to process bubblesheet data.
10519: 
10520: =over 4
10521: 
10522: =item scantron_get_correction() : 
10523: 
10524:    Builds the interface screen to interact with the operator to fix a
10525:    specific error condition in a specific scanline
10526: 
10527:  Arguments:
10528:     $r           - Apache request object
10529:     $i           - number of the current scanline
10530:     $scan_record - hash ref as returned from &scantron_parse_scanline()
10531:     $scan_config - hash ref as returned from &get_scantron_config()
10532:     $line        - full contents of the current scanline
10533:     $error       - error condition, valid values are
10534:                    'incorrectCODE', 'duplicateCODE',
10535:                    'doublebubble', 'missingbubble',
10536:                    'duplicateID', 'incorrectID'
10537:     $arg         - extra information needed
10538:        For errors:
10539:          - duplicateID   - paper number that this studentID was seen before on
10540:          - duplicateCODE - array ref of the paper numbers this CODE was
10541:                            seen on before
10542:          - incorrectCODE - current incorrect CODE 
10543:          - doublebubble  - array ref of the bubble lines that have double
10544:                            bubble errors
10545:          - missingbubble - array ref of the bubble lines that have missing
10546:                            bubble errors
10547: 
10548:    $randomorder - True if exam folder has randomorder set
10549:    $randompick  - True if exam folder has randompick set
10550:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
10551:                      for current line to question number used for same question
10552:                      in "Master Seqence" (as seen by Course Coordinator).
10553:    $startline   - Reference to hash where key is question number (0 is first)
10554:                   and value is number of first bubble line for current student
10555:                   or code-based randompick and/or randomorder.
10556: 
10557: 
10558: 
10559: =item  scantron_get_maxbubble() : 
10560: 
10561:    Arguments:
10562:        $nav_error  - Reference to scalar which is a flag to indicate a
10563:                       failure to retrieve a navmap object.
10564:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
10565:        calling routine should trap the error condition and display the warning
10566:        found in &navmap_errormsg().
10567: 
10568:        $scantron_config - Reference to bubblesheet format configuration hash.
10569: 
10570:    Returns the maximum number of bubble lines that are expected to
10571:    occur. Does this by walking the selected sequence rendering the
10572:    resource and then checking &Apache::lonxml::get_problem_counter()
10573:    for what the current value of the problem counter is.
10574: 
10575:    Caches the results to $env{'form.scantron_maxbubble'},
10576:    $env{'form.scantron.bubble_lines.n'}, 
10577:    $env{'form.scantron.first_bubble_line.n'} and
10578:    $env{"form.scantron.sub_bubblelines.n"}
10579:    which are the total number of bubble lines, the number of bubble
10580:    lines for response n and number of the first bubble line for response n,
10581:    and a comma separated list of numbers of bubble lines for sub-questions
10582:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
10583: 
10584: 
10585: =item  scantron_validate_missingbubbles() : 
10586: 
10587:    Validates all scanlines in the selected file to not have any
10588:     answers that don't have bubbles that have not been verified
10589:     to be bubble free.
10590: 
10591: =item  scantron_process_students() : 
10592: 
10593:    Routine that does the actual grading of the bubblesheet information.
10594: 
10595:    The parsed scanline hash is added to %env 
10596: 
10597:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
10598:    foreach resource , with the form data of
10599: 
10600: 	'submitted'     =>'scantron' 
10601: 	'grade_target'  =>'grade',
10602: 	'grade_username'=> username of student
10603: 	'grade_domain'  => domain of student
10604: 	'grade_courseid'=> of course
10605: 	'grade_symb'    => symb of resource to grade
10606: 
10607:     This triggers a grading pass. The problem grading code takes care
10608:     of converting the bubbled letter information (now in %env) into a
10609:     valid submission.
10610: 
10611: =item  scantron_upload_scantron_data() :
10612: 
10613:     Creates the screen for adding a new bubblesheet data file to a course.
10614: 
10615: =item  scantron_upload_scantron_data_save() : 
10616: 
10617:    Adds a provided bubble information data file to the course if user
10618:    has the correct privileges to do so. 
10619: 
10620: =item  valid_file() :
10621: 
10622:    Validates that the requested bubble data file exists in the course.
10623: 
10624: =item  scantron_download_scantron_data() : 
10625: 
10626:    Shows a list of the three internal files (original, corrected,
10627:    skipped) for a specific bubblesheet data file that exists in the
10628:    course.
10629: 
10630: =item  scantron_validate_ID() : 
10631: 
10632:    Validates all scanlines in the selected file to not have any
10633:    invalid or underspecified student/employee IDs
10634: 
10635: =item navmap_errormsg() :
10636: 
10637:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
10638:    Should be called whenever the request to instantiate a navmap object fails.
10639: 
10640: =back
10641: 
10642: =back
10643: 
10644: =cut

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