File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.737: download - view: text, annotated - select for diffs
Sun Jan 31 21:25:42 2016 UTC (8 years, 3 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Score upload form supports identification of a user based on clicker ID,
  for Course Coordinators who prefer not to use LON-CAPA's in-built
  "Process Clicker" utility.
- clickers.db file on a library server contains key = value pairs, where key
  is (escaped) clicker ID, and value is (escaped) comma-separated list of
  usernames who registered that particular clicker ID.
- bi-nightly run of searchcat.pl will update clickers.db file.

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.737 2016/01/31 21:25:42 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: 
   30: 
   31: package Apache::grades;
   32: use strict;
   33: use Apache::style;
   34: use Apache::lonxml;
   35: use Apache::lonnet;
   36: use Apache::loncommon;
   37: use Apache::lonhtmlcommon;
   38: use Apache::lonnavmaps;
   39: use Apache::lonhomework;
   40: use Apache::lonpickcode;
   41: use Apache::loncoursedata;
   42: use Apache::lonmsg();
   43: use Apache::Constants qw(:common :http);
   44: use Apache::lonlocal;
   45: use Apache::lonenc;
   46: use Apache::lonstathelpers;
   47: use Apache::lonquickgrades;
   48: use Apache::bridgetask();
   49: use String::Similarity;
   50: use LONCAPA;
   51: 
   52: use POSIX qw(floor);
   53: 
   54: 
   55: 
   56: my %perm=();
   57: my %old_essays=();
   58: 
   59: #  These variables are used to recover from ssi errors
   60: 
   61: my $ssi_retries = 5;
   62: my $ssi_error;
   63: my $ssi_error_resource;
   64: my $ssi_error_message;
   65: 
   66: 
   67: sub ssi_with_retries {
   68:     my ($resource, $retries, %form) = @_;
   69:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
   70:     if ($response->is_error) {
   71: 	$ssi_error          = 1;
   72: 	$ssi_error_resource = $resource;
   73: 	$ssi_error_message  = $response->code . " " . $response->message;
   74:     }
   75: 
   76:     return $content;
   77: 
   78: }
   79: #
   80: #  Prodcuces an ssi retry failure error message to the user:
   81: #
   82: 
   83: sub ssi_print_error {
   84:     my ($r) = @_;
   85:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
   86:     $r->print('
   87: <br />
   88: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
   89: <p>
   90: '.&mt('Unable to retrieve a resource from a server:').'<br />
   91: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
   92: '.&mt('Error:').' '.$ssi_error_message.'
   93: </p>
   94: <p>'.
   95: &mt('It is recommended that you try again later, as this error may mean the server was just temporarily unavailable, or is down for maintenance.').'<br />'.
   96: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
   97: '</p>');
   98:     return;
   99: }
  100: 
  101: #
  102: # --- Retrieve the parts from the metadata file.---
  103: # Returns an array of everything that the resources stores away
  104: #
  105: 
  106: sub getpartlist {
  107:     my ($symb,$errorref) = @_;
  108: 
  109:     my $navmap   = Apache::lonnavmaps::navmap->new();
  110:     unless (ref($navmap)) {
  111:         if (ref($errorref)) { 
  112:             $$errorref = 'navmap';
  113:             return;
  114:         }
  115:     }
  116:     my $res      = $navmap->getBySymb($symb);
  117:     my $partlist = $res->parts();
  118:     my $url      = $res->src();
  119:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
  120: 
  121:     my @stores;
  122:     foreach my $part (@{ $partlist }) {
  123: 	foreach my $key (@metakeys) {
  124: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
  125: 	}
  126:     }
  127:     return @stores;
  128: }
  129: 
  130: #--- Format fullname, username:domain if different for display
  131: #--- Use anywhere where the student names are listed
  132: sub nameUserString {
  133:     my ($type,$fullname,$uname,$udom) = @_;
  134:     if ($type eq 'header') {
  135: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
  136:     } else {
  137: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
  138: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
  139:     }
  140: }
  141: 
  142: #--- Get the partlist and the response type for a given problem. ---
  143: #--- Indicate if a response type is coded handgraded or not. ---
  144: #--- Sets response_error pointer to "1" if navmaps object broken ---
  145: sub response_type {
  146:     my ($symb,$response_error) = @_;
  147: 
  148:     my $navmap = Apache::lonnavmaps::navmap->new();
  149:     unless (ref($navmap)) {
  150:         if (ref($response_error)) {
  151:             $$response_error = 1;
  152:         }
  153:         return;
  154:     }
  155:     my $res = $navmap->getBySymb($symb);
  156:     unless (ref($res)) {
  157:         $$response_error = 1;
  158:         return;
  159:     }
  160:     my $partlist = $res->parts();
  161:     my %vPart = 
  162: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
  163:     my (%response_types,%handgrade);
  164:     foreach my $part (@{ $partlist }) {
  165: 	next if (%vPart && !exists($vPart{$part}));
  166: 
  167: 	my @types = $res->responseType($part);
  168: 	my @ids = $res->responseIds($part);
  169: 	for (my $i=0; $i < scalar(@ids); $i++) {
  170: 	    $response_types{$part}{$ids[$i]} = $types[$i];
  171: 	    $handgrade{$part.'_'.$ids[$i]} = 
  172: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
  173: 				     '.handgrade',$symb);
  174: 	}
  175:     }
  176:     return ($partlist,\%handgrade,\%response_types);
  177: }
  178: 
  179: sub flatten_responseType {
  180:     my ($responseType) = @_;
  181:     my @part_response_id =
  182: 	map { 
  183: 	    my $part = $_;
  184: 	    map {
  185: 		[$part,$_]
  186: 		} sort(keys(%{ $responseType->{$part} }));
  187: 	} sort(keys(%$responseType));
  188:     return @part_response_id;
  189: }
  190: 
  191: sub get_display_part {
  192:     my ($partID,$symb)=@_;
  193:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
  194:     if (defined($display) and $display ne '') {
  195:         $display.= ' (<span class="LC_internal_info">'
  196:                   .&mt('Part ID: [_1]',$partID).'</span>)';
  197:     } else {
  198: 	$display=$partID;
  199:     }
  200:     return $display;
  201: }
  202: 
  203: sub reset_caches {
  204:     &reset_analyze_cache();
  205:     &reset_perm();
  206:     &reset_old_essays();
  207: }
  208: 
  209: {
  210:     my %analyze_cache;
  211:     my %analyze_cache_formkeys;
  212: 
  213:     sub reset_analyze_cache {
  214: 	undef(%analyze_cache);
  215:         undef(%analyze_cache_formkeys);
  216:     }
  217: 
  218:     sub get_analyze {
  219: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash,$type,$trial,$rndseed,$bubbles_per_row)=@_;
  220: 	my $key = "$symb\0$uname\0$udom";
  221:         if ($type eq 'randomizetry') {
  222:             if ($trial ne '') {
  223:                 $key .= "\0".$trial;
  224:             }
  225:         }
  226: 	if (exists($analyze_cache{$key})) {
  227:             my $getupdate = 0;
  228:             if (ref($add_to_hash) eq 'HASH') {
  229:                 foreach my $item (keys(%{$add_to_hash})) {
  230:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
  231:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
  232:                             $getupdate = 1;
  233:                             last;
  234:                         }
  235:                     } else {
  236:                         $getupdate = 1;
  237:                     }
  238:                 }
  239:             }
  240:             if (!$getupdate) {
  241:                 return $analyze_cache{$key};
  242:             }
  243:         }
  244: 
  245: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
  246: 	$url=&Apache::lonnet::clutter($url);
  247:         my %form = ('grade_target'      => 'analyze',
  248:                     'grade_domain'      => $udom,
  249:                     'grade_symb'        => $symb,
  250:                     'grade_courseid'    =>  $env{'request.course.id'},
  251:                     'grade_username'    => $uname,
  252:                     'grade_noincrement' => $no_increment);
  253:         if ($bubbles_per_row ne '') {
  254:             $form{'bubbles_per_row'} = $bubbles_per_row;
  255:         }
  256:         if ($type eq 'randomizetry') {
  257:             $form{'grade_questiontype'} = $type;
  258:             if ($rndseed ne '') {
  259:                 $form{'grade_rndseed'} = $rndseed;
  260:             }
  261:         }
  262:         if (ref($add_to_hash)) {
  263:             %form = (%form,%{$add_to_hash});
  264:         }
  265: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
  266: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
  267: 	my %analyze=&Apache::lonnet::str2hash($subresult);
  268:         if (ref($add_to_hash) eq 'HASH') {
  269:             $analyze_cache_formkeys{$key} = $add_to_hash;
  270:         } else {
  271:             $analyze_cache_formkeys{$key} = {};
  272:         }
  273: 	return $analyze_cache{$key} = \%analyze;
  274:     }
  275: 
  276:     sub get_order {
  277: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment,$type,$trial,$rndseed)=@_;
  278: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment,undef,$type,$trial,$rndseed);
  279: 	return $analyze->{"$partid.$respid.shown"};
  280:     }
  281: 
  282:     sub get_radiobutton_correct_foil {
  283: 	my ($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed)=@_;
  284: 	my $analyze = &get_analyze($symb,$uname,$udom,undef,undef,$type,$trial,$rndseed);
  285:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom,undef,$type,$trial,$rndseed);
  286:         if (ref($foils) eq 'ARRAY') {
  287: 	    foreach my $foil (@{$foils}) {
  288: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
  289: 		    return $foil;
  290: 	        }
  291: 	    }
  292: 	}
  293:     }
  294: 
  295:     sub scantron_partids_tograde {
  296:         my ($resource,$cid,$uname,$udom,$check_for_randomlist,$bubbles_per_row) = @_;
  297:         my (%analysis,@parts);
  298:         if (ref($resource)) {
  299:             my $symb = $resource->symb();
  300:             my $add_to_form;
  301:             if ($check_for_randomlist) {
  302:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
  303:             }
  304:             my $analyze = 
  305:                 &get_analyze($symb,$uname,$udom,undef,$add_to_form,
  306:                              undef,undef,undef,$bubbles_per_row);
  307:             if (ref($analyze) eq 'HASH') {
  308:                 %analysis = %{$analyze};
  309:             }
  310:             if (ref($analysis{'parts'}) eq 'ARRAY') {
  311:                 foreach my $part (@{$analysis{'parts'}}) {
  312:                     my ($id,$respid) = split(/\./,$part);
  313:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
  314:                         push(@parts,$part);
  315:                     }
  316:                 }
  317:             }
  318:         }
  319:         return (\%analysis,\@parts);
  320:     }
  321: 
  322: }
  323: 
  324: #--- Clean response type for display
  325: #--- Currently filters option/rank/radiobutton/match/essay/Task
  326: #        response types only.
  327: sub cleanRecord {
  328:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
  329: 	$uname,$udom,$type,$trial,$rndseed) = @_;
  330:     my $grayFont = '<span class="LC_internal_info">';
  331:     if ($response =~ /^(option|rank)$/) {
  332: 	my %answer=&Apache::lonnet::str2hash($answer);
  333:         my @answer = %answer;
  334:         %answer = map {&HTML::Entities::encode($_, '"<>&')}  @answer;
  335: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  336: 	my ($toprow,$bottomrow);
  337: 	foreach my $foil (@$order) {
  338: 	    if ($grading{$foil} == 1) {
  339: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
  340: 	    } else {
  341: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
  342: 	    }
  343: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  344: 	}
  345: 	return '<blockquote><table border="1">'.
  346: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  347: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  348: 	    $bottomrow.'</tr></table></blockquote>';
  349:     } elsif ($response eq 'match') {
  350: 	my %answer=&Apache::lonnet::str2hash($answer);
  351:         my @answer = %answer;
  352:         %answer = map {&HTML::Entities::encode($_, '"<>&')}  @answer;
  353: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  354: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
  355: 	my ($toprow,$middlerow,$bottomrow);
  356: 	foreach my $foil (@$order) {
  357: 	    my $item=shift(@items);
  358: 	    if ($grading{$foil} == 1) {
  359: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
  360: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
  361: 	    } else {
  362: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
  363: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
  364: 	    }
  365: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  366: 	}
  367: 	return '<blockquote><table border="1">'.
  368: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  369: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
  370: 	    $middlerow.'</tr>'.
  371: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  372: 	    $bottomrow.'</tr></table></blockquote>';
  373:     } elsif ($response eq 'radiobutton') {
  374: 	my %answer=&Apache::lonnet::str2hash($answer);
  375:         my @answer = %answer;
  376:         %answer = map {&HTML::Entities::encode($_, '"<>&')}  @answer;
  377: 	my ($toprow,$bottomrow);
  378: 	my $correct = 
  379: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
  380: 	foreach my $foil (@$order) {
  381: 	    if (exists($answer{$foil})) {
  382: 		if ($foil eq $correct) {
  383: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
  384: 		} else {
  385: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
  386: 		}
  387: 	    } else {
  388: 		$toprow.='<td>'.&mt('false').'</td>';
  389: 	    }
  390: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  391: 	}
  392: 	return '<blockquote><table border="1">'.
  393: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  394: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  395: 	    $bottomrow.'</tr></table></blockquote>';
  396:     } elsif ($response eq 'essay') {
  397: 	if (! exists ($env{'form.'.$symb})) {
  398: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
  399: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
  400: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
  401: 
  402: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
  403: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
  404: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
  405: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
  406: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
  407: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
  408: 	}
  409: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
  410: 
  411:     } elsif ( $response eq 'organic') {
  412:         my $result=&mt('Smile representation: [_1]',
  413:                            '"<tt>'.&HTML::Entities::encode($answer, '"<>&').'</tt>"');
  414: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
  415: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
  416: 	return $result;
  417:     } elsif ( $response eq 'Task') {
  418: 	if ( $answer eq 'SUBMITTED') {
  419: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
  420: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
  421: 	    return $result;
  422: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
  423: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
  424: 			       keys(%{$record}));
  425: 	    return join('<br />',($version,@matches));
  426: 			       
  427: 			       
  428: 	} else {
  429: 	    my $result =
  430: 		'<p>'
  431: 		.&mt('Overall result: [_1]',
  432: 		     $record->{$version."resource.$respid.$partid.status"})
  433: 		.'</p>';
  434: 	    
  435: 	    $result .= '<ul>';
  436: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
  437: 			     keys(%{$record}));
  438: 	    foreach my $grade (sort(@grade)) {
  439: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
  440: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
  441: 				     $dim, $record->{$grade}).
  442: 			  '</li>';
  443: 	    }
  444: 	    $result.='</ul>';
  445: 	    return $result;
  446: 	}
  447:     } elsif ( $response =~ m/(?:numerical|formula|custom)/) {
  448:         # Respect multiple input fields, see Bug #5409
  449: 	$answer = 
  450: 	    &Apache::loncommon::format_previous_attempt_value('submission',
  451: 							      $answer);
  452: 	return $answer;
  453:     }
  454:     return &HTML::Entities::encode($answer, '"<>&');
  455: }
  456: 
  457: #-- A couple of common js functions
  458: sub commonJSfunctions {
  459:     my $request = shift;
  460:     $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
  461:     function radioSelection(radioButton) {
  462: 	var selection=null;
  463: 	if (radioButton.length > 1) {
  464: 	    for (var i=0; i<radioButton.length; i++) {
  465: 		if (radioButton[i].checked) {
  466: 		    return radioButton[i].value;
  467: 		}
  468: 	    }
  469: 	} else {
  470: 	    if (radioButton.checked) return radioButton.value;
  471: 	}
  472: 	return selection;
  473:     }
  474: 
  475:     function pullDownSelection(selectOne) {
  476: 	var selection="";
  477: 	if (selectOne.length > 1) {
  478: 	    for (var i=0; i<selectOne.length; i++) {
  479: 		if (selectOne[i].selected) {
  480: 		    return selectOne[i].value;
  481: 		}
  482: 	    }
  483: 	} else {
  484:             // only one value it must be the selected one
  485: 	    return selectOne.value;
  486: 	}
  487:     }
  488: COMMONJSFUNCTIONS
  489: }
  490: 
  491: #--- Dumps the class list with usernames,list of sections,
  492: #--- section, ids and fullnames for each user.
  493: sub getclasslist {
  494:     my ($getsec,$filterlist,$getgroup) = @_;
  495:     my @getsec;
  496:     my @getgroup;
  497:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  498:     if (!ref($getsec)) {
  499: 	if ($getsec ne '' && $getsec ne 'all') {
  500: 	    @getsec=($getsec);
  501: 	}
  502:     } else {
  503: 	@getsec=@{$getsec};
  504:     }
  505:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
  506:     if (!ref($getgroup)) {
  507: 	if ($getgroup ne '' && $getgroup ne 'all') {
  508: 	    @getgroup=($getgroup);
  509: 	}
  510:     } else {
  511: 	@getgroup=@{$getgroup};
  512:     }
  513:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
  514: 
  515:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
  516:     # Bail out if we were unable to get the classlist
  517:     return if (! defined($classlist));
  518:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
  519:     #
  520:     my %sections;
  521:     my %fullnames;
  522:     foreach my $student (keys(%$classlist)) {
  523:         my $end      = 
  524:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
  525:         my $start    = 
  526:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
  527:         my $id       = 
  528:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
  529:         my $section  = 
  530:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
  531:         my $fullname = 
  532:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
  533:         my $status   = 
  534:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
  535:         my $group   = 
  536:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
  537: 	# filter students according to status selected
  538: 	if ($filterlist && (!($stu_status =~ /Any/))) {
  539: 	    if (!($stu_status =~ $status)) {
  540: 		delete($classlist->{$student});
  541: 		next;
  542: 	    }
  543: 	}
  544: 	# filter students according to groups selected
  545: 	my @stu_groups = split(/,/,$group);
  546: 	if (@getgroup) {
  547: 	    my $exclude = 1;
  548: 	    foreach my $grp (@getgroup) {
  549: 	        foreach my $stu_group (@stu_groups) {
  550: 	            if ($stu_group eq $grp) {
  551: 	                $exclude = 0;
  552:     	            } 
  553: 	        }
  554:     	        if (($grp eq 'none') && !$group) {
  555:         	        $exclude = 0;
  556:         	}
  557: 	    }
  558: 	    if ($exclude) {
  559: 	        delete($classlist->{$student});
  560: 	    }
  561: 	}
  562: 	$section = ($section ne '' ? $section : 'none');
  563: 	if (&canview($section)) {
  564: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
  565: 		$sections{$section}++;
  566: 		if ($classlist->{$student}) {
  567: 		    $fullnames{$student}=$fullname;
  568: 		}
  569: 	    } else {
  570: 		delete($classlist->{$student});
  571: 	    }
  572: 	} else {
  573: 	    delete($classlist->{$student});
  574: 	}
  575:     }
  576:     my %seen = ();
  577:     my @sections = sort(keys(%sections));
  578:     return ($classlist,\@sections,\%fullnames);
  579: }
  580: 
  581: sub canmodify {
  582:     my ($sec)=@_;
  583:     if ($perm{'mgr'}) {
  584: 	if (!defined($perm{'mgr_section'})) {
  585: 	    # can modify whole class
  586: 	    return 1;
  587: 	} else {
  588: 	    if ($sec eq $perm{'mgr_section'}) {
  589: 		#can modify the requested section
  590: 		return 1;
  591: 	    } else {
  592: 		# can't modify the request section
  593: 		return 0;
  594: 	    }
  595: 	}
  596:     }
  597:     #can't modify
  598:     return 0;
  599: }
  600: 
  601: sub canview {
  602:     my ($sec)=@_;
  603:     if ($perm{'vgr'}) {
  604: 	if (!defined($perm{'vgr_section'})) {
  605: 	    # can modify whole class
  606: 	    return 1;
  607: 	} else {
  608: 	    if ($sec eq $perm{'vgr_section'}) {
  609: 		#can modify the requested section
  610: 		return 1;
  611: 	    } else {
  612: 		# can't modify the request section
  613: 		return 0;
  614: 	    }
  615: 	}
  616:     }
  617:     #can't modify
  618:     return 0;
  619: }
  620: 
  621: #--- Retrieve the grade status of a student for all the parts
  622: sub student_gradeStatus {
  623:     my ($symb,$udom,$uname,$partlist) = @_;
  624:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
  625:     my %partstatus = ();
  626:     foreach (@$partlist) {
  627: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
  628: 	$status              = 'nothing' if ($status eq '');
  629: 	$partstatus{$_}      = $status;
  630: 	my $subkey           = "resource.$_.submitted_by";
  631: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
  632:     }
  633:     return %partstatus;
  634: }
  635: 
  636: # hidden form and javascript that calls the form
  637: # Use by verifyscript and viewgrades
  638: # Shows a student's view of problem and submission
  639: sub jscriptNform {
  640:     my ($symb) = @_;
  641:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  642:     my $jscript= &Apache::lonhtmlcommon::scripttag(
  643: 	'    function viewOneStudent(user,domain) {'."\n".
  644: 	'	document.onestudent.student.value = user;'."\n".
  645: 	'	document.onestudent.userdom.value = domain;'."\n".
  646: 	'	document.onestudent.submit();'."\n".
  647: 	'    }'."\n".
  648: 	"\n");
  649:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
  650: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  651: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
  652: 	'<input type="hidden" name="command" value="submission" />'."\n".
  653: 	'<input type="hidden" name="student" value="" />'."\n".
  654: 	'<input type="hidden" name="userdom" value="" />'."\n".
  655: 	'</form>'."\n";
  656:     return $jscript;
  657: }
  658: 
  659: 
  660: 
  661: # Given the score (as a number [0-1] and the weight) what is the final
  662: # point value? This function will round to the nearest tenth, third,
  663: # or quarter if one of those is within the tolerance of .00001.
  664: sub compute_points {
  665:     my ($score, $weight) = @_;
  666:     
  667:     my $tolerance = .00001;
  668:     my $points = $score * $weight;
  669: 
  670:     # Check for nearness to 1/x.
  671:     my $check_for_nearness = sub {
  672:         my ($factor) = @_;
  673:         my $num = ($points * $factor) + $tolerance;
  674:         my $floored_num = floor($num);
  675:         if ($num - $floored_num < 2 * $tolerance * $factor) {
  676:             return $floored_num / $factor;
  677:         }
  678:         return $points;
  679:     };
  680: 
  681:     $points = $check_for_nearness->(10);
  682:     $points = $check_for_nearness->(3);
  683:     $points = $check_for_nearness->(4);
  684:     
  685:     return $points;
  686: }
  687: 
  688: #------------------ End of general use routines --------------------
  689: 
  690: #
  691: # Find most similar essay
  692: #
  693: 
  694: sub most_similar {
  695:     my ($uname,$udom,$symb,$uessay)=@_;
  696: 
  697:     unless ($symb) { return ''; }
  698: 
  699:     unless (ref($old_essays{$symb}) eq 'HASH') { return ''; }
  700: 
  701: # ignore spaces and punctuation
  702: 
  703:     $uessay=~s/\W+/ /gs;
  704: 
  705: # ignore empty submissions (occuring when only files are sent)
  706: 
  707:     unless ($uessay=~/\w+/s) { return ''; }
  708: 
  709: # these will be returned. Do not care if not at least 50 percent similar
  710:     my $limit=0.6;
  711:     my $sname='';
  712:     my $sdom='';
  713:     my $scrsid='';
  714:     my $sessay='';
  715: # go through all essays ...
  716:     foreach my $tkey (keys(%{$old_essays{$symb}})) {
  717: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
  718: # ... except the same student
  719:         next if (($tname eq $uname) && ($tdom eq $udom));
  720: 	my $tessay=$old_essays{$symb}{$tkey};
  721: 	$tessay=~s/\W+/ /gs;
  722: # String similarity gives up if not even limit
  723: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
  724: # Found one
  725: 	if ($tsimilar>$limit) {
  726: 	    $limit=$tsimilar;
  727: 	    $sname=$tname;
  728: 	    $sdom=$tdom;
  729: 	    $scrsid=$tcrsid;
  730: 	    $sessay=$old_essays{$symb}{$tkey};
  731: 	}
  732:     }
  733:     if ($limit>0.6) {
  734:        return ($sname,$sdom,$scrsid,$sessay,$limit);
  735:     } else {
  736:        return ('','','','',0);
  737:     }
  738: }
  739: 
  740: #-------------------------------------------------------------------
  741: 
  742: #------------------------------------ Receipt Verification Routines
  743: #
  744: 
  745: sub initialverifyreceipt {
  746:    my ($request,$symb) = @_;
  747:    &commonJSfunctions($request);
  748:    return '<form name="gradingMenu" action=""><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
  749:         &Apache::lonnet::recprefix($env{'request.course.id'}).
  750:         '-<input type="text" name="receipt" size="4" />'.
  751:         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  752:         '<input type="hidden" name="command" value="verify" />'.
  753:         "</form>\n";
  754: }
  755: 
  756: #--- Check whether a receipt number is valid.---
  757: sub verifyreceipt {
  758:     my ($request,$symb)  = @_;
  759: 
  760:     my $courseid = $env{'request.course.id'};
  761:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
  762: 	$env{'form.receipt'};
  763:     $receipt     =~ s/[^\-\d]//g;
  764: 
  765:     my $title.=
  766: 	'<h3><span class="LC_info">'.
  767: 	&mt('Verifying Receipt Number [_1]',$receipt).
  768: 	'</span></h3>'."\n";
  769: 
  770:     my ($string,$contents,$matches) = ('','',0);
  771:     my (undef,undef,$fullname) = &getclasslist('all','0');
  772:     
  773:     my $receiptparts=0;
  774:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
  775: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
  776:     my $parts=['0'];
  777:     if ($receiptparts) {
  778:         my $res_error; 
  779:         ($parts)=&response_type($symb,\$res_error);
  780:         if ($res_error) {
  781:             return &navmap_errormsg();
  782:         } 
  783:     }
  784:     
  785:     my $header = 
  786: 	&Apache::loncommon::start_data_table().
  787: 	&Apache::loncommon::start_data_table_header_row().
  788: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
  789: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
  790: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
  791:     if ($receiptparts) {
  792: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
  793:     }
  794:     $header.=
  795: 	&Apache::loncommon::end_data_table_header_row();
  796: 
  797:     foreach (sort 
  798: 	     {
  799: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  800: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  801: 		 }
  802: 		 return $a cmp $b;
  803: 	     } (keys(%$fullname))) {
  804: 	my ($uname,$udom)=split(/\:/);
  805: 	foreach my $part (@$parts) {
  806: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
  807: 		$contents.=
  808: 		    &Apache::loncommon::start_data_table_row().
  809: 		    '<td>&nbsp;'."\n".
  810: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
  811: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
  812: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
  813: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
  814: 		if ($receiptparts) {
  815: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
  816: 		}
  817: 		$contents.= 
  818: 		    &Apache::loncommon::end_data_table_row()."\n";
  819: 		
  820: 		$matches++;
  821: 	    }
  822: 	}
  823:     }
  824:     if ($matches == 0) {
  825:         $string = $title
  826:                  .'<p class="LC_warning">'
  827:                  .&mt('No match found for the above receipt number.')
  828:                  .'</p>';
  829:     } else {
  830: 	$string = &jscriptNform($symb).$title.
  831: 	    '<p>'.
  832: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
  833: 	    '</p>'.
  834: 	    $header.
  835: 	    $contents.
  836: 	    &Apache::loncommon::end_data_table()."\n";
  837:     }
  838:     return $string;
  839: }
  840: 
  841: #--- This is called by a number of programs.
  842: #--- Called from the Grading Menu - View/Grade an individual student
  843: #--- Also called directly when one clicks on the subm button 
  844: #    on the problem page.
  845: sub listStudents {
  846:     my ($request,$symb,$submitonly) = @_;
  847: 
  848:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
  849:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
  850:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
  851:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
  852:     unless ($submitonly) {
  853:        $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
  854:     }
  855: 
  856:     my $result='';
  857:     my $res_error;
  858:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
  859: 
  860:     my %js_lt = &Apache::lonlocal::texthash (
  861: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
  862: 		'single'   => 'Please select the student before clicking on the Next button.',
  863: 	     );
  864:     &js_escape(\%js_lt);
  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 = '$js_lt{'multiple'}';
  876: 	} else {
  877: 	    if (checkBox.checked) {
  878: 		ctr = 1;
  879: 	    }
  880: 	    sense = '$js_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:     &js_escape(\$alertmsg);
 1183:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1184:     function updateRadio(formname,id,weight) {
 1185: 	var gradeBox = formname["GD_BOX"+id];
 1186: 	var radioButton = formname["RADVAL"+id];
 1187: 	var oldpts = formname["oldpts"+id].value;
 1188: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
 1189: 	gradeBox.value = pts;
 1190: 	var resetbox = false;
 1191: 	if (isNaN(pts) || pts < 0) {
 1192: 	    alert("$alertmsg"+pts);
 1193: 	    for (var i=0; i<radioButton.length; i++) {
 1194: 		if (radioButton[i].checked) {
 1195: 		    gradeBox.value = i;
 1196: 		    resetbox = true;
 1197: 		}
 1198: 	    }
 1199: 	    if (!resetbox) {
 1200: 		formtextbox.value = "";
 1201: 	    }
 1202: 	    return;
 1203: 	}
 1204: 
 1205: 	if (pts > weight) {
 1206: 	    var resp = confirm("You entered a value ("+pts+
 1207: 			       ") greater than the weight for the part. Accept?");
 1208: 	    if (resp == false) {
 1209: 		gradeBox.value = oldpts;
 1210: 		return;
 1211: 	    }
 1212: 	}
 1213: 
 1214: 	for (var i=0; i<radioButton.length; i++) {
 1215: 	    radioButton[i].checked=false;
 1216: 	    if (pts == i && pts != "") {
 1217: 		radioButton[i].checked=true;
 1218: 	    }
 1219: 	}
 1220: 	updateSelect(formname,id);
 1221: 	formname["stores"+id].value = "0";
 1222:     }
 1223: 
 1224:     function writeBox(formname,id,pts) {
 1225: 	var gradeBox = formname["GD_BOX"+id];
 1226: 	if (checkSolved(formname,id) == 'update') {
 1227: 	    gradeBox.value = pts;
 1228: 	} else {
 1229: 	    var oldpts = formname["oldpts"+id].value;
 1230: 	    gradeBox.value = oldpts;
 1231: 	    var radioButton = formname["RADVAL"+id];
 1232: 	    for (var i=0; i<radioButton.length; i++) {
 1233: 		radioButton[i].checked=false;
 1234: 		if (i == oldpts) {
 1235: 		    radioButton[i].checked=true;
 1236: 		}
 1237: 	    }
 1238: 	}
 1239: 	formname["stores"+id].value = "0";
 1240: 	updateSelect(formname,id);
 1241: 	return;
 1242:     }
 1243: 
 1244:     function clearRadBox(formname,id) {
 1245: 	if (checkSolved(formname,id) == 'noupdate') {
 1246: 	    updateSelect(formname,id);
 1247: 	    return;
 1248: 	}
 1249: 	gradeSelect = formname["GD_SEL"+id];
 1250: 	for (var i=0; i<gradeSelect.length; i++) {
 1251: 	    if (gradeSelect[i].selected) {
 1252: 		var selectx=i;
 1253: 	    }
 1254: 	}
 1255: 	var stores = formname["stores"+id];
 1256: 	if (selectx == stores.value) { return };
 1257: 	var gradeBox = formname["GD_BOX"+id];
 1258: 	gradeBox.value = "";
 1259: 	var radioButton = formname["RADVAL"+id];
 1260: 	for (var i=0; i<radioButton.length; i++) {
 1261: 	    radioButton[i].checked=false;
 1262: 	}
 1263: 	stores.value = selectx;
 1264:     }
 1265: 
 1266:     function checkSolved(formname,id) {
 1267: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
 1268: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
 1269: 	    if (!reply) {return "noupdate";}
 1270: 	    formname.overRideScore.value = 'yes';
 1271: 	}
 1272: 	return "update";
 1273:     }
 1274: 
 1275:     function updateSelect(formname,id) {
 1276: 	formname["GD_SEL"+id][0].selected = true;
 1277: 	return;
 1278:     }
 1279: 
 1280: //=========== Check that a point is assigned for all the parts  ============
 1281:     function checksubmit(formname,val,total,parttot) {
 1282: 	formname.gradeOpt.value = val;
 1283: 	if (val == "Save & Next") {
 1284: 	    for (i=0;i<=total;i++) {
 1285: 		for (j=0;j<parttot;j++) {
 1286: 		    var partid = formname["partid"+i+"_"+j].value;
 1287: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1288: 			var points = formname["GD_BOX"+i+"_"+partid].value;
 1289: 			if (points == "") {
 1290: 			    var name = formname["name"+i].value;
 1291: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
 1292: 			    var resp = confirm("You did not assign a score for "+studentID+
 1293: 					       ", part "+partid+". Continue?");
 1294: 			    if (resp == false) {
 1295: 				formname["GD_BOX"+i+"_"+partid].focus();
 1296: 				return false;
 1297: 			    }
 1298: 			}
 1299: 		    }
 1300: 		}
 1301: 	    }
 1302: 	}
 1303: 	formname.submit();
 1304:     }
 1305: 
 1306: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1307:     function checkSubmitPage(formname,total) {
 1308: 	noscore = new Array(100);
 1309: 	var ptr = 0;
 1310: 	for (i=1;i<total;i++) {
 1311: 	    var partid = formname["q_"+i].value;
 1312: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1313: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1314: 		var status = formname["solved"+i+"_"+partid].value;
 1315: 		if (points == "" && status != "correct_by_student") {
 1316: 		    noscore[ptr] = i;
 1317: 		    ptr++;
 1318: 		}
 1319: 	    }
 1320: 	}
 1321: 	if (ptr != 0) {
 1322: 	    var sense = ptr == 1 ? ": " : "s: ";
 1323: 	    var prolist = "";
 1324: 	    if (ptr == 1) {
 1325: 		prolist = noscore[0];
 1326: 	    } else {
 1327: 		var i = 0;
 1328: 		while (i < ptr-1) {
 1329: 		    prolist += noscore[i]+", ";
 1330: 		    i++;
 1331: 		}
 1332: 		prolist += "and "+noscore[i];
 1333: 	    }
 1334: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1335: 	    if (resp == false) {
 1336: 		return false;
 1337: 	    }
 1338: 	}
 1339: 
 1340: 	formname.submit();
 1341:     }
 1342: SUBJAVASCRIPT
 1343: }
 1344: 
 1345: #--- javascript for essay type problem --
 1346: sub sub_page_kw_js {
 1347:     my $request = shift;
 1348:     my $iconpath = $request->dir_config('lonIconsURL');
 1349:     &commonJSfunctions($request);
 1350: 
 1351:     my $inner_js_msg_central= (<<INNERJS);
 1352: <script type="text/javascript">
 1353:     function checkInput() {
 1354:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1355:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1356:       var usrctr = document.msgcenter.usrctr.value;
 1357:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1358:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1359: 
 1360:       var msgchk = "";
 1361:       if (document.msgcenter.subchk.checked) {
 1362:          msgchk = "msgsub,";
 1363:       }
 1364:       var includemsg = 0;
 1365:       for (var i=1; i<=nmsg; i++) {
 1366:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1367:           var frmmsg = document.msgcenter["msg"+i];
 1368:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1369:           var showflg = opener.document.SCORE["shownOnce"+i];
 1370:           showflg.value = "1";
 1371:           var chkbox = document.msgcenter["msgn"+i];
 1372:           if (chkbox.checked) {
 1373:              msgchk += "savemsg"+i+",";
 1374:              includemsg = 1;
 1375:           }
 1376:       }
 1377:       if (document.msgcenter.newmsgchk.checked) {
 1378:          msgchk += "newmsg"+usrctr;
 1379:          includemsg = 1;
 1380:       }
 1381:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1382:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1383:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1384:       includemsg.value = msgchk;
 1385: 
 1386:       self.close()
 1387: 
 1388:     }
 1389: </script>
 1390: INNERJS
 1391: 
 1392:     my $inner_js_highlight_central= (<<INNERJS);
 1393: <script type="text/javascript">
 1394:     function updateChoice(flag) {
 1395:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1396:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1397:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1398:       opener.document.SCORE.refresh.value = "on";
 1399:       if (opener.document.SCORE.keywords.value!=""){
 1400:          opener.document.SCORE.submit();
 1401:       }
 1402:       self.close()
 1403:     }
 1404: </script>
 1405: INNERJS
 1406: 
 1407:     my $start_page_msg_central = 
 1408:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1409: 				       {'js_ready'  => 1,
 1410: 					'only_body' => 1,
 1411: 					'bgcolor'   =>'#FFFFFF',});
 1412:     my $end_page_msg_central = 
 1413: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1414: 
 1415: 
 1416:     my $start_page_highlight_central = 
 1417:         &Apache::loncommon::start_page('Highlight Central',
 1418: 				       $inner_js_highlight_central,
 1419: 				       {'js_ready'  => 1,
 1420: 					'only_body' => 1,
 1421: 					'bgcolor'   =>'#FFFFFF',});
 1422:     my $end_page_highlight_central = 
 1423: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1424: 
 1425:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1426:     $docopen=~s/^document\.//;
 1427:     my %js_lt = &Apache::lonlocal::texthash(
 1428:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
 1429:                 plse => 'Please select a word or group of words from document and then click this link.',
 1430:                 adds => 'Add selection to keyword list? Edit if desired.',
 1431:                 col1 => 'red',
 1432:                 col2 => 'green',
 1433:                 col3 => 'blue',
 1434:                 siz1 => 'normal',
 1435:                 siz2 => '+1',
 1436:                 siz3 => '+2',
 1437:                 sty1 => 'normal',
 1438:                 sty2 => 'italic',
 1439:                 sty3 => 'bold',
 1440:              );
 1441:     my %html_js_lt = &Apache::lonlocal::texthash(
 1442:                 comp => 'Compose Message for: ',
 1443:                 incl => 'Include',
 1444:                 type => 'Type',
 1445:                 subj => 'Subject',
 1446:                 mesa => 'Message',
 1447:                 new  => 'New',
 1448:                 save => 'Save',
 1449:                 canc => 'Cancel',
 1450:                 kehi => 'Keyword Highlight Options',
 1451:                 txtc => 'Text Color',
 1452:                 font => 'Font Size',
 1453:                 fnst => 'Font Style',
 1454:              );
 1455:     &js_escape(\%js_lt);
 1456:     &html_escape(\%html_js_lt);
 1457:     &js_escape(\%html_js_lt);
 1458:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1459: 
 1460: //===================== Show list of keywords ====================
 1461:   function keywords(formname) {
 1462:     var nret = prompt("$js_lt{'keyw'}",formname.keywords.value);
 1463:     if (nret==null) return;
 1464:     formname.keywords.value = nret;
 1465: 
 1466:     if (formname.keywords.value != "") {
 1467: 	formname.refresh.value = "on";
 1468: 	formname.submit();
 1469:     }
 1470:     return;
 1471:   }
 1472: 
 1473: //===================== Script to view submitted by ==================
 1474:   function viewSubmitter(submitter) {
 1475:     document.SCORE.refresh.value = "on";
 1476:     document.SCORE.NCT.value = "1";
 1477:     document.SCORE.unamedom0.value = submitter;
 1478:     document.SCORE.submit();
 1479:     return;
 1480:   }
 1481: 
 1482: //===================== Script to add keyword(s) ==================
 1483:   function getSel() {
 1484:     if (document.getSelection) txt = document.getSelection();
 1485:     else if (document.selection) txt = document.selection.createRange().text;
 1486:     else return;
 1487:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1488:     if (cleantxt=="") {
 1489: 	alert("$js_lt{'plse'}");
 1490: 	return;
 1491:     }
 1492:     var nret = prompt("$js_lt{'adds'}",cleantxt);
 1493:     if (nret==null) return;
 1494:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1495:     if (document.SCORE.keywords.value != "") {
 1496: 	document.SCORE.refresh.value = "on";
 1497: 	document.SCORE.submit();
 1498:     }
 1499:     return;
 1500:   }
 1501: 
 1502: //====================== Script for composing message ==============
 1503:    // preload images
 1504:    img1 = new Image();
 1505:    img1.src = "$iconpath/mailbkgrd.gif";
 1506:    img2 = new Image();
 1507:    img2.src = "$iconpath/mailto.gif";
 1508: 
 1509:   function msgCenter(msgform,usrctr,fullname) {
 1510:     var Nmsg  = msgform.savemsgN.value;
 1511:     savedMsgHeader(Nmsg,usrctr,fullname);
 1512:     var subject = msgform.msgsub.value;
 1513:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1514:     re = /msgsub/;
 1515:     var shwsel = "";
 1516:     if (re.test(msgchk)) { shwsel = "checked" }
 1517:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1518:     displaySubject(checkEntities(subject),shwsel);
 1519:     for (var i=1; i<=Nmsg; i++) {
 1520: 	var testmsg = "savemsg"+i+",";
 1521: 	re = new RegExp(testmsg,"g");
 1522: 	shwsel = "";
 1523: 	if (re.test(msgchk)) { shwsel = "checked" }
 1524: 	var message = document.SCORE["savemsg"+i].value;
 1525: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1526: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1527: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1528:     }
 1529:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1530:     shwsel = "";
 1531:     re = /newmsg/;
 1532:     if (re.test(msgchk)) { shwsel = "checked" }
 1533:     newMsg(newmsg,shwsel);
 1534:     msgTail(); 
 1535:     return;
 1536:   }
 1537: 
 1538:   function checkEntities(strx) {
 1539:     if (strx.length == 0) return strx;
 1540:     var orgStr = ["&", "<", ">", '"']; 
 1541:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1542:     var counter = 0;
 1543:     while (counter < 4) {
 1544: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1545: 	counter++;
 1546:     }
 1547:     return strx;
 1548:   }
 1549: 
 1550:   function strReplace(strx, orgStr, newStr) {
 1551:     return strx.split(orgStr).join(newStr);
 1552:   }
 1553: 
 1554:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1555:     var height = 70*Nmsg+250;
 1556:     if (height > 600) {
 1557: 	height = 600;
 1558:     }
 1559:     var xpos = (screen.width-600)/2;
 1560:     xpos = (xpos < 0) ? '0' : xpos;
 1561:     var ypos = (screen.height-height)/2-30;
 1562:     ypos = (ypos < 0) ? '0' : ypos;
 1563: 
 1564:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
 1565:     pWin.focus();
 1566:     pDoc = pWin.document;
 1567:     pDoc.$docopen;
 1568:     pDoc.write('$start_page_msg_central');
 1569: 
 1570:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1571:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1572:     pDoc.write("<h1>&nbsp;$html_js_lt{'comp'}\"+fullname+\"<\\/h1>");
 1573: 
 1574:     pDoc.write('<table style="border:1px solid black;"><tr>');
 1575:     pDoc.write("<td><b>$html_js_lt{'incl'}<\\/b><\\/td><td><b>$html_js_lt{'type'}<\\/b><\\/td><td><b>$html_js_lt{'mesa'}<\\/td><\\/tr>");
 1576: }
 1577:     function displaySubject(msg,shwsel) {
 1578:     pDoc = pWin.document;
 1579:     pDoc.write("<tr>");
 1580:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1581:     pDoc.write("<td>$html_js_lt{'subj'}<\\/td>");
 1582:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"40\\" maxlength=\\"80\\"><\\/td><\\/tr>");
 1583: }
 1584: 
 1585:   function displaySavedMsg(ctr,msg,shwsel) {
 1586:     pDoc = pWin.document;
 1587:     pDoc.write("<tr>");
 1588:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1589:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
 1590:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
 1591: }
 1592: 
 1593:   function newMsg(newmsg,shwsel) {
 1594:     pDoc = pWin.document;
 1595:     pDoc.write("<tr>");
 1596:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1597:     pDoc.write("<td align=\\"center\\">$html_js_lt{'new'}<\\/td>");
 1598:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
 1599: }
 1600: 
 1601:   function msgTail() {
 1602:     pDoc = pWin.document;
 1603:     //pDoc.write("<\\/table>");
 1604:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1605:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1606:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
 1607:     pDoc.write("<\\/form>");
 1608:     pDoc.write('$end_page_msg_central');
 1609:     pDoc.close();
 1610: }
 1611: 
 1612: //====================== Script for keyword highlight options ==============
 1613:   function kwhighlight() {
 1614:     var kwclr    = document.SCORE.kwclr.value;
 1615:     var kwsize   = document.SCORE.kwsize.value;
 1616:     var kwstyle  = document.SCORE.kwstyle.value;
 1617:     var redsel = "";
 1618:     var grnsel = "";
 1619:     var blusel = "";
 1620:     var txtcol1 = "$js_lt{'col1'}";
 1621:     var txtcol2 = "$js_lt{'col2'}";
 1622:     var txtcol3 = "$js_lt{'col3'}";
 1623:     var txtsiz1 = "$js_lt{'siz1'}";
 1624:     var txtsiz2 = "$js_lt{'siz2'}";
 1625:     var txtsiz3 = "$js_lt{'siz3'}";
 1626:     var txtsty1 = "$js_lt{'sty1'}";
 1627:     var txtsty2 = "$js_lt{'sty2'}";
 1628:     var txtsty3 = "$js_lt{'sty3'}";
 1629:     if (kwclr=="red")   {var redsel="checked='checked'"};
 1630:     if (kwclr=="green") {var grnsel="checked='checked'"};
 1631:     if (kwclr=="blue")  {var blusel="checked='checked'"};
 1632:     var sznsel = "";
 1633:     var sz1sel = "";
 1634:     var sz2sel = "";
 1635:     if (kwsize=="0")  {var sznsel="checked='checked'"};
 1636:     if (kwsize=="+1") {var sz1sel="checked='checked'"};
 1637:     if (kwsize=="+2") {var sz2sel="checked='checked'"};
 1638:     var synsel = "";
 1639:     var syisel = "";
 1640:     var sybsel = "";
 1641:     if (kwstyle=="")    {var synsel="checked='checked'"};
 1642:     if (kwstyle=="<i>") {var syisel="checked='checked'"};
 1643:     if (kwstyle=="<b>") {var sybsel="checked='checked'"};
 1644:     highlightCentral();
 1645:     highlightbody('red',txtcol1,redsel,'0',txtsiz1,sznsel,'',txtsty1,synsel);
 1646:     highlightbody('green',txtcol2,grnsel,'+1',txtsiz2,sz1sel,'<i>',txtsty2,syisel);
 1647:     highlightbody('blue',txtcol3,blusel,'+2',txtsiz3,sz2sel,'<b>',txtsty3,sybsel);
 1648:     highlightend();
 1649:     return;
 1650:   }
 1651: 
 1652:   function highlightCentral() {
 1653: //    if (window.hwdWin) window.hwdWin.close();
 1654:     var xpos = (screen.width-400)/2;
 1655:     xpos = (xpos < 0) ? '0' : xpos;
 1656:     var ypos = (screen.height-330)/2-30;
 1657:     ypos = (ypos < 0) ? '0' : ypos;
 1658: 
 1659:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1660:     hwdWin.focus();
 1661:     var hDoc = hwdWin.document;
 1662:     hDoc.$docopen;
 1663:     hDoc.write('$start_page_highlight_central');
 1664:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1665:     hDoc.write("<h1>$html_js_lt{'kehi'}<\\/h1>");
 1666: 
 1667:     hDoc.write('<table border="0" width="100%"><tr style="background-color:#A1D676">');
 1668:     hDoc.write("<th>$html_js_lt{'txtc'}<\\/th><th>$html_js_lt{'font'}<\\/th><th>$html_js_lt{'fnst'}<\\/th><\\/tr>");
 1669:   }
 1670: 
 1671:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1672:     var hDoc = hwdWin.document;
 1673:     hDoc.write("<tr>");
 1674:     hDoc.write("<td align=\\"left\\">");
 1675:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+" \\/>&nbsp;"+clrtxt+"<\\/td>");
 1676:     hDoc.write("<td align=\\"left\\">");
 1677:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+" \\/>&nbsp;"+sztxt+"<\\/td>");
 1678:     hDoc.write("<td align=\\"left\\">");
 1679:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+" \\/>&nbsp;"+sytxt+"<\\/td>");
 1680:     hDoc.write("<\\/tr>");
 1681:   }
 1682: 
 1683:   function highlightend() { 
 1684:     var hDoc = hwdWin.document;
 1685:     hDoc.write("<\\/table><br \\/>");
 1686:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\" \\/>&nbsp;&nbsp;");
 1687:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\" \\/><br /><br />");
 1688:     hDoc.write("<\\/form>");
 1689:     hDoc.write('$end_page_highlight_central');
 1690:     hDoc.close();
 1691:   }
 1692: 
 1693: SUBJAVASCRIPT
 1694: }
 1695: 
 1696: sub get_increment {
 1697:     my $increment = $env{'form.increment'};
 1698:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1699:         $increment != .1) {
 1700:         $increment = 1;
 1701:     }
 1702:     return $increment;
 1703: }
 1704: 
 1705: sub gradeBox_start {
 1706:     return (
 1707:         &Apache::loncommon::start_data_table()
 1708:        .&Apache::loncommon::start_data_table_header_row()
 1709:        .'<th>'.&mt('Part').'</th>'
 1710:        .'<th>'.&mt('Points').'</th>'
 1711:        .'<th>&nbsp;</th>'
 1712:        .'<th>'.&mt('Assign Grade').'</th>'
 1713:        .'<th>'.&mt('Weight').'</th>'
 1714:        .'<th>'.&mt('Grade Status').'</th>'
 1715:        .&Apache::loncommon::end_data_table_header_row()
 1716:     );
 1717: }
 1718: 
 1719: sub gradeBox_end {
 1720:     return (
 1721:         &Apache::loncommon::end_data_table()
 1722:     );
 1723: }
 1724: #--- displays the grading box, used in essay type problem and grading by page/sequence
 1725: sub gradeBox {
 1726:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 1727:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1728: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 1729:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 1730:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
 1731:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
 1732:     $wgt       = ($wgt > 0 ? $wgt : '1');
 1733:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 1734: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 1735:     my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 1736:     my $display_part= &get_display_part($partid,$symb);
 1737:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 1738: 				       [$partid]);
 1739:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 1740:     if ($last_resets{$partid}) {
 1741:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 1742:     }
 1743:     my $result=&Apache::loncommon::start_data_table_row();
 1744:     my $ctr = 0;
 1745:     my $thisweight = 0;
 1746:     my $increment = &get_increment();
 1747: 
 1748:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 1749:     while ($thisweight<=$wgt) {
 1750: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 1751:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 1752: 	    $thisweight.')" value="'.$thisweight.'" '.
 1753: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 1754: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 1755:         $thisweight += $increment;
 1756: 	$ctr++;
 1757:     }
 1758:     $radio.='</tr></table>';
 1759: 
 1760:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 1761: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 1762: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 1763: 	$wgt.')" /></td>'."\n";
 1764:     $line.='<td>/'.$wgt.' '.$wgtmsg.
 1765: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 1766: 	' </td>'."\n";
 1767:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
 1768: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 1769:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 1770: 	$line.='<option></option>'.
 1771: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
 1772:     } else {
 1773: 	$line.='<option selected="selected"></option>'.
 1774: 	    '<option value="excused" >'.&mt('excused').'</option>';
 1775:     }
 1776:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
 1777: 
 1778: 
 1779:     $result .= 
 1780: 	    '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
 1781:     $result.=&Apache::loncommon::end_data_table_row();
 1782:     $result.=&Apache::loncommon::start_data_table_row().'<td colspan="6">';
 1783:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 1784: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 1785: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 1786: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 1787:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 1788:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 1789:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 1790:         $aggtries.'" />'."\n";
 1791:     my $res_error;
 1792:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
 1793:     $result.='</td>'.&Apache::loncommon::end_data_table_row();
 1794:     if ($res_error) {
 1795:         return &navmap_errormsg();
 1796:     }
 1797:     return $result;
 1798: }
 1799: 
 1800: sub handback_box {
 1801:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
 1802:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error_pointer);
 1803:     my (@respids);
 1804:     my @part_response_id = &flatten_responseType($responseType);
 1805:     foreach my $part_response_id (@part_response_id) {
 1806:     	my ($part,$resp) = @{ $part_response_id };
 1807:         if ($part eq $partid) {
 1808:             push(@respids,$resp);
 1809:         }
 1810:     }
 1811:     my $result;
 1812:     foreach my $respid (@respids) {
 1813: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 1814: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 1815: 	next if (!@$files);
 1816: 	my $file_counter = 0;
 1817: 	foreach my $file (@$files) {
 1818: 	    if ($file =~ /\/portfolio\//) {
 1819:                 $file_counter++;
 1820:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 1821:     	        my ($name,$version,$ext) = &Apache::lonnet::file_name_version_ext($file_disp);
 1822:     	        $file_disp = "$name.$ext";
 1823:     	        $file = $file_path.$file_disp;
 1824:     	        $result.=&mt('Return commented version of [_1] to student.',
 1825:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 1826:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 1827:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
 1828: 	    }
 1829: 	}
 1830:         if ($file_counter) {
 1831:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
 1832:                        '<span class="LC_info">'.
 1833:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
 1834:         }
 1835:     }
 1836:     return $result;    
 1837: }
 1838: 
 1839: sub show_problem {
 1840:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 1841:     my $rendered;
 1842:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 1843:     &Apache::lonxml::remember_problem_counter();
 1844:     if ($mode eq 'both' or $mode eq 'text') {
 1845: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 1846: 						       $env{'request.course.id'},
 1847: 						       undef,\%form);
 1848:     }
 1849:     if ($removeform) {
 1850: 	$rendered=~s|<form(.*?)>||g;
 1851: 	$rendered=~s|</form>||g;
 1852: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 1853:     }
 1854:     my $companswer;
 1855:     if ($mode eq 'both' or $mode eq 'answer') {
 1856: 	&Apache::lonxml::restore_problem_counter();
 1857: 	$companswer=
 1858: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 1859: 						    $env{'request.course.id'},
 1860: 						    %form);
 1861:     }
 1862:     if ($removeform) {
 1863: 	$companswer=~s|<form(.*?)>||g;
 1864: 	$companswer=~s|</form>||g;
 1865: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 1866:     }
 1867:     my $renderheading = &mt('View of the problem');
 1868:     my $answerheading = &mt('Correct answer');
 1869:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 1870:         my $stu_fullname = $env{'form.fullname'};
 1871:         if ($stu_fullname eq '') {
 1872:             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
 1873:         }
 1874:         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
 1875:         if ($forwhom ne '') {
 1876:             $renderheading = &mt('View of the problem for[_1]',$forwhom);
 1877:             $answerheading = &mt('Correct answer for[_1]',$forwhom);
 1878:         }
 1879:     }
 1880:     $rendered=
 1881:         '<div class="LC_Box">'
 1882:        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
 1883:        .$rendered
 1884:        .'</div>';
 1885:     $companswer=
 1886:         '<div class="LC_Box">'
 1887:        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
 1888:        .$companswer
 1889:        .'</div>';
 1890:     my $result;
 1891:     if ($mode eq 'both') {
 1892:         $result=$rendered.$companswer;
 1893:     } elsif ($mode eq 'text') {
 1894:         $result=$rendered;
 1895:     } elsif ($mode eq 'answer') {
 1896:         $result=$companswer;
 1897:     }
 1898:     return $result;
 1899: }
 1900: 
 1901: sub files_exist {
 1902:     my ($r, $symb) = @_;
 1903:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1904: 
 1905:     foreach my $student (@students) {
 1906:         my ($uname,$udom,$fullname) = split(/:/,$student);
 1907:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 1908: 					      $udom,$uname);
 1909:         my ($string,$timestamp)= &get_last_submission(\%record);
 1910:         foreach my $submission (@$string) {
 1911:             my ($partid,$respid) =
 1912: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 1913:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 1914: 					   \%record);
 1915:             return 1 if (@$files);
 1916:         }
 1917:     }
 1918:     return 0;
 1919: }
 1920: 
 1921: sub download_all_link {
 1922:     my ($r,$symb) = @_;
 1923:     unless (&files_exist($r, $symb)) {
 1924:        $r->print(&mt('There are currently no submitted documents.'));
 1925:        return;
 1926:     }
 1927: 
 1928:     my $all_students = 
 1929: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 1930: 
 1931:     my $parts =
 1932: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 1933: 
 1934:     my $identifier = &Apache::loncommon::get_cgi_id();
 1935:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 1936:                              'cgi.'.$identifier.'.symb' => $symb,
 1937:                              'cgi.'.$identifier.'.parts' => $parts,});
 1938:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 1939: 	      &mt('Download All Submitted Documents').'</a>');
 1940:     return;
 1941: }
 1942: 
 1943: sub submit_download_link {
 1944:     my ($request,$symb) = @_;
 1945:     if (!$symb) { return ''; }
 1946: #FIXME: Figure out which type of problem this is and provide appropriate download
 1947:     &download_all_link($request,$symb);
 1948: }
 1949: 
 1950: sub build_section_inputs {
 1951:     my $section_inputs;
 1952:     if ($env{'form.section'} eq '') {
 1953:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 1954:     } else {
 1955:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 1956:         foreach my $section (@sections) {
 1957:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 1958:         }
 1959:     }
 1960:     return $section_inputs;
 1961: }
 1962: 
 1963: # --------------------------- show submissions of a student, option to grade 
 1964: sub submission {
 1965:     my ($request,$counter,$total,$symb) = @_;
 1966:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 1967:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 1968:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 1969:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 1970: 
 1971:     my $probtitle=&Apache::lonnet::gettitle($symb); 
 1972:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 1973: 
 1974:     if (!&canview($usec)) {
 1975:         $request->print(
 1976:             '<span class="LC_warning">'.
 1977:             &mt('Unable to view requested student.').
 1978:             ' '.&mt('([_1] in section [_2] in course id [_3])',
 1979:                         $uname.':'.$udom,$usec,$env{'request.course.id'}).
 1980:             '</span>');
 1981: 	return;
 1982:     }
 1983: 
 1984:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 1985:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 1986:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 1987:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 1988:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1989: 	'" src="'.$request->dir_config('lonIconsURL').
 1990: 	'/check.gif" height="16" border="0" />';
 1991: 
 1992:     # header info
 1993:     if ($counter == 0) {
 1994: 	&sub_page_js($request);
 1995: 	&sub_page_kw_js($request);
 1996: 
 1997: 	# option to display problem, only once else it cause problems 
 1998:         # with the form later since the problem has a form.
 1999: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 2000: 	    my $mode;
 2001: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 2002: 		$mode='both';
 2003: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 2004: 		$mode='text';
 2005: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 2006: 		$mode='answer';
 2007: 	    }
 2008: 	    &Apache::lonxml::clear_problem_counter();
 2009: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 2010: 	}
 2011: 
 2012: 	# kwclr is the only variable that is guaranteed not to be blank 
 2013:         # if this subroutine has been called once.
 2014: 	my %keyhash = ();
 2015: #	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
 2016:         if (1) {
 2017: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 2018: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 2019: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 2020: 
 2021: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2022: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 2023: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 2024: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 2025: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 2026: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
 2027: 		$keyhash{$symb.'_subject'} : $probtitle;
 2028: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 2029: 	}
 2030: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 2031: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 2032: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 2033: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 2034: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 2035: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 2036: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 2037: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 2038: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 2039: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 2040: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 2041: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 2042: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 2043: 			&build_section_inputs().
 2044: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 2045: 			'<input type="hidden" name="NCT"'.
 2046: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 2047: #	if ($env{'form.handgrade'} eq 'yes') {
 2048:         if (1) {
 2049: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 2050: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 2051: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 2052: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
 2053: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 2054: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 2055: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 2056: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
 2057: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
 2058: 	    }
 2059: 	}
 2060: 	
 2061: 	my ($cts,$prnmsg) = (1,'');
 2062: 	while ($cts <= $env{'form.savemsgN'}) {
 2063: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 2064: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 2065: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 2066: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 2067: 		'" />'."\n".
 2068: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 2069: 	    $cts++;
 2070: 	}
 2071: 	$request->print($prnmsg);
 2072: 
 2073: #	if ($env{'form.handgrade'} eq 'yes') {
 2074:         if (1) {
 2075: 
 2076:             my %lt = &Apache::lonlocal::texthash(
 2077:                           keyh => 'Keyword Highlighting for Essays',
 2078:                           keyw => 'Keyword Options',
 2079:                           list => 'List',
 2080:                           past => 'Paste Selection to List',
 2081:                           high => 'Highlight Attribute',
 2082:                      );    
 2083: #
 2084: # Print out the keyword options line
 2085: #
 2086: 	    $request->print(
 2087:                 '<div class="LC_columnSection">'
 2088:                .'<fieldset><legend>'.$lt{'keyh'}.'</legend>'
 2089:                .&Apache::lonhtmlcommon::funclist_from_array(
 2090:                     ['<a href="javascript:keywords(document.SCORE);" target="_self">'.$lt{'list'}.'</a>',
 2091:                      '<a href="#" onmousedown="javascript:getSel(); return false"
 2092:  class="page">'.$lt{'past'}.'</a>',
 2093:                      '<a href="javascript:kwhighlight();" target="_self">'.$lt{'high'}.'</a>'],
 2094:                     {legend => $lt{'keyw'}})
 2095:                .'</fieldset></div>'
 2096:             );
 2097: 
 2098: #
 2099: # Load the other essays for similarity check
 2100: #
 2101:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 2102: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 2103: 	    $apath=&escape($apath);
 2104: 	    $apath=~s/\W/\_/gs;
 2105:             &init_old_essays($symb,$apath,$adom,$aname);
 2106:         }
 2107:     }
 2108: 
 2109: # This is where output for one specific student would start
 2110:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
 2111:     $request->print(
 2112:         "\n\n"
 2113:        .'<div class="LC_grade_show_user'.$add_class.'">'
 2114:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
 2115:        ."\n"
 2116:     );
 2117: 
 2118:     # Show additional functions if allowed
 2119:     if ($perm{'vgr'}) {
 2120:         $request->print(
 2121:             &Apache::loncommon::track_student_link(
 2122:                 'View recent activity',
 2123:                 $uname,$udom,'check')
 2124:            .' '
 2125:         );
 2126:     }
 2127:     if ($perm{'opa'}) {
 2128:         $request->print(
 2129:             &Apache::loncommon::pprmlink(
 2130:                 &mt('Set/Change parameters'),
 2131:                 $uname,$udom,$symb,'check'));
 2132:     }
 2133: 
 2134:     # Show Problem
 2135:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2136: 	my $mode;
 2137: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2138: 	    $mode='both';
 2139: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2140: 	    $mode='text';
 2141: 	} elsif ($env{'form.vAns'} eq 'all') {
 2142: 	    $mode='answer';
 2143: 	}
 2144: 	&Apache::lonxml::clear_problem_counter();
 2145: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2146:     }
 2147: 
 2148:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2149:     my $res_error;
 2150:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2151:     if ($res_error) {
 2152:         $request->print(&navmap_errormsg());
 2153:         return;
 2154:     }
 2155: 
 2156:     # Display student info
 2157:     $request->print(($counter == 0 ? '' : '<br />'));
 2158: 
 2159:     my $result='<div class="LC_Box">'
 2160:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
 2161:     $result.='<input type="hidden" name="name'.$counter.
 2162:              '" value="'.$env{'form.fullname'}.'" />'."\n";
 2163: #    if ($env{'form.handgrade'} eq 'no') {
 2164:     if (1) {
 2165:         $result.='<p class="LC_info">'
 2166:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
 2167:                 ."</p>\n";
 2168:     }
 2169: 
 2170:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
 2171:     my $fullname;
 2172:     my $col_fullnames = [];
 2173: #    if ($env{'form.handgrade'} eq 'yes') {
 2174:     if (1) {
 2175: 	(my $sub_result,$fullname,$col_fullnames)=
 2176: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2177: 				 $counter);
 2178: 	$result.=$sub_result;
 2179:     }
 2180:     $request->print($result."\n");
 2181:     
 2182:     # print student answer/submission
 2183:     # Options are (1) Handgraded submission only
 2184:     #             (2) Last submission, includes submission that is not handgraded 
 2185:     #                  (for multi-response type part)
 2186:     #             (3) Last submission plus the parts info
 2187:     #             (4) The whole record for this student
 2188:     
 2189:     my ($string,$timestamp)= &get_last_submission(\%record);
 2190: 	
 2191:     my $lastsubonly;
 2192: 
 2193:     if ($$timestamp eq '') {
 2194:         $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
 2195:     } else {
 2196:         $lastsubonly =
 2197:             '<div class="LC_grade_submissions_body">'
 2198:            .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
 2199: 
 2200: 	my %seenparts;
 2201: 	my @part_response_id = &flatten_responseType($responseType);
 2202: 	foreach my $part (@part_response_id) {
 2203: 	    next if ($env{'form.lastSub'} eq 'hdgrade' 
 2204: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
 2205: 
 2206: 	    my ($partid,$respid) = @{ $part };
 2207: 	    my $display_part=&get_display_part($partid,$symb);
 2208: 	    if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2209: 		if (exists($seenparts{$partid})) { next; }
 2210: 		$seenparts{$partid}=1;
 2211:                 $request->print(
 2212:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2213:                     ' <b>'.&mt('Collaborative submission by: [_1]',
 2214:                                '<a href="javascript:viewSubmitter(\''.
 2215:                                $env{"form.$uname:$udom:$partid:submitted_by"}.
 2216:                                '\');" target="_self">'.
 2217:                                $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
 2218:                     '<br />');
 2219: 		next;
 2220: 		}
 2221: 	    my $responsetype = $responseType->{$partid}->{$respid};
 2222: 	    if (!exists($record{"resource.$partid.$respid.submission"})) {
 2223:                 $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
 2224:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2225:                     ' <span class="LC_internal_info">'.
 2226:                     '('.&mt('Response ID: [_1]',$respid).')'.
 2227:                     '</span>&nbsp; &nbsp;'.
 2228: 	       	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
 2229: 		next;
 2230: 	    }
 2231: 	    foreach my $submission (@$string) {
 2232: 		my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2233: 		if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2234: 		my ($ressub,$hide,$draft,$subval) = split(/:/,$submission,4);
 2235: 		# Similarity check
 2236:                 my $similar='';
 2237:                 my ($type,$trial,$rndseed);
 2238:                 if ($hide eq 'rand') {
 2239:                     $type = 'randomizetry';
 2240:                     $trial = $record{"resource.$partid.tries"};
 2241:                     $rndseed = $record{"resource.$partid.rndseed"};
 2242:                 }
 2243: 	        if ($env{'form.checkPlag'}) {
 2244:     		    my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2245: 		        &most_similar($uname,$udom,$symb,$subval);
 2246: 		    if ($osim) {
 2247: 			$osim=int($osim*100.0);
 2248: 			my %old_course_desc = 
 2249: 			    &Apache::lonnet::coursedescription($ocrsid,
 2250: 							{'one_time' => 1});
 2251: 
 2252:                         if ($hide eq 'anon') {
 2253:                             $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
 2254:                                      &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
 2255:                         } else {
 2256: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
 2257: 				&mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
 2258: 				    $osim,
 2259: 				    &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
 2260: 				        $old_course_desc{'description'},
 2261: 				        $old_course_desc{'num'},
 2262: 				        $old_course_desc{'domain'}).
 2263: 				    '</span></h3><blockquote><i>'.
 2264: 				    &keywords_highlight($oessay).
 2265: 				    '</i></blockquote><hr />';
 2266:                         }
 2267: 	            }
 2268: 		}
 2269: 		my $order=&get_order($partid,$respid,$symb,$uname,$udom,
 2270:                                      undef,$type,$trial,$rndseed);
 2271:                 if ($env{'form.lastSub'} eq 'lastonly' || $env{'form.lastSub'} eq 'datesub' || $env{'form.lastSub'} =~ /^(last|all)$/ || ($env{'form.lastSub'} eq 'hdgrade' && 
 2272: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
 2273: 		    my $display_part=&get_display_part($partid,$symb);
 2274:                     $lastsubonly.='<div class="LC_grade_submission_part">'.
 2275:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2276:                         ' <span class="LC_internal_info">'.
 2277:                         '('.&mt('Response ID: [_1]',$respid).')'.
 2278:                         '</span>&nbsp; &nbsp;';
 2279: 		    my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2280:                         
 2281: 		    if (@$files) {
 2282:                         if ($hide eq 'anon') {
 2283:                             $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
 2284:                         } else {
 2285:                             $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
 2286:                                         .'<br /><span class="LC_warning">';
 2287:                             if(@$files == 1) {
 2288:                                 $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
 2289:                             } else {
 2290:                                 $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
 2291:                             }
 2292:                             $lastsubonly .= '</span>';                         
 2293:                             foreach my $file (@$files) {
 2294:                                 &Apache::lonnet::allowuploaded('/adm/grades',$file);
 2295:                                 $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
 2296:                             }
 2297:                         }
 2298: 			$lastsubonly.='<br />';
 2299:                     }
 2300:                     if ($hide eq 'anon') {
 2301:                         $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>'; 
 2302:                     } else {
 2303:              	        $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>';
 2304:                         if ($draft) {
 2305:                             $lastsubonly.= ' <span class="LC_warning">'.&mt('Draft Copy').'</span>';
 2306:                         }
 2307:                         $subval =
 2308: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
 2309: 					 $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
 2310:                         if ($responsetype eq 'essay') {
 2311:                             $subval =~ s{\n}{<br />}g;
 2312:                         }
 2313:                         $lastsubonly.=$subval."\n";
 2314:                     }
 2315: 	            if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2316: 		    $lastsubonly.='</div>';
 2317: 		}
 2318:             }
 2319: 	}
 2320: 	$lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
 2321:     }
 2322:     $request->print($lastsubonly);
 2323:     if ($env{'form.lastSub'} eq 'datesub') {
 2324:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2325: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2326:   
 2327:     } 
 2328:     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2329:         my $identifier = (&canmodify($usec)? $counter : '');
 2330:         $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2331: 								 $env{'request.course.id'},
 2332: 								 $last,'.submission',
 2333: 								 'Apache::grades::keywords_highlight',
 2334:                                                                  $usec,$identifier));
 2335:     }
 2336:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2337: 	.$udom.'" />'."\n");
 2338:     # return if view submission with no grading option
 2339:     if (!&canmodify($usec)) {
 2340: 	$request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
 2341: 	return;
 2342:     } else {
 2343: 	$request->print('</div>'."\n");
 2344:     }
 2345: 
 2346:     # essay grading message center
 2347: #    if ($env{'form.handgrade'} eq 'yes') {
 2348:     if (1) {
 2349: 	my $result='<div class="LC_grade_message_center">';
 2350:     
 2351: 	$result.='<div class="LC_grade_message_center_header">'.
 2352: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
 2353: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2354: 	my $msgfor = $givenn.' '.$lastname;
 2355: 	if (scalar(@$col_fullnames) > 0) {
 2356: 	    my $lastone = pop(@$col_fullnames);
 2357: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2358: 	}
 2359: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2360: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2361: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
 2362: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2363: 	    ',\''.$msgfor.'\');" target="_self">'.
 2364: 	    &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
 2365: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2366: 	    ' <img src="'.$request->dir_config('lonIconsURL').
 2367: 	    '/mailbkgrd.gif" width="14" height="10" alt="" name="mailicon'.$counter.'" />'."\n".
 2368: 	    '<br />&nbsp;('.
 2369: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
 2370: 	$result.='</div></div>';
 2371: 	$request->print($result);
 2372:     }
 2373: 
 2374:     my %seen = ();
 2375:     my @partlist;
 2376:     my @gradePartRespid;
 2377:     my @part_response_id = &flatten_responseType($responseType);
 2378:     $request->print(
 2379:         '<div class="LC_Box">'
 2380:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
 2381:     );
 2382:     $request->print(&gradeBox_start());
 2383:     foreach my $part_response_id (@part_response_id) {
 2384:     	my ($partid,$respid) = @{ $part_response_id };
 2385: 	my $part_resp = join('_',@{ $part_response_id });
 2386: 	next if ($seen{$partid} > 0);
 2387: 	$seen{$partid}++;
 2388: 	next if ($$handgrade{$part_resp} ne 'yes' 
 2389: 		 && $env{'form.lastSub'} eq 'hdgrade');
 2390: 	push(@partlist,$partid);
 2391: 	push(@gradePartRespid,$partid.'.'.$respid);
 2392: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2393:     }
 2394:     $request->print(&gradeBox_end()); # </div>
 2395:     $request->print('</div>');
 2396: 
 2397:     $request->print('<div class="LC_grade_info_links">');
 2398:     $request->print('</div>');
 2399: 
 2400:     $result='<input type="hidden" name="partlist'.$counter.
 2401: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2402:     $result.='<input type="hidden" name="gradePartRespid'.
 2403: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2404:     my $ctr = 0;
 2405:     while ($ctr < scalar(@partlist)) {
 2406: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2407: 	    $partlist[$ctr].'" />'."\n";
 2408: 	$ctr++;
 2409:     }
 2410:     $request->print($result.''."\n");
 2411: 
 2412: # Done with printing info for one student
 2413: 
 2414:     $request->print('</div>');#LC_grade_show_user
 2415: 
 2416: 
 2417:     # print end of form
 2418:     if ($counter == $total) {
 2419:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
 2420: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2421: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
 2422: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2423: 	my $ntstu ='<select name="NTSTU">'.
 2424: 	    '<option>1</option><option>2</option>'.
 2425: 	    '<option>3</option><option>5</option>'.
 2426: 	    '<option>7</option><option>10</option></select>'."\n";
 2427: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2428: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2429:         $endform.=&mt('[_1]student(s)',$ntstu);
 2430: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2431: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2432: 	    '<input type="button" value="'.&mt('Next').'" '.
 2433: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2434:         $endform.='<span class="LC_warning">'.
 2435:                   &mt('(Next and Previous (student) do not save the scores.)').
 2436:                   '</span>'."\n" ;
 2437:         $endform.="<input type='hidden' value='".&get_increment().
 2438:             "' name='increment' />";
 2439: 	$endform.='</td></tr></table></form>';
 2440: 	$request->print($endform);
 2441:     }
 2442:     return '';
 2443: }
 2444: 
 2445: sub check_collaborators {
 2446:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2447:     my ($result,@col_fullnames);
 2448:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2449:     foreach my $part (keys(%$handgrade)) {
 2450: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2451: 					'.maxcollaborators',
 2452: 					$symb,$udom,$uname);
 2453: 	next if ($ncol <= 0);
 2454: 	$part =~ s/\_/\./g;
 2455: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2456: 	my (@good_collaborators, @bad_collaborators);
 2457: 	foreach my $possible_collaborator
 2458: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2459: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2460: 	    next if ($possible_collaborator eq '');
 2461: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
 2462: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2463: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2464: 	    # Doing this grep allows 'fuzzy' specification
 2465: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2466: 			       keys(%$classlist));
 2467: 	    if (! scalar(@matches)) {
 2468: 		push(@bad_collaborators, $possible_collaborator);
 2469: 	    } else {
 2470: 		push(@good_collaborators, @matches);
 2471: 	    }
 2472: 	}
 2473: 	if (scalar(@good_collaborators) != 0) {
 2474: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
 2475: 	    foreach my $name (@good_collaborators) {
 2476: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2477: 		push(@col_fullnames, $givenn.' '.$lastname);
 2478: 		$result.='<li>'.$fullname->{$name}.'</li>';
 2479: 	    }
 2480: 	    $result.='</ol><br />'."\n";
 2481: 	    my ($part)=split(/\./,$part);
 2482: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2483: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2484: 		"\n";
 2485: 	}
 2486: 	if (scalar(@bad_collaborators) > 0) {
 2487: 	    $result.='<div class="LC_warning">';
 2488: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2489: 	    $result .= '</div>';
 2490: 	}         
 2491: 	if (scalar(@bad_collaborators > $ncol)) {
 2492: 	    $result .= '<div class="LC_warning">';
 2493: 	    $result .= &mt('This student has submitted too many '.
 2494: 		'collaborators.  Maximum is [_1].',$ncol);
 2495: 	    $result .= '</div>';
 2496: 	}
 2497:     }
 2498:     return ($result,$fullname,\@col_fullnames);
 2499: }
 2500: 
 2501: #--- Retrieve the last submission for all the parts
 2502: sub get_last_submission {
 2503:     my ($returnhash)=@_;
 2504:     my (@string,$timestamp,%lasthidden);
 2505:     if ($$returnhash{'version'}) {
 2506: 	my %lasthash=();
 2507: 	my ($version);
 2508: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2509: 	    foreach my $key (sort(split(/\:/,
 2510: 					$$returnhash{$version.':keys'}))) {
 2511: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2512: 		$timestamp = 
 2513: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2514: 	    }
 2515: 	}
 2516:         my (%typeparts,%randombytry);
 2517:         my $showsurv = 
 2518:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
 2519:         foreach my $key (sort(keys(%lasthash))) {
 2520:             if ($key =~ /\.type$/) {
 2521:                 if (($lasthash{$key} eq 'anonsurvey') || 
 2522:                     ($lasthash{$key} eq 'anonsurveycred') ||
 2523:                     ($lasthash{$key} eq 'randomizetry')) {
 2524:                     my ($ign,@parts) = split(/\./,$key);
 2525:                     pop(@parts);
 2526:                     my $id = join('.',@parts);
 2527:                     if ($lasthash{$key} eq 'randomizetry') {
 2528:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
 2529:                     } else {
 2530:                         unless ($showsurv) {
 2531:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
 2532:                         }
 2533:                     }
 2534:                     delete($lasthash{$key});
 2535:                 }
 2536:             }
 2537:         }
 2538:         my @hidden = keys(%typeparts);
 2539:         my @randomize = keys(%randombytry);
 2540: 	foreach my $key (keys(%lasthash)) {
 2541: 	    next if ($key !~ /\.submission$/);
 2542:             my $hide;
 2543:             if (@hidden) {
 2544:                 foreach my $id (@hidden) {
 2545:                     if ($key =~ /^\Q$id\E/) {
 2546:                         $hide = 'anon';
 2547:                         last;
 2548:                     }
 2549:                 }
 2550:             }
 2551:             unless ($hide) {
 2552:                 if (@randomize) {
 2553:                     foreach my $id (@randomize) {
 2554:                         if ($key =~ /^\Q$id\E/) {
 2555:                             $hide = 'rand';
 2556:                             last;
 2557:                         }
 2558:                     }
 2559:                 }
 2560:             }
 2561: 	    my ($partid,$foo) = split(/submission$/,$key);
 2562: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ? 1 : 0;
 2563:             push(@string, join(':', $key, $hide, $draft, (
 2564:                 ref($lasthash{$key}) eq 'ARRAY' ?
 2565:                     join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
 2566: 	}
 2567:     }
 2568:     if (!@string) {
 2569: 	$string[0] =
 2570: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
 2571:     }
 2572:     return (\@string,\$timestamp);
 2573: }
 2574: 
 2575: #--- High light keywords, with style choosen by user.
 2576: sub keywords_highlight {
 2577:     my $string    = shift;
 2578:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2579:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2580:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2581:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2582:     foreach my $keyword (@keylist) {
 2583: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2584:     }
 2585:     return $string;
 2586: }
 2587: 
 2588: # For Tasks provide a mechanism to display previous version for one specific student
 2589: 
 2590: sub show_previous_task_version {
 2591:     my ($request,$symb) = @_;
 2592:     if ($symb eq '') {
 2593:         $request->print(
 2594:             '<span class="LC_error">'.
 2595:             &mt('Unable to handle ambiguous references.').
 2596:             '</span>');
 2597:         return '';
 2598:     }
 2599:     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
 2600:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 2601:     if (!&canview($usec)) {
 2602:         $request->print(
 2603:             '<span class="LC_warning">'.
 2604:             &mt('Unable to view previous version for requested student.').
 2605:             ' '.&mt('([_1] in section [_2] in course id [_3])',
 2606:                     $uname.':'.$udom,$usec,$env{'request.course.id'}).
 2607:             '</span>');
 2608:         return;
 2609:     }
 2610:     my $mode = 'both';
 2611:     my $isTask = ($symb =~/\.task$/);
 2612:     if ($isTask) {
 2613:         if ($env{'form.previousversion'} =~ /^\d+$/) {
 2614:             if ($env{'form.fullname'} eq '') {
 2615:                 $env{'form.fullname'} =
 2616:                     &Apache::loncommon::plainname($uname,$udom,'lastname');
 2617:             }
 2618:             my $probtitle=&Apache::lonnet::gettitle($symb);
 2619:             $request->print("\n\n".
 2620:                             '<div class="LC_grade_show_user">'.
 2621:                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 2622:                             '</h2>'."\n");
 2623:             &Apache::lonxml::clear_problem_counter();
 2624:             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
 2625:                             {'previousversion' => $env{'form.previousversion'} }));
 2626:             $request->print("\n</div>");
 2627:         }
 2628:     }
 2629:     return;
 2630: }
 2631: 
 2632: sub choose_task_version_form {
 2633:     my ($symb,$uname,$udom,$nomenu) = @_;
 2634:     my $isTask = ($symb =~/\.task$/);
 2635:     my ($current,$version,$result,$js,$displayed,$rowtitle);
 2636:     if ($isTask) {
 2637:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 2638:                                               $udom,$uname);
 2639:         if (($record{'resource.0.version'} eq '') ||
 2640:             ($record{'resource.0.version'} < 2)) {
 2641:             return ($record{'resource.0.version'},
 2642:                     $record{'resource.0.version'},$result,$js);
 2643:         } else {
 2644:             $current = $record{'resource.0.version'};
 2645:         }
 2646:         if ($env{'form.previousversion'}) {
 2647:             $displayed = $env{'form.previousversion'};
 2648:             $rowtitle = &mt('Choose another version:')
 2649:         } else {
 2650:             $displayed = $current;
 2651:             $rowtitle = &mt('Show earlier version:');
 2652:         }
 2653:         $result = '<div class="LC_left_float">';
 2654:         my $list;
 2655:         my $numversions = 0;
 2656:         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
 2657:             if ($i == $current) {
 2658:                 if (!$env{'form.previousversion'} || $nomenu) {
 2659:                     next;
 2660:                 } else {
 2661:                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
 2662:                     $numversions ++;
 2663:                 }
 2664:             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
 2665:                 unless ($i == $env{'form.previousversion'}) {
 2666:                     $numversions ++;
 2667:                 }
 2668:                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
 2669:             }
 2670:         }
 2671:         if ($numversions) {
 2672:             $symb = &HTML::Entities::encode($symb,'<>"&');
 2673:             $result .=
 2674:                 '<form name="getprev" method="post" action=""'.
 2675:                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
 2676:                 &Apache::loncommon::start_data_table().
 2677:                 &Apache::loncommon::start_data_table_row().
 2678:                 '<th align="left">'.$rowtitle.'</th>'.
 2679:                 '<td><select name="version">'.
 2680:                 '<option>'.&mt('Select').'</option>'.
 2681:                 $list.
 2682:                 '</select></td>'.
 2683:                 &Apache::loncommon::end_data_table_row();
 2684:             unless ($nomenu) {
 2685:                 $result .= &Apache::loncommon::start_data_table_row().
 2686:                 '<th align="left">'.&mt('Open in new window').'</th>'.
 2687:                 '<td><span class="LC_nobreak">'.
 2688:                 '<label><input type="radio" name="prevwin" value="1" />'.
 2689:                 &mt('Yes').'</label>'.
 2690:                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
 2691:                 '</span></td>'.
 2692:                 &Apache::loncommon::end_data_table_row();
 2693:             }
 2694:             $result .=
 2695:                 &Apache::loncommon::start_data_table_row().
 2696:                 '<th align="left">&nbsp;</th>'.
 2697:                 '<td>'.
 2698:                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
 2699:                 '</td>'.
 2700:                 &Apache::loncommon::end_data_table_row().
 2701:                 &Apache::loncommon::end_data_table().
 2702:                 '</form>';
 2703:             $js = &previous_display_javascript($nomenu,$current);
 2704:         } elsif ($displayed && $nomenu) {
 2705:             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
 2706:         } else {
 2707:             $result .= &mt('No previous versions to show for this student');
 2708:         }
 2709:         $result .= '</div>';
 2710:     }
 2711:     return ($current,$displayed,$result,$js);
 2712: }
 2713: 
 2714: sub previous_display_javascript {
 2715:     my ($nomenu,$current) = @_;
 2716:     my $js = <<"JSONE";
 2717: <script type="text/javascript">
 2718: // <![CDATA[
 2719: function previousVersion(uname,udom,symb) {
 2720:     var current = '$current';
 2721:     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
 2722:     var prevstr = new RegExp("^\\\\d+\$");
 2723:     if (!prevstr.test(version)) {
 2724:         return false;
 2725:     }
 2726:     var url = '';
 2727:     if (version == current) {
 2728:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
 2729:     } else {
 2730:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
 2731:     }
 2732: JSONE
 2733:     if ($nomenu) {
 2734:         $js .= <<"JSTWO";
 2735:     document.location.href = url;
 2736: JSTWO
 2737:     } else {
 2738:         $js .= <<"JSTHREE";
 2739:     var newwin = 0;
 2740:     for (var i=0; i<document.getprev.prevwin.length; i++) {
 2741:         if (document.getprev.prevwin[i].checked == true) {
 2742:             newwin = document.getprev.prevwin[i].value;
 2743:         }
 2744:     }
 2745:     if (newwin == 1) {
 2746:         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
 2747:         url = url+'&inhibitmenu=yes';
 2748:         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
 2749:             previousWin = window.open(url,'',options,1);
 2750:         } else {
 2751:             previousWin.location.href = url;
 2752:         }
 2753:         previousWin.focus();
 2754:         return false;
 2755:     } else {
 2756:         document.location.href = url;
 2757:         return false;
 2758:     }
 2759: JSTHREE
 2760:     }
 2761:     $js .= <<"ENDJS";
 2762:     return false;
 2763: }
 2764: // ]]>
 2765: </script>
 2766: ENDJS
 2767: 
 2768: }
 2769: 
 2770: #--- Called from submission routine
 2771: sub processHandGrade {
 2772:     my ($request,$symb) = @_;
 2773:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2774:     my $button = $env{'form.gradeOpt'};
 2775:     my $ngrade = $env{'form.NCT'};
 2776:     my $ntstu  = $env{'form.NTSTU'};
 2777:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2778:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 2779: 
 2780:     if ($button eq 'Save & Next') {
 2781: 	my $ctr = 0;
 2782: 	while ($ctr < $ngrade) {
 2783: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 2784: 	    my ($errorflag,$pts,$wgt,$numhidden) = 
 2785:                 &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 2786: 	    if ($errorflag eq 'no_score') {
 2787: 		$ctr++;
 2788: 		next;
 2789: 	    }
 2790: 	    if ($errorflag eq 'not_allowed') {
 2791: 		$request->print(
 2792:                     '<span class="LC_error">'
 2793:                    .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
 2794:                    .'</span>');
 2795: 		$ctr++;
 2796: 		next;
 2797: 	    }
 2798:             if ($numhidden) {
 2799:                 $request->print(
 2800:                     '<span class="LC_info">'
 2801:                    .&mt('For [_1]: [quant,_2,transaction] hidden',"$uname:$udom",$numhidden)
 2802:                    .'</span><br />');
 2803:             }
 2804: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 2805: 	    my ($subject,$message,$msgstatus) = ('','','');
 2806: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 2807:             my ($feedurl,$showsymb) =
 2808: 		&get_feedurl_and_symb($symb,$uname,$udom);
 2809: 	    my $messagetail;
 2810: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 2811: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 2812: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 2813: 		$subject.=' ['.$restitle.']';
 2814: 		my (@msgnum) = split(/,/,$includemsg);
 2815: 		foreach (@msgnum) {
 2816: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 2817: 		}
 2818: 		$message =&Apache::lonfeedback::clear_out_html($message);
 2819: 		if ($env{'form.withgrades'.$ctr}) {
 2820: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 2821: 		    $messagetail = " for <a href=\"".
 2822: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
 2823: 		}
 2824: 		$msgstatus = 
 2825:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 2826: 						     $message.$messagetail,
 2827:                                                      undef,$feedurl,undef,
 2828:                                                      undef,undef,$showsymb,
 2829:                                                      $restitle);
 2830: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
 2831: 				$msgstatus.'<br />');
 2832: 	    }
 2833: 	    if ($env{'form.collaborator'.$ctr}) {
 2834: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 2835: 		foreach my $collabstr (@collabstrs) {
 2836: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 2837: 		    foreach my $collaborator (@collaborators) {
 2838: 			my ($errorflag,$pts,$wgt) = 
 2839: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 2840: 					   $env{'form.unamedom'.$ctr},$part);
 2841: 			if ($errorflag eq 'not_allowed') {
 2842: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 2843: 			    next;
 2844: 			} elsif ($message ne '') {
 2845: 			    my ($baseurl,$showsymb) = 
 2846: 				&get_feedurl_and_symb($symb,$collaborator,
 2847: 						      $udom);
 2848: 			    if ($env{'form.withgrades'.$ctr}) {
 2849: 				$messagetail = " for <a href=\"".
 2850:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
 2851: 			    }
 2852: 			    $msgstatus = 
 2853: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 2854: 			}
 2855: 		    }
 2856: 		}
 2857: 	    }
 2858: 	    $ctr++;
 2859: 	}
 2860:     }
 2861: 
 2862: #    if ($env{'form.handgrade'} eq 'yes') {
 2863:     if (1) {
 2864: 	# Keywords sorted in alphabatical order
 2865: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2866: 	my %keyhash = ();
 2867: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 2868: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 2869: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 2870: 	$env{'form.keywords'} = join(' ',@keywords);
 2871: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 2872: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 2873: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 2874: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 2875: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 2876: 
 2877: 	# message center - Order of message gets changed. Blank line is eliminated.
 2878: 	# New messages are saved in env for the next student.
 2879: 	# All messages are saved in nohist_handgrade.db
 2880: 	my ($ctr,$idx) = (1,1);
 2881: 	while ($ctr <= $env{'form.savemsgN'}) {
 2882: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 2883: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 2884: 		$idx++;
 2885: 	    }
 2886: 	    $ctr++;
 2887: 	}
 2888: 	$ctr = 0;
 2889: 	while ($ctr < $ngrade) {
 2890: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 2891: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2892: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2893: 		$idx++;
 2894: 	    }
 2895: 	    $ctr++;
 2896: 	}
 2897: 	$env{'form.savemsgN'} = --$idx;
 2898: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 2899: 	my $putresult = &Apache::lonnet::put
 2900: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 2901:     }
 2902:     # Called by Save & Refresh from Highlight Attribute Window
 2903:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 2904:     if ($env{'form.refresh'} eq 'on') {
 2905: 	my ($ctr,$total) = (0,0);
 2906: 	while ($ctr < $ngrade) {
 2907: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 2908: 	    $ctr++;
 2909: 	}
 2910: 	$env{'form.NTSTU'}=$ngrade;
 2911: 	$ctr = 0;
 2912: 	while ($ctr < $total) {
 2913: 	    my $processUser = $env{'form.unamedom'.$ctr};
 2914: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2915: 	    $env{'form.fullname'} = $$fullname{$processUser};
 2916: 	    &submission($request,$ctr,$total-1,$symb);
 2917: 	    $ctr++;
 2918: 	}
 2919: 	return '';
 2920:     }
 2921: 
 2922:     # Get the next/previous one or group of students
 2923:     my $firststu = $env{'form.unamedom0'};
 2924:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 2925:     my $ctr = 2;
 2926:     while ($laststu eq '') {
 2927: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 2928: 	$ctr++;
 2929: 	$laststu = $firststu if ($ctr > $ngrade);
 2930:     }
 2931: 
 2932:     my (@parsedlist,@nextlist);
 2933:     my ($nextflg) = 0;
 2934:     foreach my $item (sort 
 2935: 	     {
 2936: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 2937: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 2938: 		 }
 2939: 		 return $a cmp $b;
 2940: 	     } (keys(%$fullname))) {
 2941: # FIXME: this is fishy, looks like the button label
 2942: 	if ($nextflg == 1 && $button =~ /Next$/) {
 2943: 	    push(@parsedlist,$item);
 2944: 	}
 2945: 	$nextflg = 1 if ($item eq $laststu);
 2946: 	if ($button eq 'Previous') {
 2947: 	    last if ($item eq $firststu);
 2948: 	    push(@parsedlist,$item);
 2949: 	}
 2950:     }
 2951:     $ctr = 0;
 2952: # FIXME: this is fishy, looks like the button label
 2953:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 2954:     my $res_error;
 2955:     my ($partlist) = &response_type($symb,\$res_error);
 2956:     if ($res_error) {
 2957:         $request->print(&navmap_errormsg());
 2958:         return;
 2959:     }
 2960:     foreach my $student (@parsedlist) {
 2961: 	my $submitonly=$env{'form.submitonly'};
 2962: 	my ($uname,$udom) = split(/:/,$student);
 2963: 	
 2964: 	if ($submitonly eq 'queued') {
 2965: 	    my %queue_status = 
 2966: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 2967: 							$udom,$uname);
 2968: 	    next if (!defined($queue_status{'gradingqueue'}));
 2969: 	}
 2970: 
 2971: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 2972: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2973: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 2974: 	    my $submitted = 0;
 2975: 	    my $ungraded = 0;
 2976: 	    my $incorrect = 0;
 2977: 	    foreach my $item (keys(%status)) {
 2978: 		$submitted = 1 if ($status{$item} ne 'nothing');
 2979: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 2980: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 2981: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 2982: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 2983: 		    $submitted = 0;
 2984: 		}
 2985: 	    }
 2986: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 2987: 				     $submitonly eq 'incorrect' ||
 2988: 				     $submitonly eq 'graded'));
 2989: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 2990: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 2991: 	}
 2992: 	push(@nextlist,$student) if ($ctr < $ntstu);
 2993: 	last if ($ctr == $ntstu);
 2994: 	$ctr++;
 2995:     }
 2996: 
 2997:     $ctr = 0;
 2998:     my $total = scalar(@nextlist)-1;
 2999: 
 3000:     foreach (sort(@nextlist)) {
 3001: 	my ($uname,$udom,$submitter) = split(/:/);
 3002: 	$env{'form.student'}  = $uname;
 3003: 	$env{'form.userdom'}  = $udom;
 3004: 	$env{'form.fullname'} = $$fullname{$_};
 3005: 	&submission($request,$ctr,$total,$symb);
 3006: 	$ctr++;
 3007:     }
 3008:     if ($total < 0) {
 3009: 	my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
 3010: 	$request->print($the_end);
 3011:     }
 3012:     return '';
 3013: }
 3014: 
 3015: #---- Save the score and award for each student, if changed
 3016: sub saveHandGrade {
 3017:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 3018:     my @version_parts;
 3019:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 3020: 					   $env{'request.course.id'});
 3021:     if (!&canmodify($usec)) { return('not_allowed'); }
 3022:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 3023:     my @parts_graded;
 3024:     my %newrecord  = ();
 3025:     my ($pts,$wgt,$totchg) = ('','',0);
 3026:     my %aggregate = ();
 3027:     my $aggregateflag = 0;
 3028:     if ($env{'form.HIDE'.$newflg}) {
 3029:         my ($version,$parts) = split(/:/,$env{'form.HIDE'.$newflg},2);
 3030:         my $numchgs = &makehidden($version,$parts,\%record,$symb,$domain,$stuname,1);
 3031:         $totchg += $numchgs;
 3032:     }
 3033:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 3034:     foreach my $new_part (@parts) {
 3035: 	#collaborator ($submi may vary for different parts
 3036: 	if ($submitter && $new_part ne $part) { next; }
 3037: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 3038: 	if ($dropMenu eq 'excused') {
 3039: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 3040: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 3041: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 3042: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 3043: 		}
 3044: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3045: 	    }
 3046: 	} elsif ($dropMenu eq 'reset status'
 3047: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 3048: 	    foreach my $key (keys(%record)) {
 3049: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 3050: 	    }
 3051: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3052: 		"$env{'user.name'}:$env{'user.domain'}";
 3053:             my $totaltries = $record{'resource.'.$part.'.tries'};
 3054: 
 3055:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 3056: 					       [$new_part]);
 3057:             my $aggtries =$totaltries;
 3058:             if ($last_resets{$new_part}) {
 3059:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 3060: 					   $new_part);
 3061:             }
 3062: 
 3063:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 3064:             if ($aggtries > 0) {
 3065:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3066:                 $aggregateflag = 1;
 3067:             }
 3068: 	} elsif ($dropMenu eq '') {
 3069: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 3070: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 3071: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 3072: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 3073: 		next;
 3074: 	    }
 3075: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 3076: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 3077: 	    my $partial= $pts/$wgt;
 3078: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 3079: 		#do not update score for part if not changed.
 3080:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 3081: 		next;
 3082: 	    } else {
 3083: 	        push(@parts_graded,$new_part);
 3084: 	    }
 3085: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 3086: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 3087: 	    }
 3088: 	    my $reckey = 'resource.'.$new_part.'.solved';
 3089: 	    if ($partial == 0) {
 3090: 		if ($record{$reckey} ne 'incorrect_by_override') {
 3091: 		    $newrecord{$reckey} = 'incorrect_by_override';
 3092: 		}
 3093: 	    } else {
 3094: 		if ($record{$reckey} ne 'correct_by_override') {
 3095: 		    $newrecord{$reckey} = 'correct_by_override';
 3096: 		}
 3097: 	    }	    
 3098: 	    if ($submitter && 
 3099: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 3100: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 3101: 	    }
 3102: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3103: 		"$env{'user.name'}:$env{'user.domain'}";
 3104: 	}
 3105: 	# unless problem has been graded, set flag to version the submitted files
 3106: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 3107: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 3108: 	        $dropMenu eq 'reset status')
 3109: 	   {
 3110: 	    push(@version_parts,$new_part);
 3111: 	}
 3112:     }
 3113:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3114:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3115: 
 3116:     if (%newrecord) {
 3117:         if (@version_parts) {
 3118:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 3119:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 3120: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 3121: 	    foreach my $new_part (@version_parts) {
 3122: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 3123: 				$new_part,\%newrecord);
 3124: 	    }
 3125:         }
 3126: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 3127: 				$env{'request.course.id'},$domain,$stuname);
 3128: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 3129: 				     $cdom,$cnum,$domain,$stuname);
 3130:     }
 3131:     if ($aggregateflag) {
 3132:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3133: 			      $cdom,$cnum);
 3134:     }
 3135:     return ('',$pts,$wgt,$totchg);
 3136: }
 3137: 
 3138: sub makehidden {
 3139:     my ($version,$parts,$record,$symb,$domain,$stuname,$tolog) = @_;
 3140:     return unless (ref($record) eq 'HASH');
 3141:     my %modified;
 3142:     my $numchanged = 0;
 3143:     if (exists($record->{$version.':keys'})) {
 3144:         my $partsregexp = $parts;
 3145:         $partsregexp =~ s/,/|/g;
 3146:         foreach my $key (split(/\:/,$record->{$version.':keys'})) {
 3147:             if ($key =~ /^resource\.(?:$partsregexp)\.([^\.]+)$/) {
 3148:                  my $item = $1;
 3149:                  unless (($item eq 'solved') || ($item =~ /^award(|msg|ed)$/)) {
 3150:                      $modified{$key} = $record->{$version.':'.$key};
 3151:                  }
 3152:             } elsif ($key =~ m{^(resource\.(?:$partsregexp)\.[^\.]+\.)(.+)$}) {
 3153:                 $modified{$1.'hidden'.$2} = $record->{$version.':'.$key};
 3154:             } elsif ($key =~ /^(ip|timestamp|host)$/) {
 3155:                 $modified{$key} = $record->{$version.':'.$key};
 3156:             }
 3157:         }
 3158:         if (keys(%modified)) {
 3159:             if (&Apache::lonnet::putstore($env{'request.course.id'},$symb,$version,\%modified,
 3160:                                           $domain,$stuname,$tolog) eq 'ok') {
 3161:                 $numchanged ++;
 3162:             }
 3163:         }
 3164:     }
 3165:     return $numchanged;
 3166: }
 3167: 
 3168: sub check_and_remove_from_queue {
 3169:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 3170:     my @ungraded_parts;
 3171:     foreach my $part (@{$parts}) {
 3172: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 3173: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 3174: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 3175: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 3176: 		) {
 3177: 	    push(@ungraded_parts, $part);
 3178: 	}
 3179:     }
 3180:     if ( !@ungraded_parts ) {
 3181: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 3182: 					       $cnum,$domain,$stuname);
 3183:     }
 3184: }
 3185: 
 3186: sub handback_files {
 3187:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 3188:     my $portfolio_root = '/userfiles/portfolio';
 3189:     my $res_error;
 3190:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3191:     if ($res_error) {
 3192:         $request->print('<br />'.&navmap_errormsg().'<br />');
 3193:         return;
 3194:     }
 3195:     my @handedback;
 3196:     my $file_msg;
 3197:     my @part_response_id = &flatten_responseType($responseType);
 3198:     foreach my $part_response_id (@part_response_id) {
 3199:     	my ($part_id,$resp_id) = @{ $part_response_id };
 3200: 	my $part_resp = join('_',@{ $part_response_id });
 3201:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
 3202:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
 3203:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3' 
 3204:                 if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
 3205:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
 3206:                     my ($directory,$answer_file) = 
 3207:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
 3208:                     my ($answer_name,$answer_ver,$answer_ext) =
 3209: 		        &Apache::lonnet::file_name_version_ext($answer_file);
 3210: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 3211:                     my $getpropath = 1;
 3212:                     my ($dir_list,$listerror) = 
 3213:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
 3214:                                                  $domain,$stuname,$getpropath);
 3215: 		    my $version = &Apache::lonnet::get_next_version($answer_name,$answer_ext,$dir_list);
 3216:                     # fix filename
 3217:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 3218:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 3219:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
 3220:             	                                $save_file_name);
 3221:                     if ($result !~ m|^/uploaded/|) {
 3222:                         $request->print('<br /><span class="LC_error">'.
 3223:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 3224:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
 3225:                                         '</span>');
 3226:                     } else {
 3227:                         # mark the file as read only
 3228:                         push(@handedback,$save_file_name);
 3229: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 3230: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 3231: 			}
 3232:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 3233: 			$file_msg.= '<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
 3234:                     }
 3235:                     $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>'));
 3236:                 }
 3237:             }
 3238:         }
 3239:     }
 3240:     if (@handedback > 0) {
 3241:         $request->print('<br />');
 3242:         my @what = ($symb,$env{'request.course.id'},'handback');
 3243:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
 3244:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});    
 3245:         my ($subject,$message);
 3246:         if (scalar(@handedback) == 1) {
 3247:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
 3248:             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
 3249:         } else {
 3250:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
 3251:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
 3252:         }
 3253:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
 3254:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
 3255:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
 3256:         my ($feedurl,$showsymb) =
 3257:             &get_feedurl_and_symb($symb,$domain,$stuname);
 3258:         my $restitle = &Apache::lonnet::gettitle($symb);
 3259:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
 3260:         my $msgstatus =
 3261:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
 3262:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
 3263:                  $restitle);
 3264:         if ($msgstatus) {
 3265:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
 3266:         }
 3267:     }
 3268:     return;
 3269: }
 3270: 
 3271: sub get_feedurl_and_symb {
 3272:     my ($symb,$uname,$udom) = @_;
 3273:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3274:     $url = &Apache::lonnet::clutter($url);
 3275:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 3276: 					$symb,$udom,$uname);
 3277:     if ($encrypturl =~ /^yes$/i) {
 3278: 	&Apache::lonenc::encrypted(\$url,1);
 3279: 	&Apache::lonenc::encrypted(\$symb,1);
 3280:     }
 3281:     return ($url,$symb);
 3282: }
 3283: 
 3284: sub get_submitted_files {
 3285:     my ($udom,$uname,$partid,$respid,$record) = @_;
 3286:     my @files;
 3287:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 3288:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 3289:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 3290:     	    push(@files,$file_url.$file);
 3291:         }
 3292:     }
 3293:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 3294:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 3295:     }
 3296:     return (\@files);
 3297: }
 3298: 
 3299: # ----------- Provides number of tries since last reset.
 3300: sub get_num_tries {
 3301:     my ($record,$last_reset,$part) = @_;
 3302:     my $timestamp = '';
 3303:     my $num_tries = 0;
 3304:     if ($$record{'version'}) {
 3305:         for (my $version=$$record{'version'};$version>=1;$version--) {
 3306:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 3307:                 $timestamp = $$record{$version.':timestamp'};
 3308:                 if ($timestamp > $last_reset) {
 3309:                     $num_tries ++;
 3310:                 } else {
 3311:                     last;
 3312:                 }
 3313:             }
 3314:         }
 3315:     }
 3316:     return $num_tries;
 3317: }
 3318: 
 3319: # ----------- Determine decrements required in aggregate totals 
 3320: sub decrement_aggs {
 3321:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 3322:     my %decrement = (
 3323:                         attempts => 0,
 3324:                         users => 0,
 3325:                         correct => 0
 3326:                     );
 3327:     $decrement{'attempts'} = $aggtries;
 3328:     if ($solvedstatus =~ /^correct/) {
 3329:         $decrement{'correct'} = 1;
 3330:     }
 3331:     if ($aggtries == $totaltries) {
 3332:         $decrement{'users'} = 1;
 3333:     }
 3334:     foreach my $type (keys(%decrement)) {
 3335:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 3336:     }
 3337:     return;
 3338: }
 3339: 
 3340: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 3341: sub get_last_resets {
 3342:     my ($symb,$courseid,$partids) =@_;
 3343:     my %last_resets;
 3344:     my $cdom = $env{'course.'.$courseid.'.domain'};
 3345:     my $cname = $env{'course.'.$courseid.'.num'};
 3346:     my @keys;
 3347:     foreach my $part (@{$partids}) {
 3348: 	push(@keys,"$symb\0$part\0resettime");
 3349:     }
 3350:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 3351: 				     $cdom,$cname);
 3352:     foreach my $part (@{$partids}) {
 3353: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 3354:     }
 3355:     return %last_resets;
 3356: }
 3357: 
 3358: # ----------- Handles creating versions for portfolio files as answers
 3359: sub version_portfiles {
 3360:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 3361:     my $version_parts = join('|',@$v_flag);
 3362:     my @returned_keys;
 3363:     my $parts = join('|', @$parts_graded);
 3364:     foreach my $key (keys(%$record)) {
 3365:         my $new_portfiles;
 3366:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 3367:             my @versioned_portfiles;
 3368:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 3369:             if (@portfiles) {
 3370:                 &Apache::lonnet::portfiles_versioning($symb,$domain,$stu_name,\@portfiles,
 3371:                                                       \@versioned_portfiles);
 3372:             }
 3373:             $$record{$key} = join(',',@versioned_portfiles);
 3374:             push(@returned_keys,$key);
 3375:         }
 3376:     } 
 3377:     return (@returned_keys);   
 3378: }
 3379: 
 3380: #--------------------------------------------------------------------------------------
 3381: #
 3382: #-------------------------- Next few routines handles grading by section or whole class
 3383: #
 3384: #--- Javascript to handle grading by section or whole class
 3385: sub viewgrades_js {
 3386:     my ($request) = shift;
 3387: 
 3388:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3389:     &js_escape(\$alertmsg);
 3390:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
 3391:    function writePoint(partid,weight,point) {
 3392: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3393: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3394: 	if (point == "textval") {
 3395: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3396: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3397: 		alert("$alertmsg"+parseFloat(point));
 3398: 		var resetbox = false;
 3399: 		for (var i=0; i<radioButton.length; i++) {
 3400: 		    if (radioButton[i].checked) {
 3401: 			textbox.value = i;
 3402: 			resetbox = true;
 3403: 		    }
 3404: 		}
 3405: 		if (!resetbox) {
 3406: 		    textbox.value = "";
 3407: 		}
 3408: 		return;
 3409: 	    }
 3410: 	    if (parseFloat(point) > parseFloat(weight)) {
 3411: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3412: 				   ") greater than the weight for the part. Accept?");
 3413: 		if (resp == false) {
 3414: 		    textbox.value = "";
 3415: 		    return;
 3416: 		}
 3417: 	    }
 3418: 	    for (var i=0; i<radioButton.length; i++) {
 3419: 		radioButton[i].checked=false;
 3420: 		if (parseFloat(point) == i) {
 3421: 		    radioButton[i].checked=true;
 3422: 		}
 3423: 	    }
 3424: 
 3425: 	} else {
 3426: 	    textbox.value = parseFloat(point);
 3427: 	}
 3428: 	for (i=0;i<document.classgrade.total.value;i++) {
 3429: 	    var user = document.classgrade["ctr"+i].value;
 3430: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3431: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3432: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3433: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3434: 	    if (saveval != "correct") {
 3435: 		scorename.value = point;
 3436: 		if (selname[0].selected != true) {
 3437: 		    selname[0].selected = true;
 3438: 		}
 3439: 	    }
 3440: 	}
 3441: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3442:     }
 3443: 
 3444:     function writeRadText(partid,weight) {
 3445: 	var selval   = document.classgrade["SELVAL_"+partid];
 3446: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3447:         var override = document.classgrade["FORCE_"+partid].checked;
 3448: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3449: 	if (selval[1].selected || selval[2].selected) {
 3450: 	    for (var i=0; i<radioButton.length; i++) {
 3451: 		radioButton[i].checked=false;
 3452: 
 3453: 	    }
 3454: 	    textbox.value = "";
 3455: 
 3456: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3457: 		var user = document.classgrade["ctr"+i].value;
 3458: 		user = user.replace(new RegExp(':', 'g'),"_");
 3459: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3460: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3461: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3462: 		if ((saveval != "correct") || override) {
 3463: 		    scorename.value = "";
 3464: 		    if (selval[1].selected) {
 3465: 			selname[1].selected = true;
 3466: 		    } else {
 3467: 			selname[2].selected = true;
 3468: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3469: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3470: 		    }
 3471: 		}
 3472: 	    }
 3473: 	} else {
 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 = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3482: 		    selname[0].selected = true;
 3483: 		}
 3484: 	    }
 3485: 	}	    
 3486:     }
 3487: 
 3488:     function changeSelect(partid,user) {
 3489: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3490: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3491: 	var point  = textbox.value;
 3492: 	var weight = document.classgrade["weight_"+partid].value;
 3493: 
 3494: 	if (isNaN(point) || parseFloat(point) < 0) {
 3495: 	    alert("$alertmsg"+parseFloat(point));
 3496: 	    textbox.value = "";
 3497: 	    return;
 3498: 	}
 3499: 	if (parseFloat(point) > parseFloat(weight)) {
 3500: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3501: 			       ") greater than the weight of the part. Accept?");
 3502: 	    if (resp == false) {
 3503: 		textbox.value = "";
 3504: 		return;
 3505: 	    }
 3506: 	}
 3507: 	selval[0].selected = true;
 3508:     }
 3509: 
 3510:     function changeOneScore(partid,user) {
 3511: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3512: 	if (selval[1].selected || selval[2].selected) {
 3513: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3514: 	    if (selval[2].selected) {
 3515: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3516: 	    }
 3517:         }
 3518:     }
 3519: 
 3520:     function resetEntry(numpart) {
 3521: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3522: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3523: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3524: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3525: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3526: 	    for (var i=0; i<radioButton.length; i++) {
 3527: 		radioButton[i].checked=false;
 3528: 
 3529: 	    }
 3530: 	    textbox.value = "";
 3531: 	    selval[0].selected = true;
 3532: 
 3533: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3534: 		var user = document.classgrade["ctr"+i].value;
 3535: 		user = user.replace(new RegExp(':', 'g'),"_");
 3536: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3537: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3538: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3539: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3540: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3541: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3542: 		if (saveselval == "excused") {
 3543: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3544: 		} else {
 3545: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3546: 		}
 3547: 	    }
 3548: 	}
 3549:     }
 3550: 
 3551: VIEWJAVASCRIPT
 3552: }
 3553: 
 3554: #--- show scores for a section or whole class w/ option to change/update a score
 3555: sub viewgrades {
 3556:     my ($request,$symb) = @_;
 3557:     &viewgrades_js($request);
 3558: 
 3559:     #need to make sure we have the correct data for later EXT calls, 
 3560:     #thus invalidate the cache
 3561:     &Apache::lonnet::devalidatecourseresdata(
 3562:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3563:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3564:     &Apache::lonnet::clear_EXT_cache_status();
 3565: 
 3566:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3567: 
 3568:     #view individual student submission form - called using Javascript viewOneStudent
 3569:     $result.=&jscriptNform($symb);
 3570: 
 3571:     #beginning of class grading form
 3572:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3573:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3574: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3575: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3576: 	&build_section_inputs().
 3577: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3578: 
 3579:     my ($common_header,$specific_header);
 3580:     if ($env{'form.section'} eq 'all') {
 3581: 	$common_header = &mt('Assign Common Grade to Class');
 3582:         $specific_header = &mt('Assign Grade to Specific Students in Class');
 3583:     } elsif ($env{'form.section'} eq 'none') {
 3584:         $common_header = &mt('Assign Common Grade to Students in no Section');
 3585: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
 3586:     } else {
 3587:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3588:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
 3589: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
 3590:     }
 3591:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
 3592:     #radio buttons/text box for assigning points for a section or class.
 3593:     #handles different parts of a problem
 3594:     my $res_error;
 3595:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3596:     if ($res_error) {
 3597:         return &navmap_errormsg();
 3598:     }
 3599:     my %weight = ();
 3600:     my $ctsparts = 0;
 3601:     my %seen = ();
 3602:     my @part_response_id = &flatten_responseType($responseType);
 3603:     foreach my $part_response_id (@part_response_id) {
 3604:     	my ($partid,$respid) = @{ $part_response_id };
 3605: 	my $part_resp = join('_',@{ $part_response_id });
 3606: 	next if $seen{$partid};
 3607: 	$seen{$partid}++;
 3608: 	my $handgrade=$$handgrade{$part_resp};
 3609: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 3610: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 3611: 
 3612: 	my $display_part=&get_display_part($partid,$symb);
 3613: 	my $radio.='<table border="0"><tr>';  
 3614: 	my $ctr = 0;
 3615: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 3616: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 3617: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 3618: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 3619: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 3620: 	    $ctr++;
 3621: 	}
 3622: 	$radio.='</tr></table>';
 3623: 	my $line = '<input type="text" name="TEXTVAL_'.
 3624: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
 3625: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 3626: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 3627:         $line.= '<td><b>'.&mt('Grade Status').':</b>'.
 3628:             '<select name="SELVAL_'.$partid.'" '.
 3629:             'onchange="javascript:writeRadText(\''.$partid.'\','.
 3630:                 $weight{$partid}.')"> '.
 3631: 	    '<option selected="selected"> </option>'.
 3632: 	    '<option value="excused">'.&mt('excused').'</option>'.
 3633: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 3634: 	    '</select></td>'.
 3635:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 3636: 	$line.='<input type="hidden" name="partid_'.
 3637: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 3638: 	$line.='<input type="hidden" name="weight_'.
 3639: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 3640: 
 3641: 	$result.=
 3642: 	    &Apache::loncommon::start_data_table_row()."\n".
 3643: 	    '<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>'.
 3644: 	    &Apache::loncommon::end_data_table_row()."\n";
 3645: 	$ctsparts++;
 3646:     }
 3647:     $result.=&Apache::loncommon::end_data_table()."\n".
 3648: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 3649:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 3650: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
 3651: 
 3652:     #table listing all the students in a section/class
 3653:     #header of table
 3654:     $result.= '<h3>'.$specific_header.'</h3>'.
 3655:               &Apache::loncommon::start_data_table().
 3656: 	      &Apache::loncommon::start_data_table_header_row().
 3657: 	      '<th>'.&mt('No.').'</th>'.
 3658: 	      '<th>'.&nameUserString('header')."</th>\n";
 3659:     my $partserror;
 3660:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3661:     if ($partserror) {
 3662:         return &navmap_errormsg();
 3663:     }
 3664:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 3665:     my @partids = ();
 3666:     foreach my $part (@parts) {
 3667: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3668:         my $narrowtext = &mt('Tries');
 3669: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 3670: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 3671: 	my ($partid) = &split_part_type($part);
 3672:         push(@partids,$partid);
 3673: #
 3674: # FIXME: Looks like $display looks at English text
 3675: #
 3676: 	my $display_part=&get_display_part($partid,$symb);
 3677: 	if ($display =~ /^Partial Credit Factor/) {
 3678: 	    $result.='<th>'.
 3679: 		&mt('Score Part: [_1][_2](weight = [_3])',
 3680: 		    $display_part,'<br />',$weight{$partid}).'</th>'."\n";
 3681: 	    next;
 3682: 	    
 3683: 	} else {
 3684: 	    if ($display =~ /Problem Status/) {
 3685: 		my $grade_status_mt = &mt('Grade Status');
 3686: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 3687: 	    }
 3688: 	    my $part_mt = &mt('Part:');
 3689: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 3690: 	}
 3691: 
 3692: 	$result.='<th>'.$display.'</th>'."\n";
 3693:     }
 3694:     $result.=&Apache::loncommon::end_data_table_header_row();
 3695: 
 3696:     my %last_resets = 
 3697: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 3698: 
 3699:     #get info for each student
 3700:     #list all the students - with points and grade status
 3701:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3702:     my $ctr = 0;
 3703:     foreach (sort 
 3704: 	     {
 3705: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3706: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3707: 		 }
 3708: 		 return $a cmp $b;
 3709: 	     } (keys(%$fullname))) {
 3710: 	$ctr++;
 3711: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 3712: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
 3713:     }
 3714:     $result.=&Apache::loncommon::end_data_table();
 3715:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 3716:     $result.='<input type="button" value="'.&mt('Save').'" '.
 3717: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
 3718:     if (scalar(%$fullname) eq 0) {
 3719: 	my $colspan=3+scalar(@parts);
 3720: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3721:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 3722: 	$result='<span class="LC_warning">'.
 3723: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 3724: 	        $section_display, $stu_status).
 3725: 	    '</span>';
 3726:     }
 3727:     return $result;
 3728: }
 3729: 
 3730: #--- call by previous routine to display each student
 3731: sub viewstudentgrade {
 3732:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 3733:     my ($uname,$udom) = split(/:/,$student);
 3734:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 3735:     my %aggregates = (); 
 3736:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 3737: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
 3738: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
 3739: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 3740: 	'\');" target="_self">'.$fullname.'</a> '.
 3741: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 3742:     $student=~s/:/_/; # colon doen't work in javascript for names
 3743:     foreach my $apart (@$parts) {
 3744: 	my ($part,$type) = &split_part_type($apart);
 3745: 	my $score=$record{"resource.$part.$type"};
 3746:         $result.='<td align="center">';
 3747:         my ($aggtries,$totaltries);
 3748:         unless (exists($aggregates{$part})) {
 3749: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 3750: 
 3751: 	    $aggtries = $totaltries;
 3752:             if ($$last_resets{$part}) {  
 3753:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 3754: 					   $part);
 3755:             }
 3756:             $result.='<input type="hidden" name="'.
 3757:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 3758:             $result.='<input type="hidden" name="'.
 3759:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 3760:             $aggregates{$part} = 1;
 3761:         }
 3762: 	if ($type eq 'awarded') {
 3763: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 3764: 	    $result.='<input type="hidden" name="'.
 3765: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 3766: 	    $result.='<input type="text" name="'.
 3767: 		'GD_'.$student.'_'.$part.'_awarded" '.
 3768:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
 3769: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 3770: 	} elsif ($type eq 'solved') {
 3771: 	    my ($status,$foo)=split(/_/,$score,2);
 3772: 	    $status = 'nothing' if ($status eq '');
 3773: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 3774: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 3775: 	    $result.='&nbsp;<select name="'.
 3776: 		'GD_'.$student.'_'.$part.'_solved" '.
 3777:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 3778: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 3779: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 3780: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 3781: 	    $result.="</select>&nbsp;</td>\n";
 3782: 	} else {
 3783: 	    $result.='<input type="hidden" name="'.
 3784: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 3785: 		    "\n";
 3786: 	    $result.='<input type="text" name="'.
 3787: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 3788: 		'value="'.$score.'" size="4" /></td>'."\n";
 3789: 	}
 3790:     }
 3791:     $result.=&Apache::loncommon::end_data_table_row();
 3792:     return $result;
 3793: }
 3794: 
 3795: #--- change scores for all the students in a section/class
 3796: #    record does not get update if unchanged
 3797: sub editgrades {
 3798:     my ($request,$symb) = @_;
 3799: 
 3800:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3801:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 3802:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
 3803: 
 3804:     my $result= &Apache::loncommon::start_data_table().
 3805: 	&Apache::loncommon::start_data_table_header_row().
 3806: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 3807: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 3808:     my %scoreptr = (
 3809: 		    'correct'  =>'correct_by_override',
 3810: 		    'incorrect'=>'incorrect_by_override',
 3811: 		    'excused'  =>'excused',
 3812: 		    'ungraded' =>'ungraded_attempted',
 3813:                     'credited' =>'credit_attempted',
 3814: 		    'nothing'  => '',
 3815: 		    );
 3816:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 3817: 
 3818:     my (@partid);
 3819:     my %weight = ();
 3820:     my %columns = ();
 3821:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 3822: 
 3823:     my $partserror;
 3824:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3825:     if ($partserror) {
 3826:         return &navmap_errormsg();
 3827:     }
 3828:     my $header;
 3829:     while ($ctr < $env{'form.totalparts'}) {
 3830: 	my $partid = $env{'form.partid_'.$ctr};
 3831: 	push(@partid,$partid);
 3832: 	$weight{$partid} = $env{'form.weight_'.$partid};
 3833: 	$ctr++;
 3834:     }
 3835:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3836:     foreach my $partid (@partid) {
 3837: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 3838: 	    '<th align="center">'.&mt('New Score').'</th>';
 3839: 	$columns{$partid}=2;
 3840: 	foreach my $stores (@parts) {
 3841: 	    my ($part,$type) = &split_part_type($stores);
 3842: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 3843: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 3844: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 3845: 	    $display =~ s/\[Part: \Q$part\E\]//;
 3846:             my $narrowtext = &mt('Tries');
 3847: 	    $display =~ s/Number of Attempts/$narrowtext/;
 3848: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 3849: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 3850: 	    $columns{$partid}+=2;
 3851: 	}
 3852:     }
 3853:     foreach my $partid (@partid) {
 3854: 	my $display_part=&get_display_part($partid,$symb);
 3855: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 3856: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 3857: 	    '</th>';
 3858: 
 3859:     }
 3860:     $result .= &Apache::loncommon::end_data_table_header_row().
 3861: 	&Apache::loncommon::start_data_table_header_row().
 3862: 	$header.
 3863: 	&Apache::loncommon::end_data_table_header_row();
 3864:     my @noupdate;
 3865:     my ($updateCtr,$noupdateCtr) = (1,1);
 3866:     for ($i=0; $i<$env{'form.total'}; $i++) {
 3867: 	my $line;
 3868: 	my $user = $env{'form.ctr'.$i};
 3869: 	my ($uname,$udom)=split(/:/,$user);
 3870: 	my %newrecord;
 3871: 	my $updateflag = 0;
 3872: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 3873: 	my $usec=$classlist->{"$uname:$udom"}[5];
 3874: 	if (!&canmodify($usec)) {
 3875: 	    my $numcols=scalar(@partid)*4+2;
 3876: 	    push(@noupdate,
 3877: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
 3878: 		 &mt('Not allowed to modify student')."</span></td></tr>");
 3879: 	    next;
 3880: 	}
 3881:         my %aggregate = ();
 3882:         my $aggregateflag = 0;
 3883: 	$user=~s/:/_/; # colon doen't work in javascript for names
 3884: 	foreach (@partid) {
 3885: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 3886: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 3887: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 3888: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3889: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 3890: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 3891: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 3892: 	    my $score;
 3893: 	    if ($partial eq '') {
 3894: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3895: 	    } elsif ($partial > 0) {
 3896: 		$score = 'correct_by_override';
 3897: 	    } elsif ($partial == 0) {
 3898: 		$score = 'incorrect_by_override';
 3899: 	    }
 3900: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 3901: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 3902: 
 3903: 	    $newrecord{'resource.'.$_.'.regrader'}=
 3904: 		"$env{'user.name'}:$env{'user.domain'}";
 3905: 	    if ($dropMenu eq 'reset status' &&
 3906: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 3907: 		$newrecord{'resource.'.$_.'.tries'} = '';
 3908: 		$newrecord{'resource.'.$_.'.solved'} = '';
 3909: 		$newrecord{'resource.'.$_.'.award'} = '';
 3910: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 3911: 		$updateflag = 1;
 3912:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 3913:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 3914:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 3915:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 3916:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3917:                     $aggregateflag = 1;
 3918:                 }
 3919: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 3920: 		$updateflag = 1;
 3921: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 3922: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 3923: 		$rec_update++;
 3924: 	    }
 3925: 
 3926: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3927: 		'<td align="center">'.$awarded.
 3928: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 3929: 
 3930: 
 3931: 	    my $partid=$_;
 3932: 	    foreach my $stores (@parts) {
 3933: 		my ($part,$type) = &split_part_type($stores);
 3934: 		if ($part !~ m/^\Q$partid\E/) { next;}
 3935: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 3936: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 3937: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 3938: 		if ($awarded ne '' && $awarded ne $old_aw) {
 3939: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 3940: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3941: 		    $updateflag=1;
 3942: 		}
 3943: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3944: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 3945: 	    }
 3946: 	}
 3947: 	$line.="\n";
 3948: 
 3949: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3950: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3951: 
 3952: 	if ($updateflag) {
 3953: 	    $count++;
 3954: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 3955: 				    $udom,$uname);
 3956: 
 3957: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 3958: 					      $cnum,$udom,$uname)) {
 3959: 		# need to figure out if should be in queue.
 3960: 		my %record =  
 3961: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 3962: 					     $udom,$uname);
 3963: 		my $all_graded = 1;
 3964: 		my $none_graded = 1;
 3965: 		foreach my $part (@parts) {
 3966: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 3967: 			$all_graded = 0;
 3968: 		    } else {
 3969: 			$none_graded = 0;
 3970: 		    }
 3971: 		}
 3972: 
 3973: 		if ($all_graded || $none_graded) {
 3974: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 3975: 							   $symb,$cdom,$cnum,
 3976: 							   $udom,$uname);
 3977: 		}
 3978: 	    }
 3979: 
 3980: 	    $result.=&Apache::loncommon::start_data_table_row().
 3981: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 3982: 		&Apache::loncommon::end_data_table_row();
 3983: 	    $updateCtr++;
 3984: 	} else {
 3985: 	    push(@noupdate,
 3986: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 3987: 	    $noupdateCtr++;
 3988: 	}
 3989:         if ($aggregateflag) {
 3990:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3991: 				  $cdom,$cnum);
 3992:         }
 3993:     }
 3994:     if (@noupdate) {
 3995: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
 3996: 	my $numcols=scalar(@partid)*4+2;
 3997: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 3998: 	    '<td align="center" colspan="'.$numcols.'">'.
 3999: 	    &mt('No Changes Occurred For the Students Below').
 4000: 	    '</td>'.
 4001: 	    &Apache::loncommon::end_data_table_row();
 4002: 	foreach my $line (@noupdate) {
 4003: 	    $result.=
 4004: 		&Apache::loncommon::start_data_table_row().
 4005: 		$line.
 4006: 		&Apache::loncommon::end_data_table_row();
 4007: 	}
 4008:     }
 4009:     $result .= &Apache::loncommon::end_data_table();
 4010:     my $msg = '<p><b>'.
 4011: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 4012: 	    $rec_update,$count).'</b><br />'.
 4013: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 4014: 	'</b></p>';
 4015:     return $title.$msg.$result;
 4016: }
 4017: 
 4018: sub split_part_type {
 4019:     my ($partstr) = @_;
 4020:     my ($temp,@allparts)=split(/_/,$partstr);
 4021:     my $type=pop(@allparts);
 4022:     my $part=join('_',@allparts);
 4023:     return ($part,$type);
 4024: }
 4025: 
 4026: #------------- end of section for handling grading by section/class ---------
 4027: #
 4028: #----------------------------------------------------------------------------
 4029: 
 4030: 
 4031: #----------------------------------------------------------------------------
 4032: #
 4033: #-------------------------- Next few routines handles grading by csv upload
 4034: #
 4035: #--- Javascript to handle csv upload
 4036: sub csvupload_javascript_reverse_associate {
 4037:     my $error1=&mt('You need to specify the username or the student/employee ID');
 4038:     my $error2=&mt('You need to specify at least one grading field');
 4039:   &js_escape(\$error1);
 4040:   &js_escape(\$error2);
 4041:   return(<<ENDPICK);
 4042:   function verify(vf) {
 4043:     var foundsomething=0;
 4044:     var founduname=0;
 4045:     var foundID=0;
 4046:     for (i=0;i<=vf.nfields.value;i++) {
 4047:       tw=eval('vf.f'+i+'.selectedIndex');
 4048:       if (i==0 && tw!=0) { foundID=1; }
 4049:       if (i==1 && tw!=0) { founduname=1; }
 4050:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 4051:     }
 4052:     if (founduname==0 && foundID==0) {
 4053: 	alert('$error1');
 4054: 	return;
 4055:     }
 4056:     if (foundsomething==0) {
 4057: 	alert('$error2');
 4058: 	return;
 4059:     }
 4060:     vf.submit();
 4061:   }
 4062:   function flip(vf,tf) {
 4063:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4064:     var i;
 4065:     for (i=0;i<=vf.nfields.value;i++) {
 4066:       //can not pick the same destination field for both name and domain
 4067:       if (((i ==0)||(i ==1)) && 
 4068:           ((tf==0)||(tf==1)) && 
 4069:           (i!=tf) &&
 4070:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4071:         eval('vf.f'+i+'.selectedIndex=0;')
 4072:       }
 4073:     }
 4074:   }
 4075: ENDPICK
 4076: }
 4077: 
 4078: sub csvupload_javascript_forward_associate {
 4079:     my $error1=&mt('You need to specify the username or the student/employee ID');
 4080:     my $error2=&mt('You need to specify at least one grading field');
 4081:   &js_escape(\$error1);
 4082:   &js_escape(\$error2);
 4083:   return(<<ENDPICK);
 4084:   function verify(vf) {
 4085:     var foundsomething=0;
 4086:     var founduname=0;
 4087:     var foundID=0;
 4088:     for (i=0;i<=vf.nfields.value;i++) {
 4089:       tw=eval('vf.f'+i+'.selectedIndex');
 4090:       if (tw==1) { foundID=1; }
 4091:       if (tw==2) { founduname=1; }
 4092:       if (tw>3) { foundsomething=1; }
 4093:     }
 4094:     if (founduname==0 && foundID==0) {
 4095: 	alert('$error1');
 4096: 	return;
 4097:     }
 4098:     if (foundsomething==0) {
 4099: 	alert('$error2');
 4100: 	return;
 4101:     }
 4102:     vf.submit();
 4103:   }
 4104:   function flip(vf,tf) {
 4105:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4106:     var i;
 4107:     //can not pick the same destination field twice
 4108:     for (i=0;i<=vf.nfields.value;i++) {
 4109:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4110:         eval('vf.f'+i+'.selectedIndex=0;')
 4111:       }
 4112:     }
 4113:   }
 4114: ENDPICK
 4115: }
 4116: 
 4117: sub csvuploadmap_header {
 4118:     my ($request,$symb,$datatoken,$distotal)= @_;
 4119:     my $javascript;
 4120:     if ($env{'form.upfile_associate'} eq 'reverse') {
 4121: 	$javascript=&csvupload_javascript_reverse_associate();
 4122:     } else {
 4123: 	$javascript=&csvupload_javascript_forward_associate();
 4124:     }
 4125: 
 4126:     $symb = &Apache::lonenc::check_encrypt($symb);
 4127:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
 4128:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
 4129:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
 4130:     my $reverse=&mt("Reverse Association");
 4131:     $request->print(<<ENDPICK);
 4132: <br />
 4133: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 4134: <input type="hidden" name="associate"  value="" />
 4135: <input type="hidden" name="phase"      value="three" />
 4136: <input type="hidden" name="datatoken"  value="$datatoken" />
 4137: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 4138: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 4139: <input type="hidden" name="upfile_associate" 
 4140:                                        value="$env{'form.upfile_associate'}" />
 4141: <input type="hidden" name="symb"       value="$symb" />
 4142: <input type="hidden" name="command"    value="csvuploadoptions" />
 4143: <hr />
 4144: ENDPICK
 4145:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
 4146:     return '';
 4147: 
 4148: }
 4149: 
 4150: sub csvupload_fields {
 4151:     my ($symb,$errorref) = @_;
 4152:     my (@parts) = &getpartlist($symb,$errorref);
 4153:     if (ref($errorref)) {
 4154:         if ($$errorref) {
 4155:             return;
 4156:         }
 4157:     }
 4158: 
 4159:     my @fields=(['ID','Student/Employee ID'],
 4160:                 ['clicker','Clicker ID'],
 4161: 		['username','Student Username'],
 4162: 		['domain','Student Domain']);
 4163:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 4164:     foreach my $part (sort(@parts)) {
 4165: 	my @datum;
 4166: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 4167: 	my $name=$part;
 4168: 	if  (!$display) { $display = $name; }
 4169: 	@datum=($name,$display);
 4170: 	if ($name=~/^stores_(.*)_awarded/) {
 4171: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 4172: 	}
 4173: 	push(@fields,\@datum);
 4174:     }
 4175:     return (@fields);
 4176: }
 4177: 
 4178: sub csvuploadmap_footer {
 4179:     my ($request,$i,$keyfields) =@_;
 4180:     my $buttontext = &mt('Assign Grades');
 4181:     $request->print(<<ENDPICK);
 4182: </table>
 4183: <input type="hidden" name="nfields" value="$i" />
 4184: <input type="hidden" name="keyfields" value="$keyfields" />
 4185: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
 4186: </form>
 4187: ENDPICK
 4188: }
 4189: 
 4190: sub checkforfile_js {
 4191:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 4192:     &js_escape(\$alertmsg);
 4193:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
 4194:     function checkUpload(formname) {
 4195: 	if (formname.upfile.value == "") {
 4196: 	    alert("$alertmsg");
 4197: 	    return false;
 4198: 	}
 4199: 	formname.submit();
 4200:     }
 4201: CSVFORMJS
 4202:     return $result;
 4203: }
 4204: 
 4205: sub upcsvScores_form {
 4206:     my ($request,$symb) = @_;
 4207:     if (!$symb) {return '';}
 4208:     my $result=&checkforfile_js();
 4209:     $result.=&Apache::loncommon::start_data_table().
 4210:              &Apache::loncommon::start_data_table_header_row().
 4211:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
 4212:              &Apache::loncommon::end_data_table_header_row().
 4213:              &Apache::loncommon::start_data_table_row().'<td>';
 4214:     my $upload=&mt("Upload Scores");
 4215:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 4216:     my $ignore=&mt('Ignore First Line');
 4217:     $symb = &Apache::lonenc::check_encrypt($symb);
 4218:     $result.=<<ENDUPFORM;
 4219: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4220: <input type="hidden" name="symb" value="$symb" />
 4221: <input type="hidden" name="command" value="csvuploadmap" />
 4222: $upfile_select
 4223: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 4224: </form>
 4225: ENDUPFORM
 4226:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 4227:                            &mt("How do I create a CSV file from a spreadsheet")).
 4228:              '</td>'.
 4229:             &Apache::loncommon::end_data_table_row().
 4230:             &Apache::loncommon::end_data_table();
 4231:     return $result;
 4232: }
 4233: 
 4234: 
 4235: sub csvuploadmap {
 4236:     my ($request,$symb)= @_;
 4237:     if (!$symb) {return '';}
 4238: 
 4239:     my $datatoken;
 4240:     if (!$env{'form.datatoken'}) {
 4241: 	$datatoken=&Apache::loncommon::upfile_store($request);
 4242:     } else {
 4243: 	$datatoken=$env{'form.datatoken'};
 4244: 	&Apache::loncommon::load_tmp_file($request);
 4245:     }
 4246:     my @records=&Apache::loncommon::upfile_record_sep();
 4247:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 4248:     my ($i,$keyfields);
 4249:     if (@records) {
 4250:         my $fieldserror;
 4251: 	my @fields=&csvupload_fields($symb,\$fieldserror);
 4252:         if ($fieldserror) {
 4253:             $request->print(&navmap_errormsg());
 4254:             return;
 4255:         }
 4256: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 4257: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 4258: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 4259: 							  \@fields);
 4260: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 4261: 	    chop($keyfields);
 4262: 	} else {
 4263: 	    unshift(@fields,['none','']);
 4264: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 4265: 							    \@fields);
 4266:             foreach my $rec (@records) {
 4267:                 my %temp = &Apache::loncommon::record_sep($rec);
 4268:                 if (%temp) {
 4269:                     $keyfields=join(',',sort(keys(%temp)));
 4270:                     last;
 4271:                 }
 4272:             }
 4273: 	}
 4274:     }
 4275:     &csvuploadmap_footer($request,$i,$keyfields);
 4276: 
 4277:     return '';
 4278: }
 4279: 
 4280: sub csvuploadoptions {
 4281:     my ($request,$symb)= @_;
 4282:     my $overwrite=&mt('Overwrite any existing score');
 4283:     $request->print(<<ENDPICK);
 4284: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4285: <input type="hidden" name="command"    value="csvuploadassign" />
 4286: <p>
 4287: <label>
 4288:    <input type="checkbox" name="overwite_scores" checked="checked" />
 4289:    $overwrite
 4290: </label>
 4291: </p>
 4292: ENDPICK
 4293:     my %fields=&get_fields();
 4294:     if (!defined($fields{'domain'})) {
 4295: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 4296: 	$request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
 4297:     }
 4298:     foreach my $key (sort(keys(%env))) {
 4299: 	if ($key !~ /^form\.(.*)$/) { next; }
 4300: 	my $cleankey=$1;
 4301: 	if ($cleankey eq 'command') { next; }
 4302: 	$request->print('<input type="hidden" name="'.$cleankey.
 4303: 			'"  value="'.$env{$key}.'" />'."\n");
 4304:     }
 4305:     # FIXME do a check for any duplicated user ids...
 4306:     # FIXME do a check for any invalid user ids?...
 4307:     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
 4308: <hr /></form>'."\n");
 4309:     return '';
 4310: }
 4311: 
 4312: sub get_fields {
 4313:     my %fields;
 4314:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 4315:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 4316: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 4317: 	    if ($env{'form.f'.$i} ne 'none') {
 4318: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 4319: 	    }
 4320: 	} else {
 4321: 	    if ($env{'form.f'.$i} ne 'none') {
 4322: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 4323: 	    }
 4324: 	}
 4325:     }
 4326:     return %fields;
 4327: }
 4328: 
 4329: sub csvuploadassign {
 4330:     my ($request,$symb)= @_;
 4331:     if (!$symb) {return '';}
 4332:     my $error_msg = '';
 4333:     &Apache::loncommon::load_tmp_file($request);
 4334:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 4335:     my %fields=&get_fields();
 4336:     my $courseid=$env{'request.course.id'};
 4337:     my ($classlist) = &getclasslist('all',0);
 4338:     my @notallowed;
 4339:     my @skipped;
 4340:     my @warnings;
 4341:     my $countdone=0;
 4342:     foreach my $grade (@gradedata) {
 4343: 	my %entries=&Apache::loncommon::record_sep($grade);
 4344: 	my $domain;
 4345: 	if ($entries{$fields{'domain'}}) {
 4346: 	    $domain=$entries{$fields{'domain'}};
 4347: 	} else {
 4348: 	    $domain=$env{'form.default_domain'};
 4349: 	}
 4350: 	$domain=~s/\s//g;
 4351: 	my $username=$entries{$fields{'username'}};
 4352: 	$username=~s/\s//g;
 4353: 	if (!$username) {
 4354: 	    my $id=$entries{$fields{'ID'}};
 4355: 	    $id=~s/\s//g;
 4356:             if ($id ne '') {
 4357: 	        my %ids=&Apache::lonnet::idget($domain,[$id]);
 4358: 	        $username=$ids{$id};
 4359:             } else {
 4360:                 if ($entries{$fields{'clicker'}}) {
 4361:                     my $clicker = $entries{$fields{'clicker'}};
 4362:                     $clicker=~s/\s//g;
 4363:                     if ($clicker ne '') {
 4364:                         my %clickers = &Apache::lonnet::idget($domain,[$clicker],'clickers');
 4365:                         if ($clickers{$clicker} ne '') {  
 4366:                             my $match = 0;
 4367:                             my @inclass;
 4368:                             foreach my $poss (split(/,/,$clickers{$clicker})) {
 4369:                                 if (exists($$classlist{"$poss:$domain"})) {
 4370:                                     $username = $poss;
 4371:                                     push(@inclass,$poss);
 4372:                                     $match ++;
 4373:                                     
 4374:                                 }
 4375:                             }
 4376:                             if ($match > 1) {
 4377:                                 undef($username); 
 4378:                                 $request->print('<p class="LC_warning">'.
 4379:                                                 &mt('Score not saved for clicker: [_1] (matched multiple usernames: [_2])',
 4380:                                                 $clicker,join(', ',@inclass)).'</p>');
 4381:                             }
 4382:                         }
 4383:                     }
 4384:                 }
 4385:             }
 4386: 	}
 4387: 	if (!exists($$classlist{"$username:$domain"})) {
 4388: 	    my $id=$entries{$fields{'ID'}};
 4389: 	    $id=~s/\s//g;
 4390:             my $clicker = $entries{$fields{'clicker'}};
 4391:             $clicker=~s/\s//g;
 4392:             if ($clicker) {
 4393:                 push(@skipped,"$clicker:$domain");
 4394: 	    } elsif ($id) {
 4395: 		push(@skipped,"$id:$domain");
 4396: 	    } else {
 4397: 		push(@skipped,"$username:$domain");
 4398: 	    }
 4399: 	    next;
 4400: 	}
 4401: 	my $usec=$classlist->{"$username:$domain"}[5];
 4402: 	if (!&canmodify($usec)) {
 4403: 	    push(@notallowed,"$username:$domain");
 4404: 	    next;
 4405: 	}
 4406: 	my %points;
 4407: 	my %grades;
 4408: 	foreach my $dest (keys(%fields)) {
 4409: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 4410: 		$dest eq 'domain') { next; }
 4411: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 4412: 	    if ($dest=~/stores_(.*)_points/) {
 4413: 		my $part=$1;
 4414: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 4415: 					      $symb,$domain,$username);
 4416:                 if ($wgt) {
 4417:                     $entries{$fields{$dest}}=~s/\s//g;
 4418:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 4419:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 4420:                                           : 'correct_by_override';
 4421:                     if ($pcr>1) {
 4422:                        push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
 4423:                     }
 4424:                     $grades{"resource.$part.awarded"}=$pcr;
 4425:                     $grades{"resource.$part.solved"}=$award;
 4426:                     $points{$part}=1;
 4427:                 } else {
 4428:                     $error_msg = "<br />" .
 4429:                         &mt("Some point values were assigned"
 4430:                             ." for problems with a weight "
 4431:                             ."of zero. These values were "
 4432:                             ."ignored.");
 4433:                 }
 4434: 	    } else {
 4435: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 4436: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 4437: 		my $store_key=$dest;
 4438: 		$store_key=~s/^stores/resource/;
 4439: 		$store_key=~s/_/\./g;
 4440: 		$grades{$store_key}=$entries{$fields{$dest}};
 4441: 	    }
 4442: 	}
 4443: 	if (! %grades) { 
 4444:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 4445:         } else {
 4446: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 4447: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 4448: 					   $env{'request.course.id'},
 4449: 					   $domain,$username);
 4450: 	   if ($result eq 'ok') {
 4451: # Successfully stored
 4452: 	      $request->print('.');
 4453: # Remove from grading queue
 4454:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
 4455:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
 4456:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
 4457:                                              $domain,$username);
 4458:               $countdone++;
 4459:            } else {
 4460: 	      $request->print("<p><span class=\"LC_error\">".
 4461:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 4462:                                   "$username:$domain",$result)."</span></p>");
 4463: 	   }
 4464: 	   $request->rflush();
 4465:         }
 4466:     }
 4467:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
 4468:     if (@warnings) {
 4469:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
 4470:         $request->print(join(', ',@warnings));
 4471:     }
 4472:     if (@skipped) {
 4473: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
 4474:         $request->print(join(', ',@skipped));
 4475:     }
 4476:     if (@notallowed) {
 4477: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
 4478: 	$request->print(join(', ',@notallowed));
 4479:     }
 4480:     $request->print("<br />\n");
 4481:     return $error_msg;
 4482: }
 4483: #------------- end of section for handling csv file upload ---------
 4484: #
 4485: #-------------------------------------------------------------------
 4486: #
 4487: #-------------- Next few routines handle grading by page/sequence
 4488: #
 4489: #--- Select a page/sequence and a student to grade
 4490: sub pickStudentPage {
 4491:     my ($request,$symb) = @_;
 4492: 
 4493:     my $alertmsg = &mt('Please select the student you wish to grade.');
 4494:     &js_escape(\$alertmsg);
 4495:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
 4496: 
 4497: function checkPickOne(formname) {
 4498:     if (radioSelection(formname.student) == null) {
 4499: 	alert("$alertmsg");
 4500: 	return;
 4501:     }
 4502:     ptr = pullDownSelection(formname.selectpage);
 4503:     formname.page.value = formname["page"+ptr].value;
 4504:     formname.title.value = formname["title"+ptr].value;
 4505:     formname.submit();
 4506: }
 4507: 
 4508: LISTJAVASCRIPT
 4509:     &commonJSfunctions($request);
 4510: 
 4511:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4512:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4513:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4514: 
 4515:     my $result='<h3><span class="LC_info">&nbsp;'.
 4516: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 4517: 
 4518:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 4519:     my $map_error;
 4520:     my ($titles,$symbx) = &getSymbMap($map_error);
 4521:     if ($map_error) {
 4522:         $request->print(&navmap_errormsg());
 4523:         return; 
 4524:     }
 4525:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 4526: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 4527: #    my $type=($curpage =~ /\.(page|sequence)/);
 4528: 
 4529:     # Collection of hidden fields
 4530:     my $ctr=0;
 4531:     foreach (@$titles) {
 4532:         my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4533:         $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 4534:         $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 4535:         $ctr++;
 4536:     }
 4537:     $result.='<input type="hidden" name="page" />'."\n".
 4538:         '<input type="hidden" name="title" />'."\n";
 4539: 
 4540:     $result.=&build_section_inputs();
 4541:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4542:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 4543: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 4544: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 4545: 
 4546:     # Show grading options
 4547:     $result.=&Apache::lonhtmlcommon::start_pick_box();
 4548:     my $select = '<select name="selectpage">'."\n";
 4549:     $ctr=0;
 4550:     foreach (@$titles) {
 4551: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4552: 	$select.='<option value="'.$ctr.'"'.
 4553: 	    ($$symbx{$_} =~ /$curpage$/ ? ' selected="selected"' : '').
 4554: 	    '>'.$showtitle.'</option>'."\n";
 4555: 	$ctr++;
 4556:     }
 4557:     $select.= '</select>';
 4558: 
 4559:     $result.=
 4560:         &Apache::lonhtmlcommon::row_title(&mt('Problems from'))
 4561:        .$select
 4562:        .&Apache::lonhtmlcommon::row_closure();
 4563: 
 4564:     $result.=
 4565:         &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
 4566:        .'<label><input type="radio" name="vProb" value="no"'
 4567:            .' checked="checked" /> '.&mt('no').' </label>'."\n"
 4568:        .'<label><input type="radio" name="vProb" value="yes" />'
 4569:            .&mt('yes').'</label>'."\n"
 4570:        .&Apache::lonhtmlcommon::row_closure();
 4571: 
 4572:     $result.=
 4573:         &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
 4574:        .'<label><input type="radio" name="lastSub" value="none" /> '
 4575:            .&mt('none').' </label>'."\n"
 4576:        .'<label><input type="radio" name="lastSub" value="datesub"'
 4577:            .' checked="checked" /> '.&mt('all submissions').'</label>'."\n"
 4578:        .'<label><input type="radio" name="lastSub" value="all" /> '
 4579:            .&mt('all submissions with details').' </label>'
 4580:        .&Apache::lonhtmlcommon::row_closure();
 4581:     
 4582:     $result.=
 4583:         &Apache::lonhtmlcommon::row_title(&mt('Use CODE'))
 4584:        .'<input type="text" name="CODE" value="" />'
 4585:        .&Apache::lonhtmlcommon::row_closure(1)
 4586:        .&Apache::lonhtmlcommon::end_pick_box();
 4587: 
 4588:     # Show list of students to select for grading
 4589:     $result.='<br /><input type="button" '.
 4590:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 4591: 
 4592:     $request->print($result);
 4593: 
 4594:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 4595: 	&Apache::loncommon::start_data_table().
 4596: 	&Apache::loncommon::start_data_table_header_row().
 4597: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4598: 	'<th>'.&nameUserString('header').'</th>'.
 4599: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4600: 	'<th>'.&nameUserString('header').'</th>'.
 4601: 	&Apache::loncommon::end_data_table_header_row();
 4602:  
 4603:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 4604:     my $ptr = 1;
 4605:     foreach my $student (sort 
 4606: 			 {
 4607: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4608: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4609: 			     }
 4610: 			     return $a cmp $b;
 4611: 			 } (keys(%$fullname))) {
 4612: 	my ($uname,$udom) = split(/:/,$student);
 4613: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 4614:                                   : '</td>');
 4615: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 4616: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 4617: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 4618: 	$studentTable.=
 4619: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 4620:                          : '');
 4621: 	$ptr++;
 4622:     }
 4623:     if ($ptr%2 == 0) {
 4624: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 4625: 	    &Apache::loncommon::end_data_table_row();
 4626:     }
 4627:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 4628:     $studentTable.='<input type="button" '.
 4629:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 4630: 
 4631:     $request->print($studentTable);
 4632: 
 4633:     return '';
 4634: }
 4635: 
 4636: sub getSymbMap {
 4637:     my ($map_error) = @_;
 4638:     my $navmap = Apache::lonnavmaps::navmap->new();
 4639:     unless (ref($navmap)) {
 4640:         if (ref($map_error)) {
 4641:             $$map_error = 'navmap';
 4642:         }
 4643:         return;
 4644:     }
 4645:     my %symbx = ();
 4646:     my @titles = ();
 4647:     my $minder = 0;
 4648: 
 4649:     # Gather every sequence that has problems.
 4650:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 4651: 					       1,0,1);
 4652:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 4653: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 4654: 	    my $title = $minder.'.'.
 4655: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 4656: 	    push(@titles, $title); # minder in case two titles are identical
 4657: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 4658: 	    $minder++;
 4659: 	}
 4660:     }
 4661:     return \@titles,\%symbx;
 4662: }
 4663: 
 4664: #
 4665: #--- Displays a page/sequence w/wo problems, w/wo submissions
 4666: sub displayPage {
 4667:     my ($request,$symb) = @_;
 4668:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4669:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4670:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4671:     my $pageTitle = $env{'form.page'};
 4672:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4673:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4674:     my $usec=$classlist->{$env{'form.student'}}[5];
 4675: 
 4676:     #need to make sure we have the correct data for later EXT calls, 
 4677:     #thus invalidate the cache
 4678:     &Apache::lonnet::devalidatecourseresdata(
 4679:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 4680:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 4681:     &Apache::lonnet::clear_EXT_cache_status();
 4682: 
 4683:     if (!&canview($usec)) {
 4684:         $request->print(
 4685:             '<span class="LC_warning">'.
 4686:             &mt('Unable to view requested student. ([_1])',
 4687:                     $env{'form.student'}).
 4688:             '</span>');
 4689:         return;
 4690:     }
 4691:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4692:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 4693: 	'</h3>'."\n";
 4694:     $env{'form.CODE'} = uc($env{'form.CODE'});
 4695:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 4696: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 4697:     } else {
 4698: 	delete($env{'form.CODE'});
 4699:     }
 4700:     &sub_page_js($request);
 4701:     $request->print($result);
 4702: 
 4703:     my $navmap = Apache::lonnavmaps::navmap->new();
 4704:     unless (ref($navmap)) {
 4705:         $request->print(&navmap_errormsg());
 4706:         return;
 4707:     }
 4708:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 4709:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4710:     if (!$map) {
 4711: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 4712: 	return; 
 4713:     }
 4714:     my $iterator = $navmap->getIterator($map->map_start(),
 4715: 					$map->map_finish());
 4716: 
 4717:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 4718: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 4719: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 4720: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 4721: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 4722: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 4723: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4724: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
 4725: 
 4726:     if (defined($env{'form.CODE'})) {
 4727: 	$studentTable.=
 4728: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 4729:     }
 4730:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 4731: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 4732: 
 4733:     $studentTable.='&nbsp;<span class="LC_info">'.
 4734:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
 4735:         '</span>'."\n".
 4736: 	&Apache::loncommon::start_data_table().
 4737: 	&Apache::loncommon::start_data_table_header_row().
 4738: 	'<th>'.&mt('Prob.').'</th>'.
 4739: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 4740: 	&Apache::loncommon::end_data_table_header_row();
 4741: 
 4742:     &Apache::lonxml::clear_problem_counter();
 4743:     my ($depth,$question,$prob) = (1,1,1);
 4744:     $iterator->next(); # skip the first BEGIN_MAP
 4745:     my $curRes = $iterator->next(); # for "current resource"
 4746:     while ($depth > 0) {
 4747:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4748:         if($curRes == $iterator->END_MAP) { $depth--; }
 4749: 
 4750:         if (ref($curRes) && $curRes->is_problem()) {
 4751: 	    my $parts = $curRes->parts();
 4752:             my $title = $curRes->compTitle();
 4753: 	    my $symbx = $curRes->symb();
 4754: 	    $studentTable.=
 4755: 		&Apache::loncommon::start_data_table_row().
 4756: 		'<td align="center" valign="top" >'.$prob.
 4757: 		(scalar(@{$parts}) == 1 ? '' 
 4758: 		                        : '<br />('.&mt('[_1]parts',
 4759: 							scalar(@{$parts}).'&nbsp;').')'
 4760: 		 ).
 4761: 		 '</td>';
 4762: 	    $studentTable.='<td valign="top">';
 4763: 	    my %form = ('CODE' => $env{'form.CODE'},);
 4764: 	    if ($env{'form.vProb'} eq 'yes' ) {
 4765: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 4766: 					     undef,'both',\%form);
 4767: 	    } else {
 4768: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 4769: 		$companswer =~ s|<form(.*?)>||g;
 4770: 		$companswer =~ s|</form>||g;
 4771: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 4772: #		    $companswer =~ s/$1/ /ms;
 4773: #		    $request->print('match='.$1."<br />\n");
 4774: #		}
 4775: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 4776: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 4777: 	    }
 4778: 
 4779: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 4780: 
 4781: 	    if ($env{'form.lastSub'} eq 'datesub') {
 4782: 		if ($record{'version'} eq '') {
 4783: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
 4784: 		} else {
 4785: 		    my %responseType = ();
 4786: 		    foreach my $partid (@{$parts}) {
 4787: 			my @responseIds =$curRes->responseIds($partid);
 4788: 			my @responseType =$curRes->responseType($partid);
 4789: 			my %responseIds;
 4790: 			for (my $i=0;$i<=$#responseIds;$i++) {
 4791: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 4792: 			}
 4793: 			$responseType{$partid} = \%responseIds;
 4794: 		    }
 4795: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 4796: 
 4797: 		}
 4798: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 4799: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 4800:                 my $identifier = (&canmodify($usec)? $prob : ''); 
 4801: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 4802: 									$env{'request.course.id'},
 4803: 									'','.submission',undef,
 4804:                                                                         $usec,$identifier);
 4805:  
 4806: 	    }
 4807: 	    if (&canmodify($usec)) {
 4808:             $studentTable.=&gradeBox_start();
 4809: 		foreach my $partid (@{$parts}) {
 4810: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 4811: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 4812: 		    $question++;
 4813: 		}
 4814:             $studentTable.=&gradeBox_end();
 4815: 		$prob++;
 4816: 	    }
 4817: 	    $studentTable.='</td></tr>';
 4818: 
 4819: 	}
 4820:         $curRes = $iterator->next();
 4821:     }
 4822: 
 4823:     $studentTable.=
 4824:         '</table>'."\n".
 4825:         '<input type="button" value="'.&mt('Save').'" '.
 4826:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 4827:         '</form>'."\n";
 4828:     $request->print($studentTable);
 4829: 
 4830:     return '';
 4831: }
 4832: 
 4833: sub displaySubByDates {
 4834:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 4835:     my $isCODE=0;
 4836:     my $isTask = ($symb =~/\.task$/);
 4837:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 4838:     my $studentTable=&Apache::loncommon::start_data_table().
 4839: 	&Apache::loncommon::start_data_table_header_row().
 4840: 	'<th>'.&mt('Date/Time').'</th>'.
 4841: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 4842:         ($isTask?'<th>'.&mt('Version').'</th>':'').
 4843: 	'<th>'.&mt('Submission').'</th>'.
 4844: 	'<th>'.&mt('Status').'</th>'.
 4845: 	&Apache::loncommon::end_data_table_header_row();
 4846:     my ($version);
 4847:     my %mark;
 4848:     my %orders;
 4849:     $mark{'correct_by_student'} = $checkIcon;
 4850:     if (!exists($$record{'1:timestamp'})) {
 4851: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 4852:     }
 4853: 
 4854:     my $interaction;
 4855:     my $no_increment = 1;
 4856:     my (%lastrndseed,%lasttype);
 4857:     for ($version=1;$version<=$$record{'version'};$version++) {
 4858: 	my $timestamp = 
 4859: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 4860: 	if (exists($$record{$version.':resource.0.version'})) {
 4861: 	    $interaction = $$record{$version.':resource.0.version'};
 4862: 	}
 4863:         if ($isTask && $env{'form.previousversion'}) {
 4864:             next unless ($interaction == $env{'form.previousversion'});
 4865:         }
 4866: 	my $where = ($isTask ? "$version:resource.$interaction"
 4867: 		             : "$version:resource");
 4868: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 4869: 	    '<td>'.$timestamp.'</td>';
 4870: 	if ($isCODE) {
 4871: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 4872: 	}
 4873:         if ($isTask) {
 4874:             $studentTable.='<td>'.$interaction.'</td>';
 4875:         }
 4876: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 4877: 	my @displaySub = ();
 4878: 	foreach my $partid (@{$parts}) {
 4879:             my ($hidden,$type);
 4880:             $type = $$record{$version.':resource.'.$partid.'.type'};
 4881:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
 4882:                 $hidden = 1;
 4883:             }
 4884: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
 4885: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 4886: 	    
 4887: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 4888: 	    my $display_part=&get_display_part($partid,$symb);
 4889: 	    foreach my $matchKey (@matchKey) {
 4890: 		if (exists($$record{$version.':'.$matchKey}) &&
 4891: 		    $$record{$version.':'.$matchKey} ne '') {
 4892:                     
 4893: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 4894: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 4895:                     $displaySub[0].='<span class="LC_nobreak">';
 4896:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
 4897:                                    .' <span class="LC_internal_info">'
 4898:                                    .'('.&mt('Response ID: [_1]',$responseId).')'
 4899:                                    .'</span>'
 4900:                                    .' <b>';
 4901:                     if ($hidden) {
 4902:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
 4903:                     } else {
 4904:                         my ($trial,$rndseed,$newvariation);
 4905:                         if ($type eq 'randomizetry') {
 4906:                             $trial = $$record{"$where.$partid.tries"};
 4907:                             $rndseed = $$record{"$where.$partid.rndseed"};
 4908:                         }
 4909: 		        if ($$record{"$where.$partid.tries"} eq '') {
 4910: 			    $displaySub[0].=&mt('Trial not counted');
 4911: 		        } else {
 4912: 			    $displaySub[0].=&mt('Trial: [_1]',
 4913: 					    $$record{"$where.$partid.tries"});
 4914:                             if (($rndseed ne '') && ($lastrndseed{$partid} ne '')) {
 4915:                                 if (($rndseed ne $lastrndseed{$partid}) &&
 4916:                                     (($type eq 'randomizetry') || ($lasttype{$partid} eq 'randomizetry'))) {
 4917:                                     $newvariation = '&nbsp;('.&mt('New variation this try').')';
 4918:                                 }
 4919:                             }
 4920:                             $lastrndseed{$partid} = $rndseed;
 4921:                             $lasttype{$partid} = $type;
 4922: 		        }
 4923: 		        my $responseType=($isTask ? 'Task'
 4924:                                               : $responseType->{$partid}->{$responseId});
 4925: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
 4926: 		        if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
 4927: 			    $orders{$partid}->{$responseId}=
 4928: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
 4929:                                            $no_increment,$type,$trial,$rndseed);
 4930: 		        }
 4931: 		        $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
 4932: 		        $displaySub[0].='&nbsp; '.
 4933: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
 4934:                     }
 4935: 		}
 4936: 	    }
 4937: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 4938: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 4939: 				    $$record{"$where.$partid.checkedin"},
 4940: 				    $$record{"$where.$partid.checkedin.slot"}).
 4941: 					'<br />';
 4942: 	    }
 4943: 	    if (exists $$record{"$where.$partid.award"}) {
 4944: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 4945: 		    lc($$record{"$where.$partid.award"}).' '.
 4946: 		    $mark{$$record{"$where.$partid.solved"}}.
 4947: 		    '<br />';
 4948: 	    }
 4949: 	    if (exists $$record{"$where.$partid.regrader"}) {
 4950: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 4951: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4952: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 4953: 		$displaySub[2].=
 4954: 		    $$record{"$version:resource.$partid.regrader"}.
 4955: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4956: 	    }
 4957: 	}
 4958: 	# needed because old essay regrader has not parts info
 4959: 	if (exists $$record{"$version:resource.regrader"}) {
 4960: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 4961: 	}
 4962: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 4963: 	if ($displaySub[2]) {
 4964: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 4965: 	}
 4966: 	$studentTable.='&nbsp;</td>'.
 4967: 	    &Apache::loncommon::end_data_table_row();
 4968:     }
 4969:     $studentTable.=&Apache::loncommon::end_data_table();
 4970:     return $studentTable;
 4971: }
 4972: 
 4973: sub updateGradeByPage {
 4974:     my ($request,$symb) = @_;
 4975: 
 4976:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4977:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4978:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4979:     my $pageTitle = $env{'form.page'};
 4980:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4981:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4982:     my $usec=$classlist->{$env{'form.student'}}[5];
 4983:     if (!&canmodify($usec)) {
 4984: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 4985: 	return;
 4986:     }
 4987:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4988:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 4989: 	'</h3>'."\n";
 4990: 
 4991:     $request->print($result);
 4992: 
 4993: 
 4994:     my $navmap = Apache::lonnavmaps::navmap->new();
 4995:     unless (ref($navmap)) {
 4996:         $request->print(&navmap_errormsg());
 4997:         return;
 4998:     }
 4999:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 5000:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 5001:     if (!$map) {
 5002: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 5003: 	return; 
 5004:     }
 5005:     my $iterator = $navmap->getIterator($map->map_start(),
 5006: 					$map->map_finish());
 5007: 
 5008:     my $studentTable=
 5009: 	&Apache::loncommon::start_data_table().
 5010: 	&Apache::loncommon::start_data_table_header_row().
 5011: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 5012: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 5013: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 5014: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 5015: 	&Apache::loncommon::end_data_table_header_row();
 5016: 
 5017:     $iterator->next(); # skip the first BEGIN_MAP
 5018:     my $curRes = $iterator->next(); # for "current resource"
 5019:     my ($depth,$question,$prob,$changeflag,$hideflag)= (1,1,1,0,0);
 5020:     while ($depth > 0) {
 5021:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 5022:         if($curRes == $iterator->END_MAP) { $depth--; }
 5023: 
 5024:         if (ref($curRes) && $curRes->is_problem()) {
 5025: 	    my $parts = $curRes->parts();
 5026:             my $title = $curRes->compTitle();
 5027: 	    my $symbx = $curRes->symb();
 5028: 	    $studentTable.=
 5029: 		&Apache::loncommon::start_data_table_row().
 5030: 		'<td align="center" valign="top" >'.$prob.
 5031: 		(scalar(@{$parts}) == 1 ? '' 
 5032:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
 5033: 		.')').'</td>';
 5034: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 5035: 
 5036: 	    my %newrecord=();
 5037: 	    my @displayPts=();
 5038:             my %aggregate = ();
 5039:             my $aggregateflag = 0;
 5040:             if ($env{'form.HIDE'.$prob}) {
 5041:                 my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 5042:                 my ($version,$parts) = split(/:/,$env{'form.HIDE'.$prob},2);
 5043:                 my $numchgs = &makehidden($version,$parts,\%record,$symbx,$udom,$uname,1);
 5044:                 $hideflag += $numchgs;
 5045:             }
 5046: 	    foreach my $partid (@{$parts}) {
 5047: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 5048: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 5049: 
 5050: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 5051: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 5052: 		my $partial = $newpts/$wgt;
 5053: 		my $score;
 5054: 		if ($partial > 0) {
 5055: 		    $score = 'correct_by_override';
 5056: 		} elsif ($newpts ne '') { #empty is taken as 0
 5057: 		    $score = 'incorrect_by_override';
 5058: 		}
 5059: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 5060: 		if ($dropMenu eq 'excused') {
 5061: 		    $partial = '';
 5062: 		    $score = 'excused';
 5063: 		} elsif ($dropMenu eq 'reset status'
 5064: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 5065: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 5066: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 5067: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 5068: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 5069: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 5070: 		    $changeflag++;
 5071: 		    $newpts = '';
 5072:                     
 5073:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 5074:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 5075:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 5076:                     if ($aggtries > 0) {
 5077:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 5078:                         $aggregateflag = 1;
 5079:                     }
 5080: 		}
 5081: 		my $display_part=&get_display_part($partid,$curRes->symb());
 5082: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 5083: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5084: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 5085: 		    '&nbsp;<br />';
 5086: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5087: 		     (($score eq 'excused') ? 'excused' : $newpts).
 5088: 		    '&nbsp;<br />';
 5089: 		$question++;
 5090: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 5091: 
 5092: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 5093: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 5094: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 5095: 		    if (scalar(keys(%newrecord)) > 0);
 5096: 
 5097: 		$changeflag++;
 5098: 	    }
 5099: 	    if (scalar(keys(%newrecord)) > 0) {
 5100: 		my %record = 
 5101: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 5102: 					     $udom,$uname);
 5103: 
 5104: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 5105: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 5106: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 5107: 		    $newrecord{'resource.CODE'} = '';
 5108: 		}
 5109: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 5110: 					$udom,$uname);
 5111: 		%record = &Apache::lonnet::restore($symbx,
 5112: 						   $env{'request.course.id'},
 5113: 						   $udom,$uname);
 5114: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 5115: 					     $cdom,$cnum,$udom,$uname);
 5116: 	    }
 5117: 	    
 5118:             if ($aggregateflag) {
 5119:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 5120:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 5121:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 5122:             }
 5123: 
 5124: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 5125: 		'<td valign="top">'.$displayPts[1].'</td>'.
 5126: 		&Apache::loncommon::end_data_table_row();
 5127: 
 5128: 	    $prob++;
 5129: 	}
 5130:         $curRes = $iterator->next();
 5131:     }
 5132: 
 5133:     $studentTable.=&Apache::loncommon::end_data_table();
 5134:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 5135: 		  &mt('The scores were changed for [quant,_1,problem].',
 5136: 		  $changeflag).'<br />');
 5137:     my $hidemsg=($hideflag == 0 ? '' :
 5138:                  &mt('Submissions were marked "hidden" for [quant,_1,transaction].',
 5139:                      $hideflag).'<br />');
 5140:     $request->print($hidemsg.$grademsg.$studentTable);
 5141: 
 5142:     return '';
 5143: }
 5144: 
 5145: #-------- end of section for handling grading by page/sequence ---------
 5146: #
 5147: #-------------------------------------------------------------------
 5148: 
 5149: #-------------------- Bubblesheet (Scantron) Grading -------------------
 5150: #
 5151: #------ start of section for handling grading by page/sequence ---------
 5152: 
 5153: =pod
 5154: 
 5155: =head1 Bubble sheet grading routines
 5156: 
 5157:   For this documentation:
 5158: 
 5159:    'scanline' refers to the full line of characters
 5160:    from the file that we are parsing that represents one entire sheet
 5161: 
 5162:    'bubble line' refers to the data
 5163:    representing the line of bubbles that are on the physical bubblesheet
 5164: 
 5165: 
 5166: The overall process is that a scanned in bubblesheet data is uploaded
 5167: into a course. When a user wants to grade, they select a
 5168: sequence/folder of resources, a file of bubblesheet info, and pick
 5169: one of the predefined configurations for what each scanline looks
 5170: like.
 5171: 
 5172: Next each scanline is checked for any errors of either 'missing
 5173: bubbles' (it's an error because it may have been mis-scanned
 5174: because too light bubbling), 'double bubble' (each bubble line should
 5175: have no more than one letter picked), invalid or duplicated CODE,
 5176: invalid student/employee ID
 5177: 
 5178: If the CODE option is used that determines the randomization of the
 5179: homework problems, either way the student/employee ID is looked up into a
 5180: username:domain.
 5181: 
 5182: During the validation phase the instructor can choose to skip scanlines. 
 5183: 
 5184: After the validation phase, there are now 3 bubblesheet files
 5185: 
 5186:   scantron_original_filename (unmodified original file)
 5187:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 5188:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 5189: 
 5190: Also there is a separate hash nohist_scantrondata that contains extra
 5191: correction information that isn't representable in the bubblesheet
 5192: file (see &scantron_getfile() for more information)
 5193: 
 5194: After all scanlines are either valid, marked as valid or skipped, then
 5195: foreach line foreach problem in the picked sequence, an ssi request is
 5196: made that simulates a user submitting their selected letter(s) against
 5197: the homework problem.
 5198: 
 5199: =over 4
 5200: 
 5201: 
 5202: 
 5203: =item defaultFormData
 5204: 
 5205:   Returns html hidden inputs used to hold context/default values.
 5206: 
 5207:  Arguments:
 5208:   $symb - $symb of the current resource 
 5209: 
 5210: =cut
 5211: 
 5212: sub defaultFormData {
 5213:     my ($symb)=@_;
 5214:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />';
 5215: }
 5216: 
 5217: 
 5218: =pod 
 5219: 
 5220: =item getSequenceDropDown
 5221: 
 5222:    Return html dropdown of possible sequences to grade
 5223:  
 5224:  Arguments:
 5225:    $symb - $symb of the current resource
 5226:    $map_error - ref to scalar which will container error if
 5227:                 $navmap object is unavailable in &getSymbMap().
 5228: 
 5229: =cut
 5230: 
 5231: sub getSequenceDropDown {
 5232:     my ($symb,$map_error)=@_;
 5233:     my $result='<select name="selectpage">'."\n";
 5234:     my ($titles,$symbx) = &getSymbMap($map_error);
 5235:     if (ref($map_error)) {
 5236:         return if ($$map_error);
 5237:     }
 5238:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 5239:     my $ctr=0;
 5240:     foreach (@$titles) {
 5241: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 5242: 	$result.='<option value="'.$$symbx{$_}.'" '.
 5243: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 5244: 	    '>'.$showtitle.'</option>'."\n";
 5245: 	$ctr++;
 5246:     }
 5247:     $result.= '</select>';
 5248:     return $result;
 5249: }
 5250: 
 5251: my %bubble_lines_per_response;     # no. bubble lines for each response.
 5252:                                    # key is zero-based index - 0, 1, 2 ...
 5253: 
 5254: my %first_bubble_line;             # First bubble line no. for each bubble.
 5255: 
 5256: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 5257:                                    # matchresponse or rankresponse, where 
 5258:                                    # an individual response can have multiple 
 5259:                                    # lines
 5260: 
 5261: my %responsetype_per_response;     # responsetype for each response
 5262: 
 5263: my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
 5264:                                    # numbered response. Needed when randomorder
 5265:                                    # or randompick are in use. Key is ID, value 
 5266:                                    # is response number.
 5267: 
 5268: # Save and restore the bubble lines array to the form env.
 5269: 
 5270: 
 5271: sub save_bubble_lines {
 5272:     foreach my $line (keys(%bubble_lines_per_response)) {
 5273: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 5274: 	$env{"form.scantron.first_bubble_line.$line"} =
 5275: 	    $first_bubble_line{$line};
 5276:         $env{"form.scantron.sub_bubblelines.$line"} = 
 5277:             $subdivided_bubble_lines{$line};
 5278:         $env{"form.scantron.responsetype.$line"} =
 5279:             $responsetype_per_response{$line};
 5280:     }
 5281:     foreach my $resid (keys(%masterseq_id_responsenum)) {
 5282:         my $line = $masterseq_id_responsenum{$resid};
 5283:         $env{"form.scantron.residpart.$line"} = $resid;
 5284:     }
 5285: }
 5286: 
 5287: 
 5288: sub restore_bubble_lines {
 5289:     my $line = 0;
 5290:     %bubble_lines_per_response = ();
 5291:     %masterseq_id_responsenum = ();
 5292:     while ($env{"form.scantron.bubblelines.$line"}) {
 5293: 	my $value = $env{"form.scantron.bubblelines.$line"};
 5294: 	$bubble_lines_per_response{$line} = $value;
 5295: 	$first_bubble_line{$line}  =
 5296: 	    $env{"form.scantron.first_bubble_line.$line"};
 5297:         $subdivided_bubble_lines{$line} =
 5298:             $env{"form.scantron.sub_bubblelines.$line"};
 5299:         $responsetype_per_response{$line} =
 5300:             $env{"form.scantron.responsetype.$line"};
 5301:         my $id = $env{"form.scantron.residpart.$line"};
 5302:         $masterseq_id_responsenum{$id} = $line;
 5303: 	$line++;
 5304:     }
 5305: }
 5306: 
 5307: =pod 
 5308: 
 5309: =item scantron_filenames
 5310: 
 5311:    Returns a list of the scantron files in the current course 
 5312: 
 5313: =cut
 5314: 
 5315: sub scantron_filenames {
 5316:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5317:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5318:     my $getpropath = 1;
 5319:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
 5320:                                                         $cname,$getpropath);
 5321:     my @possiblenames;
 5322:     if (ref($dirlist) eq 'ARRAY') {
 5323:         foreach my $filename (sort(@{$dirlist})) {
 5324: 	    ($filename)=split(/&/,$filename);
 5325: 	    if ($filename!~/^scantron_orig_/) { next ; }
 5326: 	    $filename=~s/^scantron_orig_//;
 5327: 	    push(@possiblenames,$filename);
 5328:         }
 5329:     }
 5330:     return @possiblenames;
 5331: }
 5332: 
 5333: =pod 
 5334: 
 5335: =item scantron_uploads
 5336: 
 5337:    Returns  html drop-down list of scantron files in current course.
 5338: 
 5339:  Arguments:
 5340:    $file2grade - filename to set as selected in the dropdown
 5341: 
 5342: =cut
 5343: 
 5344: sub scantron_uploads {
 5345:     my ($file2grade) = @_;
 5346:     my $result=	'<select name="scantron_selectfile">';
 5347:     $result.="<option></option>";
 5348:     foreach my $filename (sort(&scantron_filenames())) {
 5349: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 5350:     }
 5351:     $result.="</select>";
 5352:     return $result;
 5353: }
 5354: 
 5355: =pod 
 5356: 
 5357: =item scantron_scantab
 5358: 
 5359:   Returns html drop down of the scantron formats in the scantronformat.tab
 5360:   file.
 5361: 
 5362: =cut
 5363: 
 5364: sub scantron_scantab {
 5365:     my $result='<select name="scantron_format">'."\n";
 5366:     $result.='<option></option>'."\n";
 5367:     my @lines = &get_scantronformat_file();
 5368:     if (@lines > 0) {
 5369:         foreach my $line (@lines) {
 5370:             next if (($line =~ /^\#/) || ($line eq ''));
 5371: 	    my ($name,$descrip)=split(/:/,$line);
 5372: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 5373:         }
 5374:     }
 5375:     $result.='</select>'."\n";
 5376:     return $result;
 5377: }
 5378: 
 5379: =pod
 5380: 
 5381: =item get_scantronformat_file
 5382: 
 5383:   Returns an array containing lines from the scantron format file for
 5384:   the domain of the course.
 5385: 
 5386:   If a url for a custom.tab file is listed in domain's configuration.db, 
 5387:   lines are from this file.
 5388: 
 5389:   Otherwise, if a default.tab has been published in RES space by the 
 5390:   domainconfig user, lines are from this file.
 5391: 
 5392:   Otherwise, fall back to getting lines from the legacy file on the
 5393:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
 5394: 
 5395: =cut
 5396: 
 5397: sub get_scantronformat_file {
 5398:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5399:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
 5400:     my $gottab = 0;
 5401:     my @lines;
 5402:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 5403:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 5404:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 5405:             if ($formatfile ne '-1') {
 5406:                 @lines = split("\n",$formatfile,-1);
 5407:                 $gottab = 1;
 5408:             }
 5409:         }
 5410:     }
 5411:     if (!$gottab) {
 5412:         my $confname = $cdom.'-domainconfig';
 5413:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 5414:         my $formatfile =  &Apache::lonnet::getfile($default);
 5415:         if ($formatfile ne '-1') {
 5416:             @lines = split("\n",$formatfile,-1);
 5417:             $gottab = 1;
 5418:         }
 5419:     }
 5420:     if (!$gottab) {
 5421:         my @domains = &Apache::lonnet::current_machine_domains();
 5422:         if (grep(/^\Q$cdom\E$/,@domains)) {
 5423:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 5424:             @lines = <$fh>;
 5425:             close($fh);
 5426:         } else {
 5427:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
 5428:             @lines = <$fh>;
 5429:             close($fh);
 5430:         }
 5431:     }
 5432:     return @lines;
 5433: }
 5434: 
 5435: =pod 
 5436: 
 5437: =item scantron_CODElist
 5438: 
 5439:   Returns html drop down of the saved CODE lists from current course,
 5440:   generated from earlier printings.
 5441: 
 5442: =cut
 5443: 
 5444: sub scantron_CODElist {
 5445:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5446:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5447:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 5448:     my $namechoice='<option></option>';
 5449:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 5450: 	if ($name =~ /^error: 2 /) { next; }
 5451: 	if ($name =~ /^type\0/) { next; }
 5452: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 5453:     }
 5454:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 5455:     return $namechoice;
 5456: }
 5457: 
 5458: =pod 
 5459: 
 5460: =item scantron_CODEunique
 5461: 
 5462:   Returns the html for "Each CODE to be used once" radio.
 5463: 
 5464: =cut
 5465: 
 5466: sub scantron_CODEunique {
 5467:     my $result='<span class="LC_nobreak">
 5468:                  <label><input type="radio" name="scantron_CODEunique"
 5469:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 5470:                 </span>
 5471:                 <span class="LC_nobreak">
 5472:                  <label><input type="radio" name="scantron_CODEunique"
 5473:                         value="no" />'.&mt('No').' </label>
 5474:                 </span>';
 5475:     return $result;
 5476: }
 5477: 
 5478: =pod 
 5479: 
 5480: =item scantron_selectphase
 5481: 
 5482:   Generates the initial screen to start the bubblesheet process.
 5483:   Allows for - starting a grading run.
 5484:              - downloading existing scan data (original, corrected
 5485:                                                 or skipped info)
 5486: 
 5487:              - uploading new scan data
 5488: 
 5489:  Arguments:
 5490:   $r          - The Apache request object
 5491:   $file2grade - name of the file that contain the scanned data to score
 5492: 
 5493: =cut
 5494: 
 5495: sub scantron_selectphase {
 5496:     my ($r,$file2grade,$symb) = @_;
 5497:     if (!$symb) {return '';}
 5498:     my $map_error;
 5499:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
 5500:     if ($map_error) {
 5501:         $r->print('<br />'.&navmap_errormsg().'<br />');
 5502:         return;
 5503:     }
 5504:     my $default_form_data=&defaultFormData($symb);
 5505:     my $file_selector=&scantron_uploads($file2grade);
 5506:     my $format_selector=&scantron_scantab();
 5507:     my $CODE_selector=&scantron_CODElist();
 5508:     my $CODE_unique=&scantron_CODEunique();
 5509:     my $result;
 5510: 
 5511:     $ssi_error = 0;
 5512: 
 5513:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 5514:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 5515: 
 5516: 	# Chunk of form to prompt for a scantron file upload.
 5517: 
 5518:         $r->print('
 5519:     <br />
 5520:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5521:        '.&Apache::loncommon::start_data_table_header_row().'
 5522:             <th>
 5523:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
 5524:             </th>
 5525:        '.&Apache::loncommon::end_data_table_header_row().'
 5526:        '.&Apache::loncommon::start_data_table_row().'
 5527:             <td>
 5528: ');
 5529:     my $default_form_data=&defaultFormData($symb);
 5530:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5531:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 5532:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 5533:     &js_escape(\$alertmsg);
 5534:     $r->print(&Apache::lonhtmlcommon::scripttag('
 5535:     function checkUpload(formname) {
 5536: 	if (formname.upfile.value == "") {
 5537: 	    alert("'.$alertmsg.'");
 5538: 	    return false;
 5539: 	}
 5540: 	formname.submit();
 5541:     }'));
 5542:     $r->print('
 5543:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 5544:                 '.$default_form_data.'
 5545:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 5546:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 5547:                 <input name="command" value="scantronupload_save" type="hidden" />
 5548:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
 5549:                 <br />
 5550:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 5551:               </form>
 5552: ');
 5553: 
 5554:         $r->print('
 5555:             </td>
 5556:        '.&Apache::loncommon::end_data_table_row().'
 5557:        '.&Apache::loncommon::end_data_table().'
 5558: ');
 5559:     }
 5560: 
 5561:     # Chunk of form to prompt for a file to grade and how:
 5562: 
 5563:     $result.= '
 5564:     <br />
 5565:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 5566:     <input type="hidden" name="command" value="scantron_warning" />
 5567:     '.$default_form_data.'
 5568:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5569:        '.&Apache::loncommon::start_data_table_header_row().'
 5570:             <th colspan="2">
 5571:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 5572:             </th>
 5573:        '.&Apache::loncommon::end_data_table_header_row().'
 5574:        '.&Apache::loncommon::start_data_table_row().'
 5575:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 5576:        '.&Apache::loncommon::end_data_table_row().'
 5577:        '.&Apache::loncommon::start_data_table_row().'
 5578:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
 5579:        '.&Apache::loncommon::end_data_table_row().'
 5580:        '.&Apache::loncommon::start_data_table_row().'
 5581:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
 5582:        '.&Apache::loncommon::end_data_table_row().'
 5583:        '.&Apache::loncommon::start_data_table_row().'
 5584:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 5585:        '.&Apache::loncommon::end_data_table_row().'
 5586:        '.&Apache::loncommon::start_data_table_row().'
 5587:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 5588:        '.&Apache::loncommon::end_data_table_row().'
 5589:        '.&Apache::loncommon::start_data_table_row().'
 5590: 	    <td> '.&mt('Options:').' </td>
 5591:             <td>
 5592: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 5593:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 5594:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 5595: 	    </td>
 5596:        '.&Apache::loncommon::end_data_table_row().'
 5597:        '.&Apache::loncommon::start_data_table_row().'
 5598:             <td colspan="2">
 5599:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
 5600:             </td>
 5601:        '.&Apache::loncommon::end_data_table_row().'
 5602:     '.&Apache::loncommon::end_data_table().'
 5603:     </form>
 5604: ';
 5605:    
 5606:     $r->print($result);
 5607: 
 5608: 
 5609: 
 5610:     # Chunk of the form that prompts to view a scoring office file,
 5611:     # corrected file, skipped records in a file.
 5612: 
 5613:     $r->print('
 5614:    <br />
 5615:    <form action="/adm/grades" name="scantron_download">
 5616:      '.$default_form_data.'
 5617:      <input type="hidden" name="command" value="scantron_download" />
 5618:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5619:        '.&Apache::loncommon::start_data_table_header_row().'
 5620:               <th>
 5621:                 &nbsp;'.&mt('Download a scoring office file').'
 5622:               </th>
 5623:        '.&Apache::loncommon::end_data_table_header_row().'
 5624:        '.&Apache::loncommon::start_data_table_row().'
 5625:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 5626:                 <br />
 5627:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 5628:        '.&Apache::loncommon::end_data_table_row().'
 5629:      '.&Apache::loncommon::end_data_table().'
 5630:    </form>
 5631:    <br />
 5632: ');
 5633: 
 5634:     &Apache::lonpickcode::code_list($r,2);
 5635: 
 5636:     $r->print('<br /><form method="post" name="checkscantron" action="">'.
 5637:              $default_form_data."\n".
 5638:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 5639:              &Apache::loncommon::start_data_table_header_row()."\n".
 5640:              '<th colspan="2">
 5641:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
 5642:              '</th>'."\n".
 5643:               &Apache::loncommon::end_data_table_header_row()."\n".
 5644:               &Apache::loncommon::start_data_table_row()."\n".
 5645:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 5646:               '<td> '.$sequence_selector.' </td>'.
 5647:               &Apache::loncommon::end_data_table_row()."\n".
 5648:               &Apache::loncommon::start_data_table_row()."\n".
 5649:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 5650:               '<td> '.$file_selector.' </td>'."\n".
 5651:               &Apache::loncommon::end_data_table_row()."\n".
 5652:               &Apache::loncommon::start_data_table_row()."\n".
 5653:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 5654:               '<td> '.$format_selector.' </td>'."\n".
 5655:               &Apache::loncommon::end_data_table_row()."\n".
 5656:               &Apache::loncommon::start_data_table_row()."\n".
 5657:               '<td> '.&mt('Options').' </td>'."\n".
 5658:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
 5659:               &Apache::loncommon::end_data_table_row()."\n".
 5660:               &Apache::loncommon::start_data_table_row()."\n".
 5661:               '<td colspan="2">'."\n".
 5662:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 5663:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
 5664:               '</td>'."\n".
 5665:               &Apache::loncommon::end_data_table_row()."\n".
 5666:               &Apache::loncommon::end_data_table()."\n".
 5667:               '</form><br />');
 5668:     return;
 5669: }
 5670: 
 5671: =pod
 5672: 
 5673: =item get_scantron_config
 5674: 
 5675:    Parse and return the bubblesheet configuration line selected as a
 5676:    hash of configuration file fields.
 5677: 
 5678:  Arguments:
 5679:     which - the name of the configuration to parse from the file.
 5680: 
 5681: 
 5682:  Returns:
 5683:             If the named configuration is not in the file, an empty
 5684:             hash is returned.
 5685:     a hash with the fields
 5686:       name         - internal name for the this configuration setup
 5687:       description  - text to display to operator that describes this config
 5688:       CODElocation - if 0 or the string 'none'
 5689:                           - no CODE exists for this config
 5690:                      if -1 || the string 'letter'
 5691:                           - a CODE exists for this config and is
 5692:                             a string of letters
 5693:                      Unsupported value (but planned for future support)
 5694:                           if a positive integer
 5695:                                - The CODE exists as the first n items from
 5696:                                  the question section of the form
 5697:                           if the string 'number'
 5698:                                - The CODE exists for this config and is
 5699:                                  a string of numbers
 5700:       CODEstart   - (only matter if a CODE exists) column in the line where
 5701:                      the CODE starts
 5702:       CODElength  - length of the CODE
 5703:       IDstart     - column where the student/employee ID starts
 5704:       IDlength    - length of the student/employee ID info
 5705:       Qstart      - column where the information from the bubbled
 5706:                     'questions' start
 5707:       Qlength     - number of columns comprising a single bubble line from
 5708:                     the sheet. (usually either 1 or 10)
 5709:       Qon         - either a single character representing the character used
 5710:                     to signal a bubble was chosen in the positional setup, or
 5711:                     the string 'letter' if the letter of the chosen bubble is
 5712:                     in the final, or 'number' if a number representing the
 5713:                     chosen bubble is in the file (1->A 0->J)
 5714:       Qoff        - the character used to represent that a bubble was
 5715:                     left blank
 5716:       PaperID     - if the scanning process generates a unique number for each
 5717:                     sheet scanned the column that this ID number starts in
 5718:       PaperIDlength - number of columns that comprise the unique ID number
 5719:                       for the sheet of paper
 5720:       FirstName   - column that the first name starts in
 5721:       FirstNameLength - number of columns that the first name spans
 5722:  
 5723:       LastName    - column that the last name starts in
 5724:       LastNameLength - number of columns that the last name spans
 5725:       BubblesPerRow - number of bubbles available in each row used to 
 5726:                       bubble an answer. (If not specified, 10 assumed).
 5727: 
 5728: =cut
 5729: 
 5730: sub get_scantron_config {
 5731:     my ($which) = @_;
 5732:     my @lines = &get_scantronformat_file();
 5733:     my %config;
 5734:     #FIXME probably should move to XML it has already gotten a bit much now
 5735:     foreach my $line (@lines) {
 5736: 	my ($name,$descrip)=split(/:/,$line);
 5737: 	if ($name ne $which ) { next; }
 5738: 	chomp($line);
 5739: 	my @config=split(/:/,$line);
 5740: 	$config{'name'}=$config[0];
 5741: 	$config{'description'}=$config[1];
 5742: 	$config{'CODElocation'}=$config[2];
 5743: 	$config{'CODEstart'}=$config[3];
 5744: 	$config{'CODElength'}=$config[4];
 5745: 	$config{'IDstart'}=$config[5];
 5746: 	$config{'IDlength'}=$config[6];
 5747: 	$config{'Qstart'}=$config[7];
 5748:  	$config{'Qlength'}=$config[8];
 5749: 	$config{'Qoff'}=$config[9];
 5750: 	$config{'Qon'}=$config[10];
 5751: 	$config{'PaperID'}=$config[11];
 5752: 	$config{'PaperIDlength'}=$config[12];
 5753: 	$config{'FirstName'}=$config[13];
 5754: 	$config{'FirstNamelength'}=$config[14];
 5755: 	$config{'LastName'}=$config[15];
 5756: 	$config{'LastNamelength'}=$config[16];
 5757:         $config{'BubblesPerRow'}=$config[17];
 5758: 	last;
 5759:     }
 5760:     return %config;
 5761: }
 5762: 
 5763: =pod 
 5764: 
 5765: =item username_to_idmap
 5766: 
 5767:     creates a hash keyed by student/employee ID with values of the corresponding
 5768:     student username:domain. If a single ID occurs for more than one student,
 5769:     the status of the student is checked, and if Active, the value in the hash
 5770:     will be set to the Active student.
 5771: 
 5772:   Arguments:
 5773: 
 5774:     $classlist - reference to the class list hash. This is a hash
 5775:                  keyed by student name:domain  whose elements are references
 5776:                  to arrays containing various chunks of information
 5777:                  about the student. (See loncoursedata for more info).
 5778: 
 5779:   Returns
 5780:     %idmap - the constructed hash
 5781: 
 5782: =cut
 5783: 
 5784: sub username_to_idmap {
 5785:     my ($classlist)= @_;
 5786:     my %idmap;
 5787:     foreach my $student (keys(%$classlist)) {
 5788:         my $id = $classlist->{$student}->[&Apache::loncoursedata::CL_ID];
 5789:         unless ($id eq '') {
 5790:             if (!exists($idmap{$id})) {
 5791:                 $idmap{$id} = $student;
 5792:             } else {
 5793:                 my $status = $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS];
 5794:                 if ($status eq 'Active') {
 5795:                     $idmap{$id} = $student;
 5796:                 }
 5797:             }
 5798:         }
 5799:     }
 5800:     return %idmap;
 5801: }
 5802: 
 5803: =pod
 5804: 
 5805: =item scantron_fixup_scanline
 5806: 
 5807:    Process a requested correction to a scanline.
 5808: 
 5809:   Arguments:
 5810:     $scantron_config   - hash from &get_scantron_config()
 5811:     $scan_data         - hash of correction information 
 5812:                           (see &scantron_getfile())
 5813:     $line              - existing scanline
 5814:     $whichline         - line number of the passed in scanline
 5815:     $field             - type of change to process 
 5816:                          (either 
 5817:                           'ID'     -> correct the student/employee ID
 5818:                           'CODE'   -> correct the CODE
 5819:                           'answer' -> fixup the submitted answers)
 5820:     
 5821:    $args               - hash of additional info,
 5822:                           - 'ID' 
 5823:                                'newid' -> studentID to use in replacement
 5824:                                           of existing one
 5825:                           - 'CODE' 
 5826:                                'CODE_ignore_dup' - set to true if duplicates
 5827:                                                    should be ignored.
 5828: 	                       'CODE' - is new code or 'use_unfound'
 5829:                                         if the existing unfound code should
 5830:                                         be used as is
 5831:                           - 'answer'
 5832:                                'response' - new answer or 'none' if blank
 5833:                                'question' - the bubble line to change
 5834:                                'questionnum' - the question identifier,
 5835:                                                may include subquestion. 
 5836: 
 5837:   Returns:
 5838:     $line - the modified scanline
 5839: 
 5840:   Side effects: 
 5841:     $scan_data - may be updated
 5842: 
 5843: =cut
 5844: 
 5845: 
 5846: sub scantron_fixup_scanline {
 5847:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 5848:     if ($field eq 'ID') {
 5849: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 5850: 	    return ($line,1,'New value too large');
 5851: 	}
 5852: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 5853: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 5854: 				     $args->{'newid'});
 5855: 	}
 5856: 	substr($line,$$scantron_config{'IDstart'}-1,
 5857: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 5858: 	if ($args->{'newid'}=~/^\s*$/) {
 5859: 	    &scan_data($scan_data,"$whichline.user",
 5860: 		       $args->{'username'}.':'.$args->{'domain'});
 5861: 	}
 5862:     } elsif ($field eq 'CODE') {
 5863: 	if ($args->{'CODE_ignore_dup'}) {
 5864: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 5865: 	}
 5866: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 5867: 	if ($args->{'CODE'} ne 'use_unfound') {
 5868: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 5869: 		return ($line,1,'New CODE value too large');
 5870: 	    }
 5871: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 5872: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 5873: 	    }
 5874: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 5875: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 5876: 	}
 5877:     } elsif ($field eq 'answer') {
 5878: 	my $length=$scantron_config->{'Qlength'};
 5879: 	my $off=$scantron_config->{'Qoff'};
 5880: 	my $on=$scantron_config->{'Qon'};
 5881: 	my $answer=${off}x$length;
 5882: 	if ($args->{'response'} eq 'none') {
 5883: 	    &scan_data($scan_data,
 5884: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 5885: 	} else {
 5886: 	    if ($on eq 'letter') {
 5887: 		my @alphabet=('A'..'Z');
 5888: 		$answer=$alphabet[$args->{'response'}];
 5889: 	    } elsif ($on eq 'number') {
 5890: 		$answer=$args->{'response'}+1;
 5891: 		if ($answer == 10) { $answer = '0'; }
 5892: 	    } else {
 5893: 		substr($answer,$args->{'response'},1)=$on;
 5894: 	    }
 5895: 	    &scan_data($scan_data,
 5896: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 5897: 	}
 5898: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 5899: 	substr($line,$where-1,$length)=$answer;
 5900:     }
 5901:     return $line;
 5902: }
 5903: 
 5904: =pod
 5905: 
 5906: =item scan_data
 5907: 
 5908:     Edit or look up  an item in the scan_data hash.
 5909: 
 5910:   Arguments:
 5911:     $scan_data  - The hash (see scantron_getfile)
 5912:     $key        - shorthand of the key to edit (actual key is
 5913:                   scantronfilename_key).
 5914:     $data        - New value of the hash entry.
 5915:     $delete      - If true, the entry is removed from the hash.
 5916: 
 5917:   Returns:
 5918:     The new value of the hash table field (undefined if deleted).
 5919: 
 5920: =cut
 5921: 
 5922: 
 5923: sub scan_data {
 5924:     my ($scan_data,$key,$value,$delete)=@_;
 5925:     my $filename=$env{'form.scantron_selectfile'};
 5926:     if (defined($value)) {
 5927: 	$scan_data->{$filename.'_'.$key} = $value;
 5928:     }
 5929:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 5930:     return $scan_data->{$filename.'_'.$key};
 5931: }
 5932: 
 5933: # ----- These first few routines are general use routines.----
 5934: 
 5935: # Return the number of occurences of a pattern in a string.
 5936: 
 5937: sub occurence_count {
 5938:     my ($string, $pattern) = @_;
 5939: 
 5940:     my @matches = ($string =~ /$pattern/g);
 5941: 
 5942:     return scalar(@matches);
 5943: }
 5944: 
 5945: 
 5946: # Take a string known to have digits and convert all the
 5947: # digits into letters in the range J,A..I.
 5948: 
 5949: sub digits_to_letters {
 5950:     my ($input) = @_;
 5951: 
 5952:     my @alphabet = ('J', 'A'..'I');
 5953: 
 5954:     my @input    = split(//, $input);
 5955:     my $output ='';
 5956:     for (my $i = 0; $i < scalar(@input); $i++) {
 5957: 	if ($input[$i] =~ /\d/) {
 5958: 	    $output .= $alphabet[$input[$i]];
 5959: 	} else {
 5960: 	    $output .= $input[$i];
 5961: 	}
 5962:     }
 5963:     return $output;
 5964: }
 5965: 
 5966: =pod 
 5967: 
 5968: =item scantron_parse_scanline
 5969: 
 5970:   Decodes a scanline from the selected bubblesheet file
 5971: 
 5972:  Arguments:
 5973:     line             - The text of the bubblesheet file line to process
 5974:     whichline        - Line number
 5975:     scantron_config  - Hash describing the format of the bubblesheet lines.
 5976:     scan_data        - Hash of extra information about the scanline
 5977:                        (see scantron_getfile for more information)
 5978:     just_header      - True if should not process question answers but only
 5979:                        the stuff to the left of the answers.
 5980:     randomorder      - True if randomorder in use
 5981:     randompick       - True if randompick in use
 5982:     sequence         - Exam folder URL
 5983:     master_seq       - Ref to array containing symbs in exam folder
 5984:     symb_to_resource - Ref to hash of symbs for resources in exam folder
 5985:                        (corresponding values are resource objects)
 5986:     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
 5987:     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
 5988:                        are refs to an array of resource objects, ordered
 5989:                        according to order used for CODE, when randomorder
 5990:                        and or randompick are in use.
 5991:     respnumlookup    - Ref to hash mapping question numbers in bubble lines
 5992:                        for current line to question number used for same question
 5993:                         in "Master Sequence" (as seen by Course Coordinator).
 5994:     startline        - Ref to hash where key is question number (0 is first)
 5995:                        and value is number of first bubble line for current 
 5996:                        student or code-based randompick and/or randomorder.
 5997:     totalref         - Ref of scalar used to score total number of bubble
 5998:                        lines needed for responses in a scan line (used when
 5999:                        randompick in use. 
 6000:     
 6001:  Returns:
 6002:    Hash containing the result of parsing the scanline
 6003: 
 6004:    Keys are all proceeded by the string 'scantron.'
 6005: 
 6006:        CODE    - the CODE in use for this scanline
 6007:        useCODE - 1 if the CODE is invalid but it usage has been forced
 6008:                  by the operator
 6009:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 6010:                             CODEs were selected, but the usage has been
 6011:                             forced by the operator
 6012:        ID  - student/employee ID
 6013:        PaperID - if used, the ID number printed on the sheet when the 
 6014:                  paper was scanned
 6015:        FirstName - first name from the sheet
 6016:        LastName  - last name from the sheet
 6017: 
 6018:      if just_header was not true these key may also exist
 6019: 
 6020:        missingerror - a list of bubble ranges that are considered to be answers
 6021:                       to a single question that don't have any bubbles filled in.
 6022:                       Of the form questionnumber:firstbubblenumber:count.
 6023:        doubleerror  - a list of bubble ranges that are considered to be answers
 6024:                       to a single question that have more than one bubble filled in.
 6025:                       Of the form questionnumber::firstbubblenumber:count
 6026:    
 6027:                 In the above, count is the number of bubble responses in the
 6028:                 input line needed to represent the possible answers to the question.
 6029:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 6030:                 per line would have count = 2.
 6031: 
 6032:        maxquest     - the number of the last bubble line that was parsed
 6033: 
 6034:        (<number> starts at 1)
 6035:        <number>.answer - zero or more letters representing the selected
 6036:                          letters from the scanline for the bubble line 
 6037:                          <number>.
 6038:                          if blank there was either no bubble or there where
 6039:                          multiple bubbles, (consult the keys missingerror and
 6040:                          doubleerror if this is an error condition)
 6041: 
 6042: =cut
 6043: 
 6044: sub scantron_parse_scanline {
 6045:     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
 6046:         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
 6047:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
 6048: 
 6049:     my %record;
 6050:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
 6051:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 6052: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 6053: 	if ($$scantron_config{'CODElocation'} < 0 ||
 6054: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 6055: 	    $$scantron_config{'CODElocation'} eq 'number') {
 6056: 	    $record{'scantron.CODE'}=substr($data,
 6057: 					    $$scantron_config{'CODEstart'}-1,
 6058: 					    $$scantron_config{'CODElength'});
 6059: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 6060: 		$record{'scantron.useCODE'}=1;
 6061: 	    }
 6062: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 6063: 		$record{'scantron.CODE_ignore_dup'}=1;
 6064: 	    }
 6065: 	} else {
 6066: 	    #FIXME interpret first N questions
 6067: 	}
 6068:     }
 6069:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 6070: 				  $$scantron_config{'IDlength'});
 6071:     $record{'scantron.PaperID'}=
 6072: 	substr($data,$$scantron_config{'PaperID'}-1,
 6073: 	       $$scantron_config{'PaperIDlength'});
 6074:     $record{'scantron.FirstName'}=
 6075: 	substr($data,$$scantron_config{'FirstName'}-1,
 6076: 	       $$scantron_config{'FirstNamelength'});
 6077:     $record{'scantron.LastName'}=
 6078: 	substr($data,$$scantron_config{'LastName'}-1,
 6079: 	       $$scantron_config{'LastNamelength'});
 6080:     if ($just_header) { return \%record; }
 6081: 
 6082:     my @alphabet=('A'..'Z');
 6083:     my $questnum=0;
 6084:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 6085: 
 6086:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 6087:     if ($randompick || $randomorder) {
 6088:         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
 6089:                                          $master_seq,$symb_to_resource,
 6090:                                          $partids_by_symb,$orderedforcode,
 6091:                                          $respnumlookup,$startline);
 6092:         if ($total) {
 6093:             $lastpos = $total*$$scantron_config{'Qlength'}; 
 6094:         }
 6095:         if (ref($totalref)) {
 6096:             $$totalref = $total;
 6097:         }
 6098:     }
 6099:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 6100:     chomp($questions);		# Get rid of any trailing \n.
 6101:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 6102:     while (length($questions)) {
 6103:         my $answers_needed;
 6104:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6105:             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
 6106:         } else {
 6107: 	    $answers_needed = $bubble_lines_per_response{$questnum};
 6108:         }
 6109:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 6110:                              || 1;
 6111:         $questnum++;
 6112:         my $quest_id = $questnum;
 6113:         my $currentquest = substr($questions,0,$answer_length);
 6114:         $questions       = substr($questions,$answer_length);
 6115:         if (length($currentquest) < $answer_length) { next; }
 6116: 
 6117:         my $subdivided;
 6118:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6119:             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
 6120:         } else {
 6121:             $subdivided = $subdivided_bubble_lines{$questnum-1};
 6122:         }
 6123:         if ($subdivided =~ /,/) {
 6124:             my $subquestnum = 1;
 6125:             my $subquestions = $currentquest;
 6126:             my @subanswers_needed = split(/,/,$subdivided);
 6127:             foreach my $subans (@subanswers_needed) {
 6128:                 my $subans_length =
 6129:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 6130:                 my $currsubquest = substr($subquestions,0,$subans_length);
 6131:                 $subquestions   = substr($subquestions,$subans_length);
 6132:                 $quest_id = "$questnum.$subquestnum";
 6133:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 6134:                     ($$scantron_config{'Qon'} eq 'number')) {
 6135:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 6136:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6137:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6138:                         $randomorder,$randompick,$respnumlookup);
 6139:                 } else {
 6140:                     $ansnum = &scantron_validator_positional($ansnum,
 6141:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6142:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6143:                         $randomorder,$randompick,$respnumlookup);
 6144:                 }
 6145:                 $subquestnum ++;
 6146:             }
 6147:         } else {
 6148:             if (($$scantron_config{'Qon'} eq 'letter') ||
 6149:                 ($$scantron_config{'Qon'} eq 'number')) {
 6150:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 6151:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6152:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6153:                     $randomorder,$randompick,$respnumlookup);
 6154:             } else {
 6155:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 6156:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6157:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6158:                     $randomorder,$randompick,$respnumlookup);
 6159:             }
 6160:         }
 6161:     }
 6162:     $record{'scantron.maxquest'}=$questnum;
 6163:     return \%record;
 6164: }
 6165: 
 6166: sub get_master_seq {
 6167:     my ($resources,$master_seq,$symb_to_resource) = @_;
 6168:     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') && 
 6169:                    (ref($symb_to_resource) eq 'HASH'));
 6170:     my $resource_error;
 6171:     foreach my $resource (@{$resources}) {
 6172:         my $ressymb;
 6173:         if (ref($resource)) {
 6174:             $ressymb = $resource->symb();
 6175:             push(@{$master_seq},$ressymb);
 6176:             $symb_to_resource->{$ressymb} = $resource;
 6177:         } else {
 6178:             $resource_error = 1;
 6179:             last;
 6180:         }
 6181:     }
 6182:     return $resource_error;
 6183: }
 6184: 
 6185: sub get_respnum_lookups {
 6186:     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
 6187:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
 6188:     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
 6189:                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
 6190:                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
 6191:                    (ref($startline) eq 'HASH'));
 6192:     my ($user,$scancode);
 6193:     if ((exists($record->{'scantron.CODE'})) &&
 6194:         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
 6195:         $scancode = $record->{'scantron.CODE'};
 6196:     } else {
 6197:         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
 6198:     }
 6199:     my @mapresources =
 6200:         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
 6201:                      $orderedforcode);
 6202:     my $total = 0;
 6203:     my $count = 0;
 6204:     foreach my $resource (@mapresources) {
 6205:         my $id = $resource->id();
 6206:         my $symb = $resource->symb();
 6207:         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
 6208:             foreach my $partid (@{$partids_by_symb->{$symb}}) {
 6209:                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
 6210:                 if ($respnum ne '') {
 6211:                     $respnumlookup->{$count} = $respnum;
 6212:                     $startline->{$count} = $total;
 6213:                     $total += $bubble_lines_per_response{$respnum};
 6214:                     $count ++;
 6215:                 }
 6216:             }
 6217:         }
 6218:     }
 6219:     return $total;
 6220: }
 6221: 
 6222: sub scantron_validator_lettnum {
 6223:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 6224:         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
 6225:         $randompick,$respnumlookup) = @_;
 6226: 
 6227:     # Qon 'letter' implies for each slot in currquest we have:
 6228:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 6229:     #    about anything else (esp. a value of Qoff) for missing
 6230:     #    bubbles.
 6231:     #
 6232:     # Qon 'number' implies each slot gives a digit that indexes the
 6233:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 6234:     #    and * or ? for double bubbles on a single line.
 6235:     #
 6236: 
 6237:     my $matchon;
 6238:     if ($$scantron_config{'Qon'} eq 'letter') {
 6239:         $matchon = '[A-Z]';
 6240:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 6241:         $matchon = '\d';
 6242:     }
 6243:     my $occurrences = 0;
 6244:     my $responsenum = $questnum-1;
 6245:     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6246:        $responsenum = $respnumlookup->{$questnum-1} 
 6247:     }
 6248:     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6249:         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6250:         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6251:         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6252:         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6253:         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6254:         my @singlelines = split('',$currquest);
 6255:         foreach my $entry (@singlelines) {
 6256:             $occurrences = &occurence_count($entry,$matchon);
 6257:             if ($occurrences > 1) {
 6258:                 last;
 6259:             }
 6260:         }
 6261:     } else {
 6262:         $occurrences = &occurence_count($currquest,$matchon); 
 6263:     }
 6264:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 6265:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6266:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6267:             my $bubble = substr($currquest,$ans,1);
 6268:             if ($bubble =~ /$matchon/ ) {
 6269:                 if ($$scantron_config{'Qon'} eq 'number') {
 6270:                     if ($bubble == 0) {
 6271:                         $bubble = 10; 
 6272:                     }
 6273:                     $record->{"scantron.$ansnum.answer"} = 
 6274:                         $alphabet->[$bubble-1];
 6275:                 } else {
 6276:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 6277:                 }
 6278:             } else {
 6279:                 $record->{"scantron.$ansnum.answer"}='';
 6280:             }
 6281:             $ansnum++;
 6282:         }
 6283:     } elsif (!defined($currquest)
 6284:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 6285:             || (&occurence_count($currquest,$matchon) == 0)) {
 6286:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6287:             $record->{"scantron.$ansnum.answer"}='';
 6288:             $ansnum++;
 6289:         }
 6290:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6291:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 6292:         }
 6293:     } else {
 6294:         if ($$scantron_config{'Qon'} eq 'number') {
 6295:             $currquest = &digits_to_letters($currquest);            
 6296:         }
 6297:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6298:             my $bubble = substr($currquest,$ans,1);
 6299:             $record->{"scantron.$ansnum.answer"} = $bubble;
 6300:             $ansnum++;
 6301:         }
 6302:     }
 6303:     return $ansnum;
 6304: }
 6305: 
 6306: sub scantron_validator_positional {
 6307:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 6308:         $whichline,$alphabet,$record,$scantron_config,$scan_data,
 6309:         $randomorder,$randompick,$respnumlookup) = @_;
 6310: 
 6311:     # Otherwise there's a positional notation;
 6312:     # each bubble line requires Qlength items, and there are filled in
 6313:     # bubbles for each case where there 'Qon' characters.
 6314:     #
 6315: 
 6316:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 6317: 
 6318:     # If the split only gives us one element.. the full length of the
 6319:     # answer string, no bubbles are filled in:
 6320: 
 6321:     if ($answers_needed eq '') {
 6322:         return;
 6323:     }
 6324: 
 6325:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 6326:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6327:             $record->{"scantron.$ansnum.answer"}='';
 6328:             $ansnum++;
 6329:         }
 6330:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6331:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 6332:         }
 6333:     } elsif (scalar(@array) == 2) {
 6334:         my $location = length($array[0]);
 6335:         my $line_num = int($location / $$scantron_config{'Qlength'});
 6336:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 6337:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6338:             if ($ans eq $line_num) {
 6339:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 6340:             } else {
 6341:                 $record->{"scantron.$ansnum.answer"} = ' ';
 6342:             }
 6343:             $ansnum++;
 6344:          }
 6345:     } else {
 6346:         #  If there's more than one instance of a bubble character
 6347:         #  That's a double bubble; with positional notation we can
 6348:         #  record all the bubbles filled in as well as the
 6349:         #  fact this response consists of multiple bubbles.
 6350:         #
 6351:         my $responsenum = $questnum-1;
 6352:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6353:             $responsenum = $respnumlookup->{$questnum-1}
 6354:         }
 6355:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6356:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6357:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6358:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6359:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6360:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6361:             my $doubleerror = 0;
 6362:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 6363:                    (!$doubleerror)) {
 6364:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 6365:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 6366:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 6367:                if (length(@currarray) > 2) {
 6368:                    $doubleerror = 1;
 6369:                } 
 6370:             }
 6371:             if ($doubleerror) {
 6372:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6373:             }
 6374:         } else {
 6375:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6376:         }
 6377:         my $item = $ansnum;
 6378:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6379:             $record->{"scantron.$item.answer"} = '';
 6380:             $item ++;
 6381:         }
 6382: 
 6383:         my @ans=@array;
 6384:         my $i=0;
 6385:         my $increment = 0;
 6386:         while ($#ans) {
 6387:             $i+=length($ans[0]) + $increment;
 6388:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 6389:             my $bubble = $i%$$scantron_config{'Qlength'};
 6390:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 6391:             shift(@ans);
 6392:             $increment = 1;
 6393:         }
 6394:         $ansnum += $answers_needed;
 6395:     }
 6396:     return $ansnum;
 6397: }
 6398: 
 6399: =pod
 6400: 
 6401: =item scantron_add_delay
 6402: 
 6403:    Adds an error message that occurred during the grading phase to a
 6404:    queue of messages to be shown after grading pass is complete
 6405: 
 6406:  Arguments:
 6407:    $delayqueue  - arrary ref of hash ref of error messages
 6408:    $scanline    - the scanline that caused the error
 6409:    $errormesage - the error message
 6410:    $errorcode   - a numeric code for the error
 6411: 
 6412:  Side Effects:
 6413:    updates the $delayqueue to have a new hash ref of the error
 6414: 
 6415: =cut
 6416: 
 6417: sub scantron_add_delay {
 6418:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 6419:     push(@$delayqueue,
 6420: 	 {'line' => $scanline, 'emsg' => $errormessage,
 6421: 	  'ecode' => $errorcode }
 6422: 	 );
 6423: }
 6424: 
 6425: =pod
 6426: 
 6427: =item scantron_find_student
 6428: 
 6429:    Finds the username for the current scanline
 6430: 
 6431:   Arguments:
 6432:    $scantron_record - hash result from scantron_parse_scanline
 6433:    $scan_data       - hash of correction information 
 6434:                       (see &scantron_getfile() form more information)
 6435:    $idmap           - hash from &username_to_idmap()
 6436:    $line            - number of current scanline
 6437:  
 6438:   Returns:
 6439:    Either 'username:domain' or undef if unknown
 6440: 
 6441: =cut
 6442: 
 6443: sub scantron_find_student {
 6444:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 6445:     my $scanID=$$scantron_record{'scantron.ID'};
 6446:     if ($scanID =~ /^\s*$/) {
 6447:  	return &scan_data($scan_data,"$line.user");
 6448:     }
 6449:     foreach my $id (keys(%$idmap)) {
 6450:  	if (lc($id) eq lc($scanID)) {
 6451:  	    return $$idmap{$id};
 6452:  	}
 6453:     }
 6454:     return undef;
 6455: }
 6456: 
 6457: =pod
 6458: 
 6459: =item scantron_filter
 6460: 
 6461:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 6462:    hidden resources was selected
 6463: 
 6464: =cut
 6465: 
 6466: sub scantron_filter {
 6467:     my ($curres)=@_;
 6468: 
 6469:     if (ref($curres) && $curres->is_problem()) {
 6470: 	# if the user has asked to not have either hidden
 6471: 	# or 'randomout' controlled resources to be graded
 6472: 	# don't include them
 6473: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6474: 	    && $curres->randomout) {
 6475: 	    return 0;
 6476: 	}
 6477: 	return 1;
 6478:     }
 6479:     return 0;
 6480: }
 6481: 
 6482: =pod
 6483: 
 6484: =item scantron_process_corrections
 6485: 
 6486:    Gets correction information out of submitted form data and corrects
 6487:    the scanline
 6488: 
 6489: =cut
 6490: 
 6491: sub scantron_process_corrections {
 6492:     my ($r) = @_;
 6493:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6494:     my ($scanlines,$scan_data)=&scantron_getfile();
 6495:     my $classlist=&Apache::loncoursedata::get_classlist();
 6496:     my $which=$env{'form.scantron_line'};
 6497:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 6498:     my ($skip,$err,$errmsg);
 6499:     if ($env{'form.scantron_skip_record'}) {
 6500: 	$skip=1;
 6501:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 6502: 	my $newstudent=$env{'form.scantron_username'}.':'.
 6503: 	    $env{'form.scantron_domain'};
 6504: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 6505: 	($line,$err,$errmsg)=
 6506: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6507: 				     'ID',{'newid'=>$newid,
 6508: 				    'username'=>$env{'form.scantron_username'},
 6509: 				    'domain'=>$env{'form.scantron_domain'}});
 6510:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 6511: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 6512: 	my $newCODE;
 6513: 	my %args;
 6514: 	if      ($resolution eq 'use_unfound') {
 6515: 	    $newCODE='use_unfound';
 6516: 	} elsif ($resolution eq 'use_found') {
 6517: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 6518: 	} elsif ($resolution eq 'use_typed') {
 6519: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 6520: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 6521: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 6522: 	}
 6523: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 6524: 	    $args{'CODE_ignore_dup'}=1;
 6525: 	}
 6526: 	$args{'CODE'}=$newCODE;
 6527: 	($line,$err,$errmsg)=
 6528: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6529: 				     'CODE',\%args);
 6530:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 6531: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 6532: 	    ($line,$err,$errmsg)=
 6533: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 6534: 					 $which,'answer',
 6535: 					 { 'question'=>$question,
 6536: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 6537:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 6538: 	    if ($err) { last; }
 6539: 	}
 6540:     }
 6541:     if ($err) {
 6542:         $r->print(
 6543:             '<p class="LC_error">'
 6544:            .&mt('Unable to accept last correction, an error occurred: [_1]',
 6545:                 $errmsg)
 6546:            .'</p>');
 6547:     } else {
 6548: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 6549: 	&scantron_putfile($scanlines,$scan_data);
 6550:     }
 6551: }
 6552: 
 6553: =pod
 6554: 
 6555: =item reset_skipping_status
 6556: 
 6557:    Forgets the current set of remember skipped scanlines (and thus
 6558:    reverts back to considering all lines in the
 6559:    scantron_skipped_<filename> file)
 6560: 
 6561: =cut
 6562: 
 6563: sub reset_skipping_status {
 6564:     my ($scanlines,$scan_data)=&scantron_getfile();
 6565:     &scan_data($scan_data,'remember_skipping',undef,1);
 6566:     &scantron_putfile(undef,$scan_data);
 6567: }
 6568: 
 6569: =pod
 6570: 
 6571: =item start_skipping
 6572: 
 6573:    Marks a scanline to be skipped. 
 6574: 
 6575: =cut
 6576: 
 6577: sub start_skipping {
 6578:     my ($scan_data,$i)=@_;
 6579:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6580:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 6581: 	$remembered{$i}=2;
 6582:     } else {
 6583: 	$remembered{$i}=1;
 6584:     }
 6585:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 6586: }
 6587: 
 6588: =pod
 6589: 
 6590: =item should_be_skipped
 6591: 
 6592:    Checks whether a scanline should be skipped.
 6593: 
 6594: =cut
 6595: 
 6596: sub should_be_skipped {
 6597:     my ($scanlines,$scan_data,$i)=@_;
 6598:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 6599: 	# not redoing old skips
 6600: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 6601: 	return 0;
 6602:     }
 6603:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6604: 
 6605:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 6606: 	return 0;
 6607:     }
 6608:     return 1;
 6609: }
 6610: 
 6611: =pod
 6612: 
 6613: =item remember_current_skipped
 6614: 
 6615:    Discovers what scanlines are in the scantron_skipped_<filename>
 6616:    file and remembers them into scan_data for later use.
 6617: 
 6618: =cut
 6619: 
 6620: sub remember_current_skipped {
 6621:     my ($scanlines,$scan_data)=&scantron_getfile();
 6622:     my %to_remember;
 6623:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6624: 	if ($scanlines->{'skipped'}[$i]) {
 6625: 	    $to_remember{$i}=1;
 6626: 	}
 6627:     }
 6628: 
 6629:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 6630:     &scantron_putfile(undef,$scan_data);
 6631: }
 6632: 
 6633: =pod
 6634: 
 6635: =item check_for_error
 6636: 
 6637:     Checks if there was an error when attempting to remove a specific
 6638:     scantron_.. bubblesheet data file. Prints out an error if
 6639:     something went wrong.
 6640: 
 6641: =cut
 6642: 
 6643: sub check_for_error {
 6644:     my ($r,$result)=@_;
 6645:     if ($result ne 'ok' && $result ne 'not_found' ) {
 6646: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 6647:     }
 6648: }
 6649: 
 6650: =pod
 6651: 
 6652: =item scantron_warning_screen
 6653: 
 6654:    Interstitial screen to make sure the operator has selected the
 6655:    correct options before we start the validation phase.
 6656: 
 6657: =cut
 6658: 
 6659: sub scantron_warning_screen {
 6660:     my ($button_text,$symb)=@_;
 6661:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 6662:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6663:     my $CODElist;
 6664:     if ($scantron_config{'CODElocation'} &&
 6665: 	$scantron_config{'CODEstart'} &&
 6666: 	$scantron_config{'CODElength'}) {
 6667: 	$CODElist=$env{'form.scantron_CODElist'};
 6668: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
 6669: 	$CODElist=
 6670: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 6671: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 6672:     }
 6673:     my $lastbubblepoints;
 6674:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 6675:         $lastbubblepoints =
 6676:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
 6677:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
 6678:     }
 6679:     return ('
 6680: <p>
 6681: <span class="LC_warning">
 6682: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
 6683: </p>
 6684: <table>
 6685: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 6686: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 6687: '.$CODElist.$lastbubblepoints.'
 6688: </table>
 6689: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
 6690: '.&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>
 6691: 
 6692: <br />
 6693: ');
 6694: }
 6695: 
 6696: =pod
 6697: 
 6698: =item scantron_do_warning
 6699: 
 6700:    Check if the operator has picked something for all required
 6701:    fields. Error out if something is missing.
 6702: 
 6703: =cut
 6704: 
 6705: sub scantron_do_warning {
 6706:     my ($r,$symb)=@_;
 6707:     if (!$symb) {return '';}
 6708:     my $default_form_data=&defaultFormData($symb);
 6709:     $r->print(&scantron_form_start().$default_form_data);
 6710:     if ( $env{'form.selectpage'} eq '' ||
 6711: 	 $env{'form.scantron_selectfile'} eq '' ||
 6712: 	 $env{'form.scantron_format'} eq '' ) {
 6713: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
 6714: 	if ( $env{'form.selectpage'} eq '') {
 6715: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 6716: 	} 
 6717: 	if ( $env{'form.scantron_selectfile'} eq '') {
 6718: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected a file that contains the student's response data.").'</span></p>');
 6719: 	} 
 6720: 	if ( $env{'form.scantron_format'} eq '') {
 6721: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected the format of the student's response data.").'</span></p>');
 6722: 	} 
 6723:     } else {
 6724: 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
 6725:         my $bubbledbyhand=&hand_bubble_option();
 6726: 	$r->print('
 6727: '.$warning.$bubbledbyhand.'
 6728: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 6729: <input type="hidden" name="command" value="scantron_validate" />
 6730: ');
 6731:     }
 6732:     $r->print("</form><br />");
 6733:     return '';
 6734: }
 6735: 
 6736: =pod
 6737: 
 6738: =item scantron_form_start
 6739: 
 6740:     html hidden input for remembering all selected grading options
 6741: 
 6742: =cut
 6743: 
 6744: sub scantron_form_start {
 6745:     my ($max_bubble)=@_;
 6746:     my $result= <<SCANTRONFORM;
 6747: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 6748:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 6749:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 6750:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 6751:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 6752:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 6753:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 6754:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 6755:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 6756:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 6757: SCANTRONFORM
 6758: 
 6759:   my $line = 0;
 6760:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 6761:        my $chunk =
 6762: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 6763:        $chunk .=
 6764: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 6765:        $chunk .= 
 6766:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 6767:        $chunk .=
 6768:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 6769:        $chunk .=
 6770:            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
 6771:        $result .= $chunk;
 6772:        $line++;
 6773:     }
 6774:     return $result;
 6775: }
 6776: 
 6777: =pod
 6778: 
 6779: =item scantron_validate_file
 6780: 
 6781:     Dispatch routine for doing validation of a bubblesheet data file.
 6782: 
 6783:     Also processes any necessary information resets that need to
 6784:     occur before validation begins (ignore previous corrections,
 6785:     restarting the skipped records processing)
 6786: 
 6787: =cut
 6788: 
 6789: sub scantron_validate_file {
 6790:     my ($r,$symb) = @_;
 6791:     if (!$symb) {return '';}
 6792:     my $default_form_data=&defaultFormData($symb);
 6793:     
 6794:     # do the detection of only doing skipped records first before we delete
 6795:     # them when doing the corrections reset
 6796:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 6797: 	&reset_skipping_status();
 6798:     }
 6799:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 6800: 	&remember_current_skipped();
 6801: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 6802:     }
 6803: 
 6804:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 6805: 	&check_for_error($r,&scantron_remove_file('corrected'));
 6806: 	&check_for_error($r,&scantron_remove_file('skipped'));
 6807: 	&check_for_error($r,&scantron_remove_scan_data());
 6808: 	$env{'form.scantron_options_ignore'}='done';
 6809:     }
 6810: 
 6811:     if ($env{'form.scantron_corrections'}) {
 6812: 	&scantron_process_corrections($r);
 6813:     }
 6814:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 6815:     #get the student pick code ready
 6816:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 6817:     my $nav_error;
 6818:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6819:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 6820:     if ($nav_error) {
 6821:         $r->print(&navmap_errormsg());
 6822:         return '';
 6823:     }
 6824:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 6825:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 6826:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
 6827:     }
 6828:     $r->print($result);
 6829:     
 6830:     my @validate_phases=( 'sequence',
 6831: 			  'ID',
 6832: 			  'CODE',
 6833: 			  'doublebubble',
 6834: 			  'missingbubbles');
 6835:     if (!$env{'form.validatepass'}) {
 6836: 	$env{'form.validatepass'} = 0;
 6837:     }
 6838:     my $currentphase=$env{'form.validatepass'};
 6839: 
 6840: 
 6841:     my $stop=0;
 6842:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 6843: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 6844: 	$r->rflush();
 6845:      
 6846: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 6847: 	{
 6848: 	    no strict 'refs';
 6849: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 6850: 	}
 6851:     }
 6852:     if (!$stop) {
 6853: 	my $warning=&scantron_warning_screen('Start Grading',$symb);
 6854: 	$r->print(&mt('Validation process complete.').'<br />'.
 6855:                   $warning.
 6856:                   &mt('Perform verification for each student after storage of submissions?').
 6857:                   '&nbsp;<span class="LC_nobreak"><label>'.
 6858:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 6859:                   ('&nbsp;'x3).'<label>'.
 6860:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 6861:                   '</label></span><br />'.
 6862:                   &mt('Grading will take longer if you use verification.').'<br />'.
 6863:                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
 6864:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 6865:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 6866:     } else {
 6867: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 6868: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 6869:     }
 6870:     if ($stop) {
 6871: 	if ($validate_phases[$currentphase] eq 'sequence') {
 6872: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 6873: 	    $r->print(' '.&mt('this error').' <br />');
 6874: 
 6875: 	    $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>');
 6876: 	} else {
 6877:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 6878: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 6879:             } else {
 6880:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 6881:             }
 6882: 	    $r->print(' '.&mt('using corrected info').' <br />');
 6883: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 6884: 	    $r->print(" ".&mt("this scanline saving it for later."));
 6885: 	}
 6886:     }
 6887:     $r->print(" </form><br />");
 6888:     return '';
 6889: }
 6890: 
 6891: 
 6892: =pod
 6893: 
 6894: =item scantron_remove_file
 6895: 
 6896:    Removes the requested bubblesheet data file, makes sure that
 6897:    scantron_original_<filename> is never removed
 6898: 
 6899: 
 6900: =cut
 6901: 
 6902: sub scantron_remove_file {
 6903:     my ($which)=@_;
 6904:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6905:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6906:     my $file='scantron_';
 6907:     if ($which eq 'corrected' || $which eq 'skipped') {
 6908: 	$file.=$which.'_';
 6909:     } else {
 6910: 	return 'refused';
 6911:     }
 6912:     $file.=$env{'form.scantron_selectfile'};
 6913:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 6914: }
 6915: 
 6916: 
 6917: =pod
 6918: 
 6919: =item scantron_remove_scan_data
 6920: 
 6921:    Removes all scan_data correction for the requested bubblesheet
 6922:    data file.  (In the case that both the are doing skipped records we need
 6923:    to remember the old skipped lines for the time being so that element
 6924:    persists for a while.)
 6925: 
 6926: =cut
 6927: 
 6928: sub scantron_remove_scan_data {
 6929:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6930:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6931:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 6932:     my @todelete;
 6933:     my $filename=$env{'form.scantron_selectfile'};
 6934:     foreach my $key (@keys) {
 6935: 	if ($key=~/^\Q$filename\E_/) {
 6936: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 6937: 		$key=~/remember_skipping/) {
 6938: 		next;
 6939: 	    }
 6940: 	    push(@todelete,$key);
 6941: 	}
 6942:     }
 6943:     my $result;
 6944:     if (@todelete) {
 6945: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 6946: 				       \@todelete,$cdom,$cname);
 6947:     } else {
 6948: 	$result = 'ok';
 6949:     }
 6950:     return $result;
 6951: }
 6952: 
 6953: 
 6954: =pod
 6955: 
 6956: =item scantron_getfile
 6957: 
 6958:     Fetches the requested bubblesheet data file (all 3 versions), and
 6959:     the scan_data hash
 6960:   
 6961:   Arguments:
 6962:     None
 6963: 
 6964:   Returns:
 6965:     2 hash references
 6966: 
 6967:      - first one has 
 6968:          orig      -
 6969:          corrected -
 6970:          skipped   -  each of which points to an array ref of the specified
 6971:                       file broken up into individual lines
 6972:          count     - number of scanlines
 6973:  
 6974:      - second is the scan_data hash possible keys are
 6975:        ($number refers to scanline numbered $number and thus the key affects
 6976:         only that scanline
 6977:         $bubline refers to the specific bubble line element and the aspects
 6978:         refers to that specific bubble line element)
 6979: 
 6980:        $number.user - username:domain to use
 6981:        $number.CODE_ignore_dup 
 6982:                     - ignore the duplicate CODE error 
 6983:        $number.useCODE
 6984:                     - use the CODE in the scanline as is
 6985:        $number.no_bubble.$bubline
 6986:                     - it is valid that there is no bubbled in bubble
 6987:                       at $number $bubline
 6988:        remember_skipping
 6989:                     - a frozen hash containing keys of $number and values
 6990:                       of either 
 6991:                         1 - we are on a 'do skipped records pass' and plan
 6992:                             on processing this line
 6993:                         2 - we are on a 'do skipped records pass' and this
 6994:                             scanline has been marked to skip yet again
 6995: 
 6996: =cut
 6997: 
 6998: sub scantron_getfile {
 6999:     #FIXME really would prefer a scantron directory
 7000:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7001:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7002:     my $lines;
 7003:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7004: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 7005:     my %scanlines;
 7006:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 7007:     my $temp=$scanlines{'orig'};
 7008:     $scanlines{'count'}=$#$temp;
 7009: 
 7010:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7011: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 7012:     if ($lines eq '-1') {
 7013: 	$scanlines{'corrected'}=[];
 7014:     } else {
 7015: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 7016:     }
 7017:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7018: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 7019:     if ($lines eq '-1') {
 7020: 	$scanlines{'skipped'}=[];
 7021:     } else {
 7022: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 7023:     }
 7024:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 7025:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 7026:     my %scan_data = @tmp;
 7027:     return (\%scanlines,\%scan_data);
 7028: }
 7029: 
 7030: =pod
 7031: 
 7032: =item lonnet_putfile
 7033: 
 7034:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 7035: 
 7036:  Arguments:
 7037:    $contents - data to store
 7038:    $filename - filename to store $contents into
 7039: 
 7040:  Returns:
 7041:    result value from &Apache::lonnet::finishuserfileupload
 7042: 
 7043: =cut
 7044: 
 7045: sub lonnet_putfile {
 7046:     my ($contents,$filename)=@_;
 7047:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7048:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7049:     $env{'form.sillywaytopassafilearound'}=$contents;
 7050:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 7051: 
 7052: }
 7053: 
 7054: =pod
 7055: 
 7056: =item scantron_putfile
 7057: 
 7058:     Stores the current version of the bubblesheet data files, and the
 7059:     scan_data hash. (Does not modify the original version only the
 7060:     corrected and skipped versions.
 7061: 
 7062:  Arguments:
 7063:     $scanlines - hash ref that looks like the first return value from
 7064:                  &scantron_getfile()
 7065:     $scan_data - hash ref that looks like the second return value from
 7066:                  &scantron_getfile()
 7067: 
 7068: =cut
 7069: 
 7070: sub scantron_putfile {
 7071:     my ($scanlines,$scan_data) = @_;
 7072:     #FIXME really would prefer a scantron directory
 7073:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7074:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7075:     if ($scanlines) {
 7076: 	my $prefix='scantron_';
 7077: # no need to update orig, shouldn't change
 7078: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 7079: #		    $env{'form.scantron_selectfile'});
 7080: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 7081: 			$prefix.'corrected_'.
 7082: 			$env{'form.scantron_selectfile'});
 7083: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 7084: 			$prefix.'skipped_'.
 7085: 			$env{'form.scantron_selectfile'});
 7086:     }
 7087:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 7088: }
 7089: 
 7090: =pod
 7091: 
 7092: =item scantron_get_line
 7093: 
 7094:    Returns the correct version of the scanline
 7095: 
 7096:  Arguments:
 7097:     $scanlines - hash ref that looks like the first return value from
 7098:                  &scantron_getfile()
 7099:     $scan_data - hash ref that looks like the second return value from
 7100:                  &scantron_getfile()
 7101:     $i         - number of the requested line (starts at 0)
 7102: 
 7103:  Returns:
 7104:    A scanline, (either the original or the corrected one if it
 7105:    exists), or undef if the requested scanline should be
 7106:    skipped. (Either because it's an skipped scanline, or it's an
 7107:    unskipped scanline and we are not doing a 'do skipped scanlines'
 7108:    pass.
 7109: 
 7110: =cut
 7111: 
 7112: sub scantron_get_line {
 7113:     my ($scanlines,$scan_data,$i)=@_;
 7114:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 7115:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 7116:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 7117:     return $scanlines->{'orig'}[$i]; 
 7118: }
 7119: 
 7120: =pod
 7121: 
 7122: =item scantron_todo_count
 7123: 
 7124:     Counts the number of scanlines that need processing.
 7125: 
 7126:  Arguments:
 7127:     $scanlines - hash ref that looks like the first return value from
 7128:                  &scantron_getfile()
 7129:     $scan_data - hash ref that looks like the second return value from
 7130:                  &scantron_getfile()
 7131: 
 7132:  Returns:
 7133:     $count - number of scanlines to process
 7134: 
 7135: =cut
 7136: 
 7137: sub get_todo_count {
 7138:     my ($scanlines,$scan_data)=@_;
 7139:     my $count=0;
 7140:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7141: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7142: 	if ($line=~/^[\s\cz]*$/) { next; }
 7143: 	$count++;
 7144:     }
 7145:     return $count;
 7146: }
 7147: 
 7148: =pod
 7149: 
 7150: =item scantron_put_line
 7151: 
 7152:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
 7153:     data file.
 7154: 
 7155:  Arguments:
 7156:     $scanlines - hash ref that looks like the first return value from
 7157:                  &scantron_getfile()
 7158:     $scan_data - hash ref that looks like the second return value from
 7159:                  &scantron_getfile()
 7160:     $i         - line number to update
 7161:     $newline   - contents of the updated scanline
 7162:     $skip      - if true make the line for skipping and update the
 7163:                  'skipped' file
 7164: 
 7165: =cut
 7166: 
 7167: sub scantron_put_line {
 7168:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 7169:     if ($skip) {
 7170: 	$scanlines->{'skipped'}[$i]=$newline;
 7171: 	&start_skipping($scan_data,$i);
 7172: 	return;
 7173:     }
 7174:     $scanlines->{'corrected'}[$i]=$newline;
 7175: }
 7176: 
 7177: =pod
 7178: 
 7179: =item scantron_clear_skip
 7180: 
 7181:    Remove a line from the 'skipped' file
 7182: 
 7183:  Arguments:
 7184:     $scanlines - hash ref that looks like the first return value from
 7185:                  &scantron_getfile()
 7186:     $scan_data - hash ref that looks like the second return value from
 7187:                  &scantron_getfile()
 7188:     $i         - line number to update
 7189: 
 7190: =cut
 7191: 
 7192: sub scantron_clear_skip {
 7193:     my ($scanlines,$scan_data,$i)=@_;
 7194:     if (exists($scanlines->{'skipped'}[$i])) {
 7195: 	undef($scanlines->{'skipped'}[$i]);
 7196: 	return 1;
 7197:     }
 7198:     return 0;
 7199: }
 7200: 
 7201: =pod
 7202: 
 7203: =item scantron_filter_not_exam
 7204: 
 7205:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 7206:    filter out resources that are not marked as 'exam' mode
 7207: 
 7208: =cut
 7209: 
 7210: sub scantron_filter_not_exam {
 7211:     my ($curres)=@_;
 7212:     
 7213:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 7214: 	# if the user has asked to not have either hidden
 7215: 	# or 'randomout' controlled resources to be graded
 7216: 	# don't include them
 7217: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 7218: 	    && $curres->randomout) {
 7219: 	    return 0;
 7220: 	}
 7221: 	return 1;
 7222:     }
 7223:     return 0;
 7224: }
 7225: 
 7226: =pod
 7227: 
 7228: =item scantron_validate_sequence
 7229: 
 7230:     Validates the selected sequence, checking for resource that are
 7231:     not set to exam mode.
 7232: 
 7233: =cut
 7234: 
 7235: sub scantron_validate_sequence {
 7236:     my ($r,$currentphase) = @_;
 7237: 
 7238:     my $navmap=Apache::lonnavmaps::navmap->new();
 7239:     unless (ref($navmap)) {
 7240:         $r->print(&navmap_errormsg());
 7241:         return (1,$currentphase);
 7242:     }
 7243:     my (undef,undef,$sequence)=
 7244: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7245: 
 7246:     my $map=$navmap->getResourceByUrl($sequence);
 7247: 
 7248:     $r->print('<input type="hidden" name="validate_sequence_exam"
 7249:                                     value="ignore" />');
 7250:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 7251: 	my @resources=
 7252: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 7253: 	if (@resources) {
 7254: 	    $r->print(
 7255:                 '<p class="LC_warning">'
 7256:                .&mt('Some resources in the sequence currently are not set to'
 7257:                    .' bubblesheet exam mode. Grading these resources currently may not'
 7258:                    .' work correctly.')
 7259:                .'</p>'
 7260:             );
 7261: 	    return (1,$currentphase);
 7262: 	}
 7263:     }
 7264: 
 7265:     return (0,$currentphase+1);
 7266: }
 7267: 
 7268: 
 7269: 
 7270: sub scantron_validate_ID {
 7271:     my ($r,$currentphase) = @_;
 7272:     
 7273:     #get student info
 7274:     my $classlist=&Apache::loncoursedata::get_classlist();
 7275:     my %idmap=&username_to_idmap($classlist);
 7276: 
 7277:     #get scantron line setup
 7278:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7279:     my ($scanlines,$scan_data)=&scantron_getfile();
 7280: 
 7281:     my $nav_error;
 7282:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
 7283:     if ($nav_error) {
 7284:         $r->print(&navmap_errormsg());
 7285:         return(1,$currentphase);
 7286:     }
 7287: 
 7288:     my %found=('ids'=>{},'usernames'=>{});
 7289:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7290: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7291: 	if ($line=~/^[\s\cz]*$/) { next; }
 7292: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7293: 						 $scan_data);
 7294: 	my $id=$$scan_record{'scantron.ID'};
 7295: 	my $found;
 7296: 	foreach my $checkid (keys(%idmap)) {
 7297: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 7298: 	}
 7299: 	if ($found) {
 7300: 	    my $username=$idmap{$found};
 7301: 	    if ($found{'ids'}{$found}) {
 7302: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7303: 					 $line,'duplicateID',$found);
 7304: 		return(1,$currentphase);
 7305: 	    } elsif ($found{'usernames'}{$username}) {
 7306: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7307: 					 $line,'duplicateID',$username);
 7308: 		return(1,$currentphase);
 7309: 	    }
 7310: 	    #FIXME store away line we previously saw the ID on to use above
 7311: 	    $found{'ids'}{$found}++;
 7312: 	    $found{'usernames'}{$username}++;
 7313: 	} else {
 7314: 	    if ($id =~ /^\s*$/) {
 7315: 		my $username=&scan_data($scan_data,"$i.user");
 7316: 		if (defined($username) && $found{'usernames'}{$username}) {
 7317: 		    &scantron_get_correction($r,$i,$scan_record,
 7318: 					     \%scantron_config,
 7319: 					     $line,'duplicateID',$username);
 7320: 		    return(1,$currentphase);
 7321: 		} elsif (!defined($username)) {
 7322: 		    &scantron_get_correction($r,$i,$scan_record,
 7323: 					     \%scantron_config,
 7324: 					     $line,'incorrectID');
 7325: 		    return(1,$currentphase);
 7326: 		}
 7327: 		$found{'usernames'}{$username}++;
 7328: 	    } else {
 7329: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7330: 					 $line,'incorrectID');
 7331: 		return(1,$currentphase);
 7332: 	    }
 7333: 	}
 7334:     }
 7335: 
 7336:     return (0,$currentphase+1);
 7337: }
 7338: 
 7339: 
 7340: sub scantron_get_correction {
 7341:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
 7342:         $randomorder,$randompick,$respnumlookup,$startline)=@_;
 7343: #FIXME in the case of a duplicated ID the previous line, probably need
 7344: #to show both the current line and the previous one and allow skipping
 7345: #the previous one or the current one
 7346: 
 7347:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 7348:         $r->print(
 7349:             '<p class="LC_warning">'
 7350:            .&mt('An error was detected ([_1]) for PaperID [_2]',
 7351:                 "<b>$error</b>",
 7352:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
 7353:            ."</p> \n");
 7354:     } else {
 7355:         $r->print(
 7356:             '<p class="LC_warning">'
 7357:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
 7358:                 "<b>$error</b>", $i, "<pre>$line</pre>")
 7359:            ."</p> \n");
 7360:     }
 7361:     my $message =
 7362:         '<p>'
 7363:        .&mt('The ID on the form is [_1]',
 7364:             "<tt>$$scan_record{'scantron.ID'}</tt>")
 7365:        .'<br />'
 7366:        .&mt('The name on the paper is [_1], [_2]',
 7367:             $$scan_record{'scantron.LastName'},
 7368:             $$scan_record{'scantron.FirstName'})
 7369:        .'</p>';
 7370: 
 7371:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 7372:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 7373:                            # Array populated for doublebubble or
 7374:     my @lines_to_correct;  # missingbubble errors to build javascript
 7375:                            # to validate radio button checking   
 7376: 
 7377:     if ($error =~ /ID$/) {
 7378: 	if ($error eq 'incorrectID') {
 7379:             $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
 7380: 		      "</p>\n");
 7381: 	} elsif ($error eq 'duplicateID') {
 7382:             $r->print('<p class="LC_warning">'.&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 7383: 	}
 7384: 	$r->print($message);
 7385: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 7386: 	$r->print("\n<ul><li> ");
 7387: 	#FIXME it would be nice if this sent back the user ID and
 7388: 	#could do partial userID matches
 7389: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 7390: 				       'scantron_username','scantron_domain'));
 7391: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 7392: 	$r->print("\n:\n".
 7393: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 7394: 
 7395: 	$r->print('</li>');
 7396:     } elsif ($error =~ /CODE$/) {
 7397: 	if ($error eq 'incorrectCODE') {
 7398: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 7399: 	} elsif ($error eq 'duplicateCODE') {
 7400: 	    $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");
 7401: 	}
 7402: 	$r->print("<p>".&mt('The CODE on the form is [_1]',
 7403: 			    "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
 7404:                  ."</p>\n");
 7405: 	$r->print($message);
 7406: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
 7407: 	$r->print("\n<br /> ");
 7408: 	my $i=0;
 7409: 	if ($error eq 'incorrectCODE' 
 7410: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 7411: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 7412: 	    if ($closest > 0) {
 7413: 		foreach my $testcode (@{$closest}) {
 7414: 		    my $checked='';
 7415: 		    if (!$i) { $checked=' checked="checked"'; }
 7416: 		    $r->print("
 7417:    <label>
 7418:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
 7419:        ".&mt("Use the similar CODE [_1] instead.",
 7420: 	    "<b><tt>".$testcode."</tt></b>")."
 7421:     </label>
 7422:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 7423: 		    $r->print("\n<br />");
 7424: 		    $i++;
 7425: 		}
 7426: 	    }
 7427: 	}
 7428: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 7429: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
 7430: 	    $r->print("
 7431:     <label>
 7432:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
 7433:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
 7434: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 7435:     </label>");
 7436: 	    $r->print("\n<br />");
 7437: 	}
 7438: 
 7439: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
 7440: function change_radio(field) {
 7441:     var slct=document.scantronupload.scantron_CODE_resolution;
 7442:     var i;
 7443:     for (i=0;i<slct.length;i++) {
 7444:         if (slct[i].value==field) { slct[i].checked=true; }
 7445:     }
 7446: }
 7447: ENDSCRIPT
 7448: 	my $href="/adm/pickcode?".
 7449: 	   "form=".&escape("scantronupload").
 7450: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 7451: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 7452: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 7453: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 7454: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 7455: 	    $r->print("
 7456:     <label>
 7457:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 7458:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 7459: 	     "<a target='_blank' href='$href'>","</a>")."
 7460:     </label> 
 7461:     ".&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\')" />'));
 7462: 	    $r->print("\n<br />");
 7463: 	}
 7464: 	$r->print("
 7465:     <label>
 7466:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 7467:        ".&mt("Use [_1] as the CODE.",
 7468: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 7469: 	$r->print("\n<br /><br />");
 7470:     } elsif ($error eq 'doublebubble') {
 7471: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 7472: 
 7473: 	# The form field scantron_questions is acutally a list of line numbers.
 7474: 	# represented by this form so:
 7475: 
 7476: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 7477:                                                 $respnumlookup,$startline);
 7478: 
 7479: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7480: 		  $line_list.'" />');
 7481: 	$r->print($message);
 7482: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 7483: 	foreach my $question (@{$arg}) {
 7484: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7485:                                                    $scan_record, $error,
 7486:                                                    $randomorder,$randompick,
 7487:                                                    $respnumlookup,$startline);
 7488:             push(@lines_to_correct,@linenums);
 7489: 	}
 7490:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7491:     } elsif ($error eq 'missingbubble') {
 7492: 	$r->print('<p class="LC_warning">'.&mt("There have been [_1]no[_2] bubbles scanned for some question(s)",'<b>','</b>')."</p>\n");
 7493: 	$r->print($message);
 7494: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 7495: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 7496: 
 7497: 	# The form field scantron_questions is actually a list of line numbers not
 7498: 	# a list of question numbers. Therefore:
 7499: 	#
 7500: 
 7501: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 7502:                                                 $respnumlookup,$startline);
 7503: 
 7504: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7505: 		  $line_list.'" />');
 7506: 	foreach my $question (@{$arg}) {
 7507: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7508:                                                    $scan_record, $error,
 7509:                                                    $randomorder,$randompick,
 7510:                                                    $respnumlookup,$startline);
 7511:             push(@lines_to_correct,@linenums);
 7512: 	}
 7513:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7514:     } else {
 7515: 	$r->print("\n<ul>");
 7516:     }
 7517:     $r->print("\n</li></ul>");
 7518: }
 7519: 
 7520: sub verify_bubbles_checked {
 7521:     my (@ansnums) = @_;
 7522:     my $ansnumstr = join('","',@ansnums);
 7523:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 7524:     &js_escape(\$warning);
 7525:     my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
 7526: function verify_bubble_radio(form) {
 7527:     var ansnumArray = new Array ("$ansnumstr");
 7528:     var need_bubble_count = 0;
 7529:     for (var i=0; i<ansnumArray.length; i++) {
 7530:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 7531:             var bubble_picked = 0; 
 7532:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 7533:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 7534:                     bubble_picked = 1;
 7535:                 }
 7536:             }
 7537:             if (bubble_picked == 0) {
 7538:                 need_bubble_count ++;
 7539:             }
 7540:         }
 7541:     }
 7542:     if (need_bubble_count) {
 7543:         alert("$warning");
 7544:         return;
 7545:     }
 7546:     form.submit(); 
 7547: }
 7548: ENDSCRIPT
 7549:     return $output;
 7550: }
 7551: 
 7552: =pod
 7553: 
 7554: =item  questions_to_line_list
 7555: 
 7556: Converts a list of questions into a string of comma separated
 7557: line numbers in the answer sheet used by the questions.  This is
 7558: used to fill in the scantron_questions form field.
 7559: 
 7560:   Arguments:
 7561:      questions    - Reference to an array of questions.
 7562:      randomorder  - True if randomorder in use.
 7563:      randompick   - True if randompick in use.
 7564:      respnumlookup - Reference to HASH mapping question numbers in bubble lines
 7565:                      for current line to question number used for same question
 7566:                      in "Master Seqence" (as seen by Course Coordinator).
 7567:      startline    - Reference to hash where key is question number (0 is first)
 7568:                     and key is number of first bubble line for current student
 7569:                     or code-based randompick and/or randomorder.
 7570: 
 7571: =cut
 7572: 
 7573: 
 7574: sub questions_to_line_list {
 7575:     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
 7576:     my @lines;
 7577: 
 7578:     foreach my $item (@{$questions}) {
 7579:         my $question = $item;
 7580:         my ($first,$count,$last);
 7581:         if ($item =~ /^(\d+)\.(\d+)$/) {
 7582:             $question = $1;
 7583:             my $subquestion = $2;
 7584:             my $responsenum = $question-1;
 7585:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7586:                 $responsenum = $respnumlookup->{$question-1};
 7587:                 if (ref($startline) eq 'HASH') {
 7588:                     $first = $startline->{$question-1} + 1;
 7589:                 }
 7590:             } else {
 7591:                 $first = $first_bubble_line{$responsenum} + 1;
 7592:             }
 7593:             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 7594:             my $subcount = 1;
 7595:             while ($subcount<$subquestion) {
 7596:                 $first += $subans[$subcount-1];
 7597:                 $subcount ++;
 7598:             }
 7599:             $count = $subans[$subquestion-1];
 7600:         } else {
 7601:             my $responsenum = $question-1;
 7602:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7603:                 $responsenum = $respnumlookup->{$question-1};
 7604:                 if (ref($startline) eq 'HASH') {
 7605:                     $first = $startline->{$question-1} + 1;
 7606:                 }
 7607:             } else {
 7608:                 $first = $first_bubble_line{$responsenum} + 1;
 7609:             }
 7610: 	    $count   = $bubble_lines_per_response{$responsenum};
 7611:         }
 7612:         $last = $first+$count-1;
 7613:         push(@lines, ($first..$last));
 7614:     }
 7615:     return join(',', @lines);
 7616: }
 7617: 
 7618: =pod 
 7619: 
 7620: =item prompt_for_corrections
 7621: 
 7622: Prompts for a potentially multiline correction to the
 7623: user's bubbling (factors out common code from scantron_get_correction
 7624: for multi and missing bubble cases).
 7625: 
 7626:  Arguments:
 7627:    $r           - Apache request object.
 7628:    $question    - The question number to prompt for.
 7629:    $scan_config - The scantron file configuration hash.
 7630:    $scan_record - Reference to the hash that has the the parsed scanlines.
 7631:    $error       - Type of error
 7632:    $randomorder - True if randomorder in use.
 7633:    $randompick  - True if randompick in use.
 7634:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
 7635:                     for current line to question number used for same question
 7636:                     in "Master Seqence" (as seen by Course Coordinator).
 7637:    $startline   - Reference to hash where key is question number (0 is first)
 7638:                   and value is number of first bubble line for current student
 7639:                   or code-based randompick and/or randomorder.
 7640: 
 7641: 
 7642:  Implicit inputs:
 7643:    %bubble_lines_per_response   - Starting line numbers for each question.
 7644:                                   Numbered from 0 (but question numbers are from
 7645:                                   1.
 7646:    %first_bubble_line           - Starting bubble line for each question.
 7647:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 7648:                                   type problems render as separate sub-questions, 
 7649:                                   in exam mode. This hash contains a 
 7650:                                   comma-separated list of the lines per 
 7651:                                   sub-question.
 7652:    %responsetype_per_response   - essayresponse, formularesponse,
 7653:                                   stringresponse, imageresponse, reactionresponse,
 7654:                                   and organicresponse type problem parts can have
 7655:                                   multiple lines per response if the weight
 7656:                                   assigned exceeds 10.  In this case, only
 7657:                                   one bubble per line is permitted, but more 
 7658:                                   than one line might contain bubbles, e.g.
 7659:                                   bubbling of: line 1 - J, line 2 - J, 
 7660:                                   line 3 - B would assign 22 points.  
 7661: 
 7662: =cut
 7663: 
 7664: sub prompt_for_corrections {
 7665:     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
 7666:         $randompick, $respnumlookup, $startline) = @_;
 7667:     my ($current_line,$lines);
 7668:     my @linenums;
 7669:     my $questionnum = $question;
 7670:     my ($first,$responsenum);
 7671:     if ($question =~ /^(\d+)\.(\d+)$/) {
 7672:         $question = $1;
 7673:         my $subquestion = $2;
 7674:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7675:             $responsenum = $respnumlookup->{$question-1};
 7676:             if (ref($startline) eq 'HASH') {
 7677:                 $first = $startline->{$question-1};
 7678:             }
 7679:         } else {
 7680:             $responsenum = $question-1;
 7681:             $first = $first_bubble_line{$responsenum};
 7682:         }
 7683:         $current_line = $first + 1 ;
 7684:         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 7685:         my $subcount = 1;
 7686:         while ($subcount<$subquestion) {
 7687:             $current_line += $subans[$subcount-1];
 7688:             $subcount ++;
 7689:         }
 7690:         $lines = $subans[$subquestion-1];
 7691:     } else {
 7692:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7693:             $responsenum = $respnumlookup->{$question-1};
 7694:             if (ref($startline) eq 'HASH') { 
 7695:                 $first = $startline->{$question-1};
 7696:             }
 7697:         } else {
 7698:             $responsenum = $question-1;
 7699:             $first = $first_bubble_line{$responsenum};
 7700:         }
 7701:         $current_line = $first + 1;
 7702:         $lines        = $bubble_lines_per_response{$responsenum};
 7703:     }
 7704:     if ($lines > 1) {
 7705:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 7706:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 7707:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 7708:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 7709:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 7710:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 7711:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 7712:             $r->print(
 7713:                 &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)
 7714:                .'<br /><br />'
 7715:                .&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.')
 7716:                .'<br />'
 7717:                .&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.')
 7718:                .'<br />'
 7719:                .&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.")
 7720:                .'<br /><br />'
 7721:             );
 7722:         } else {
 7723:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 7724:         }
 7725:     }
 7726:     for (my $i =0; $i < $lines; $i++) {
 7727:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 7728: 	&scantron_bubble_selector($r,$scan_config,$current_line,
 7729: 	        		  $questionnum,$error,split('', $selected));
 7730:         push(@linenums,$current_line);
 7731: 	$current_line++;
 7732:     }
 7733:     if ($lines > 1) {
 7734: 	$r->print("<hr /><br />");
 7735:     }
 7736:     return @linenums;
 7737: }
 7738: 
 7739: =pod
 7740: 
 7741: =item scantron_bubble_selector
 7742:   
 7743:    Generates the html radiobuttons to correct a single bubble line
 7744:    possibly showing the existing the selected bubbles if known
 7745: 
 7746:  Arguments:
 7747:     $r           - Apache request object
 7748:     $scan_config - hash from &get_scantron_config()
 7749:     $line        - Number of the line being displayed.
 7750:     $questionnum - Question number (may include subquestion)
 7751:     $error       - Type of error.
 7752:     @selected    - Array of bubbles picked on this line.
 7753: 
 7754: =cut
 7755: 
 7756: sub scantron_bubble_selector {
 7757:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 7758:     my $max=$$scan_config{'Qlength'};
 7759: 
 7760:     my $scmode=$$scan_config{'Qon'};
 7761:     if ($scmode eq 'number' || $scmode eq 'letter') { 
 7762:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
 7763:             ($$scan_config{'BubblesPerRow'} > 0)) {
 7764:             $max=$$scan_config{'BubblesPerRow'};
 7765:             if (($scmode eq 'number') && ($max > 10)) {
 7766:                 $max = 10;
 7767:             } elsif (($scmode eq 'letter') && $max > 26) {
 7768:                 $max = 26;
 7769:             }
 7770:         } else {
 7771:             $max = 10;
 7772:         }
 7773:     }
 7774: 
 7775:     my @alphabet=('A'..'Z');
 7776:     $r->print(&Apache::loncommon::start_data_table().
 7777:               &Apache::loncommon::start_data_table_row());
 7778:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 7779:     for (my $i=0;$i<$max+1;$i++) {
 7780: 	$r->print("\n".'<td align="center">');
 7781: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 7782: 	else { $r->print('&nbsp;'); }
 7783: 	$r->print('</td>');
 7784:     }
 7785:     $r->print(&Apache::loncommon::end_data_table_row().
 7786:               &Apache::loncommon::start_data_table_row());
 7787:     for (my $i=0;$i<$max;$i++) {
 7788: 	$r->print("\n".
 7789: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 7790: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 7791:     }
 7792:     my $nobub_checked = ' ';
 7793:     if ($error eq 'missingbubble') {
 7794:         $nobub_checked = ' checked = "checked" ';
 7795:     }
 7796:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 7797: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 7798:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 7799:               $line.'" value="'.$questionnum.'" /></td>');
 7800:     $r->print(&Apache::loncommon::end_data_table_row().
 7801:               &Apache::loncommon::end_data_table());
 7802: }
 7803: 
 7804: =pod
 7805: 
 7806: =item num_matches
 7807: 
 7808:    Counts the number of characters that are the same between the two arguments.
 7809: 
 7810:  Arguments:
 7811:    $orig - CODE from the scanline
 7812:    $code - CODE to match against
 7813: 
 7814:  Returns:
 7815:    $count - integer count of the number of same characters between the
 7816:             two arguments
 7817: 
 7818: =cut
 7819: 
 7820: sub num_matches {
 7821:     my ($orig,$code) = @_;
 7822:     my @code=split(//,$code);
 7823:     my @orig=split(//,$orig);
 7824:     my $same=0;
 7825:     for (my $i=0;$i<scalar(@code);$i++) {
 7826: 	if ($code[$i] eq $orig[$i]) { $same++; }
 7827:     }
 7828:     return $same;
 7829: }
 7830: 
 7831: =pod
 7832: 
 7833: =item scantron_get_closely_matching_CODEs
 7834: 
 7835:    Cycles through all CODEs and finds the set that has the greatest
 7836:    number of same characters as the provided CODE
 7837: 
 7838:  Arguments:
 7839:    $allcodes - hash ref returned by &get_codes()
 7840:    $CODE     - CODE from the current scanline
 7841: 
 7842:  Returns:
 7843:    2 element list
 7844:     - first elements is number of how closely matching the best fit is 
 7845:       (5 means best set has 5 matching characters)
 7846:     - second element is an arrary ref containing the set of valid CODEs
 7847:       that best fit the passed in CODE
 7848: 
 7849: =cut
 7850: 
 7851: sub scantron_get_closely_matching_CODEs {
 7852:     my ($allcodes,$CODE)=@_;
 7853:     my @CODEs;
 7854:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 7855: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 7856:     }
 7857: 
 7858:     return ($#CODEs,$CODEs[-1]);
 7859: }
 7860: 
 7861: =pod
 7862: 
 7863: =item get_codes
 7864: 
 7865:    Builds a hash which has keys of all of the valid CODEs from the selected
 7866:    set of remembered CODEs.
 7867: 
 7868:  Arguments:
 7869:   $old_name - name of the set of remembered CODEs
 7870:   $cdom     - domain of the course
 7871:   $cnum     - internal course name
 7872: 
 7873:  Returns:
 7874:   %allcodes - keys are the valid CODEs, values are all 1
 7875: 
 7876: =cut
 7877: 
 7878: sub get_codes {
 7879:     my ($old_name, $cdom, $cnum) = @_;
 7880:     if (!$old_name) {
 7881: 	$old_name=$env{'form.scantron_CODElist'};
 7882:     }
 7883:     if (!$cdom) {
 7884: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 7885:     }
 7886:     if (!$cnum) {
 7887: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 7888:     }
 7889:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 7890: 				    $cdom,$cnum);
 7891:     my %allcodes;
 7892:     if ($result{"type\0$old_name"} eq 'number') {
 7893: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 7894:     } else {
 7895: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 7896:     }
 7897:     return %allcodes;
 7898: }
 7899: 
 7900: =pod
 7901: 
 7902: =item scantron_validate_CODE
 7903: 
 7904:    Validates all scanlines in the selected file to not have any
 7905:    invalid or underspecified CODEs and that none of the codes are
 7906:    duplicated if this was requested.
 7907: 
 7908: =cut
 7909: 
 7910: sub scantron_validate_CODE {
 7911:     my ($r,$currentphase) = @_;
 7912:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7913:     if ($scantron_config{'CODElocation'} &&
 7914: 	$scantron_config{'CODEstart'} &&
 7915: 	$scantron_config{'CODElength'}) {
 7916: 	if (!defined($env{'form.scantron_CODElist'})) {
 7917: 	    &FIXME_blow_up()
 7918: 	}
 7919:     } else {
 7920: 	return (0,$currentphase+1);
 7921:     }
 7922:     
 7923:     my %usedCODEs;
 7924: 
 7925:     my %allcodes=&get_codes();
 7926: 
 7927:     my $nav_error;
 7928:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
 7929:     if ($nav_error) {
 7930:         $r->print(&navmap_errormsg());
 7931:         return(1,$currentphase);
 7932:     }
 7933: 
 7934:     my ($scanlines,$scan_data)=&scantron_getfile();
 7935:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7936: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7937: 	if ($line=~/^[\s\cz]*$/) { next; }
 7938: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7939: 						 $scan_data);
 7940: 	my $CODE=$$scan_record{'scantron.CODE'};
 7941: 	my $error=0;
 7942: 	if (!&Apache::lonnet::validCODE($CODE)) {
 7943: 	    &scantron_get_correction($r,$i,$scan_record,
 7944: 				     \%scantron_config,
 7945: 				     $line,'incorrectCODE',\%allcodes);
 7946: 	    return(1,$currentphase);
 7947: 	}
 7948: 	if (%allcodes && !exists($allcodes{$CODE}) 
 7949: 	    && !$$scan_record{'scantron.useCODE'}) {
 7950: 	    &scantron_get_correction($r,$i,$scan_record,
 7951: 				     \%scantron_config,
 7952: 				     $line,'incorrectCODE',\%allcodes);
 7953: 	    return(1,$currentphase);
 7954: 	}
 7955: 	if (exists($usedCODEs{$CODE}) 
 7956: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 7957: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 7958: 	    &scantron_get_correction($r,$i,$scan_record,
 7959: 				     \%scantron_config,
 7960: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 7961: 	    return(1,$currentphase);
 7962: 	}
 7963: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 7964:     }
 7965:     return (0,$currentphase+1);
 7966: }
 7967: 
 7968: =pod
 7969: 
 7970: =item scantron_validate_doublebubble
 7971: 
 7972:    Validates all scanlines in the selected file to not have any
 7973:    bubble lines with multiple bubbles marked.
 7974: 
 7975: =cut
 7976: 
 7977: sub scantron_validate_doublebubble {
 7978:     my ($r,$currentphase) = @_;
 7979:     #get student info
 7980:     my $classlist=&Apache::loncoursedata::get_classlist();
 7981:     my %idmap=&username_to_idmap($classlist);
 7982:     my (undef,undef,$sequence)=
 7983:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 7984: 
 7985:     #get scantron line setup
 7986:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7987:     my ($scanlines,$scan_data)=&scantron_getfile();
 7988: 
 7989:     my $navmap = Apache::lonnavmaps::navmap->new();
 7990:     unless (ref($navmap)) {
 7991:         $r->print(&navmap_errormsg());
 7992:         return(1,$currentphase);
 7993:     }
 7994:     my $map=$navmap->getResourceByUrl($sequence);
 7995:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7996:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 7997:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 7998:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 7999: 
 8000:     my $nav_error;
 8001:     if (ref($map)) {
 8002:         $randomorder = $map->randomorder();
 8003:         $randompick = $map->randompick();
 8004:         if ($randomorder || $randompick) {
 8005:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8006:             if ($nav_error) {
 8007:                 $r->print(&navmap_errormsg());
 8008:                 return(1,$currentphase);
 8009:             }
 8010:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8011:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 8012:         }
 8013:     } else {
 8014:         $r->print(&navmap_errormsg());
 8015:         return(1,$currentphase);
 8016:     }
 8017: 
 8018:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
 8019:     if ($nav_error) {
 8020:         $r->print(&navmap_errormsg());
 8021:         return(1,$currentphase);
 8022:     }
 8023: 
 8024:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8025: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8026: 	if ($line=~/^[\s\cz]*$/) { next; }
 8027: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8028: 						 $scan_data,undef,\%idmap,$randomorder,
 8029:                                                  $randompick,$sequence,\@master_seq,
 8030:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 8031:                                                  \%orderedforcode,\%respnumlookup,\%startline);
 8032: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 8033: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 8034: 				 'doublebubble',
 8035: 				 $$scan_record{'scantron.doubleerror'},
 8036:                                  $randomorder,$randompick,\%respnumlookup,\%startline);
 8037:     	return (1,$currentphase);
 8038:     }
 8039:     return (0,$currentphase+1);
 8040: }
 8041: 
 8042: 
 8043: sub scantron_get_maxbubble {
 8044:     my ($nav_error,$scantron_config) = @_;
 8045:     if (defined($env{'form.scantron_maxbubble'}) &&
 8046: 	$env{'form.scantron_maxbubble'}) {
 8047: 	&restore_bubble_lines();
 8048: 	return $env{'form.scantron_maxbubble'};
 8049:     }
 8050: 
 8051:     my (undef, undef, $sequence) =
 8052: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8053: 
 8054:     my $navmap=Apache::lonnavmaps::navmap->new();
 8055:     unless (ref($navmap)) {
 8056:         if (ref($nav_error)) {
 8057:             $$nav_error = 1;
 8058:         }
 8059:         return;
 8060:     }
 8061:     my $map=$navmap->getResourceByUrl($sequence);
 8062:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8063:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
 8064: 
 8065:     &Apache::lonxml::clear_problem_counter();
 8066: 
 8067:     my $uname       = $env{'user.name'};
 8068:     my $udom        = $env{'user.domain'};
 8069:     my $cid         = $env{'request.course.id'};
 8070:     my $total_lines = 0;
 8071:     %bubble_lines_per_response = ();
 8072:     %first_bubble_line         = ();
 8073:     %subdivided_bubble_lines   = ();
 8074:     %responsetype_per_response = ();
 8075:     %masterseq_id_responsenum  = ();
 8076: 
 8077:     my $response_number = 0;
 8078:     my $bubble_line     = 0;
 8079:     foreach my $resource (@resources) {
 8080:         my $resid = $resource->id(); 
 8081:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
 8082:                                                           $udom,undef,$bubbles_per_row);
 8083:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 8084: 	    foreach my $part_id (@{$parts}) {
 8085:                 my $lines;
 8086: 
 8087: 	        # TODO - make this a persistent hash not an array.
 8088: 
 8089:                 # optionresponse, matchresponse and rankresponse type items 
 8090:                 # render as separate sub-questions in exam mode.
 8091:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 8092:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 8093:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 8094:                     my ($numbub,$numshown);
 8095:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 8096:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 8097:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 8098:                         }
 8099:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 8100:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 8101:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 8102:                         }
 8103:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 8104:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 8105:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 8106:                         }
 8107:                     }
 8108:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 8109:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 8110:                     }
 8111:                     my $bubbles_per_row =
 8112:                         &bubblesheet_bubbles_per_row($scantron_config);
 8113:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
 8114:                     if (($numbub % $bubbles_per_row) != 0) {
 8115:                         $inner_bubble_lines++;
 8116:                     }
 8117:                     for (my $i=0; $i<$numshown; $i++) {
 8118:                         $subdivided_bubble_lines{$response_number} .= 
 8119:                             $inner_bubble_lines.',';
 8120:                     }
 8121:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 8122:                     $lines = $numshown * $inner_bubble_lines;
 8123:                 } else {
 8124:                     $lines = $analysis->{"$part_id.bubble_lines"};
 8125:                 }
 8126: 
 8127:                 $first_bubble_line{$response_number} = $bubble_line;
 8128: 	        $bubble_lines_per_response{$response_number} = $lines;
 8129:                 $responsetype_per_response{$response_number} = 
 8130:                     $analysis->{$part_id.'.type'};
 8131:                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;  
 8132: 	        $response_number++;
 8133: 
 8134: 	        $bubble_line +=  $lines;
 8135: 	        $total_lines +=  $lines;
 8136: 	    }
 8137:         }
 8138:     }
 8139:     &Apache::lonnet::delenv('scantron.');
 8140: 
 8141:     &save_bubble_lines();
 8142:     $env{'form.scantron_maxbubble'} =
 8143: 	$total_lines;
 8144:     return $env{'form.scantron_maxbubble'};
 8145: }
 8146: 
 8147: sub bubblesheet_bubbles_per_row {
 8148:     my ($scantron_config) = @_;
 8149:     my $bubbles_per_row;
 8150:     if (ref($scantron_config) eq 'HASH') {
 8151:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
 8152:     }
 8153:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
 8154:         $bubbles_per_row = 10;
 8155:     }
 8156:     return $bubbles_per_row;
 8157: }
 8158: 
 8159: sub scantron_validate_missingbubbles {
 8160:     my ($r,$currentphase) = @_;
 8161:     #get student info
 8162:     my $classlist=&Apache::loncoursedata::get_classlist();
 8163:     my %idmap=&username_to_idmap($classlist);
 8164:     my (undef,undef,$sequence)=
 8165:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8166: 
 8167:     #get scantron line setup
 8168:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8169:     my ($scanlines,$scan_data)=&scantron_getfile();
 8170: 
 8171:     my $navmap = Apache::lonnavmaps::navmap->new();
 8172:     unless (ref($navmap)) {
 8173:         $r->print(&navmap_errormsg());
 8174:         return(1,$currentphase);
 8175:     }
 8176: 
 8177:     my $map=$navmap->getResourceByUrl($sequence);
 8178:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8179:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8180:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 8181:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8182: 
 8183:     my $nav_error;
 8184:     if (ref($map)) {
 8185:         $randomorder = $map->randomorder();
 8186:         $randompick = $map->randompick();
 8187:         if ($randomorder || $randompick) {
 8188:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8189:             if ($nav_error) {
 8190:                 $r->print(&navmap_errormsg());
 8191:                 return(1,$currentphase);
 8192:             }
 8193:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8194:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 8195:         }
 8196:     } else {
 8197:         $r->print(&navmap_errormsg());
 8198:         return(1,$currentphase);
 8199:     }
 8200: 
 8201: 
 8202:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 8203:     if ($nav_error) {
 8204:         $r->print(&navmap_errormsg());
 8205:         return(1,$currentphase);
 8206:     }
 8207: 
 8208:     if (!$max_bubble) { $max_bubble=2**31; }
 8209:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8210: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8211: 	if ($line=~/^[\s\cz]*$/) { next; }
 8212: 	my $scan_record =
 8213:             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
 8214: 				     $randomorder,$randompick,$sequence,\@master_seq,
 8215:                                      \%symb_to_resource,\%grader_partids_by_symb,
 8216:                                      \%orderedforcode,\%respnumlookup,\%startline);
 8217: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 8218: 	my @to_correct;
 8219: 	
 8220: 	# Probably here's where the error is...
 8221: 
 8222: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 8223:             my $lastbubble;
 8224:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 8225:                my $question = $1;
 8226:                my $subquestion = $2;
 8227:                my ($first,$responsenum);
 8228:                if ($randomorder || $randompick) {
 8229:                    $responsenum = $respnumlookup{$question-1};
 8230:                    $first = $startline{$question-1};
 8231:                } else {
 8232:                    $responsenum = $question-1; 
 8233:                    $first = $first_bubble_line{$responsenum};
 8234:                }
 8235:                if (!defined($first)) { next; }
 8236:                my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8237:                my $subcount = 1;
 8238:                while ($subcount<$subquestion) {
 8239:                    $first += $subans[$subcount-1];
 8240:                    $subcount ++;
 8241:                }
 8242:                my $count = $subans[$subquestion-1];
 8243:                $lastbubble = $first + $count;
 8244:             } else {
 8245:                my ($first,$responsenum);
 8246:                if ($randomorder || $randompick) {
 8247:                    $responsenum = $respnumlookup{$missing-1};
 8248:                    $first = $startline{$missing-1};
 8249:                } else {
 8250:                    $responsenum = $missing-1;
 8251:                    $first = $first_bubble_line{$responsenum};
 8252:                }
 8253:                if (!defined($first)) { next; }
 8254:                $lastbubble = $first + $bubble_lines_per_response{$responsenum};
 8255:             }
 8256:             if ($lastbubble > $max_bubble) { next; }
 8257: 	    push(@to_correct,$missing);
 8258: 	}
 8259: 	if (@to_correct) {
 8260: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 8261: 				     $line,'missingbubble',\@to_correct,
 8262:                                      $randomorder,$randompick,\%respnumlookup,
 8263:                                      \%startline);
 8264: 	    return (1,$currentphase);
 8265: 	}
 8266: 
 8267:     }
 8268:     return (0,$currentphase+1);
 8269: }
 8270: 
 8271: sub hand_bubble_option {
 8272:     my (undef, undef, $sequence) =
 8273:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8274:     return if ($sequence eq '');
 8275:     my $navmap = Apache::lonnavmaps::navmap->new();
 8276:     unless (ref($navmap)) {
 8277:         return;
 8278:     }
 8279:     my $needs_hand_bubbles;
 8280:     my $map=$navmap->getResourceByUrl($sequence);
 8281:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8282:     foreach my $res (@resources) {
 8283:         if (ref($res)) {
 8284:             if ($res->is_problem()) {
 8285:                 my $partlist = $res->parts();
 8286:                 foreach my $part (@{ $partlist }) {
 8287:                     my @types = $res->responseType($part);
 8288:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
 8289:                         $needs_hand_bubbles = 1;
 8290:                         last;
 8291:                     }
 8292:                 }
 8293:             }
 8294:         }
 8295:     }
 8296:     if ($needs_hand_bubbles) {
 8297:         my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8298:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8299:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
 8300:                &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 />').
 8301:                '<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;'.
 8302:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
 8303:     }
 8304:     return;
 8305: }
 8306: 
 8307: sub scantron_process_students {
 8308:     my ($r,$symb) = @_;
 8309: 
 8310:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8311:     if (!$symb) {
 8312: 	return '';
 8313:     }
 8314:     my $default_form_data=&defaultFormData($symb);
 8315: 
 8316:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8317:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config); 
 8318:     my ($scanlines,$scan_data)=&scantron_getfile();
 8319:     my $classlist=&Apache::loncoursedata::get_classlist();
 8320:     my %idmap=&username_to_idmap($classlist);
 8321:     my $navmap=Apache::lonnavmaps::navmap->new();
 8322:     unless (ref($navmap)) {
 8323:         $r->print(&navmap_errormsg());
 8324:         return '';
 8325:     }
 8326:     my $map=$navmap->getResourceByUrl($sequence);
 8327:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8328:         %grader_randomlists_by_symb);
 8329:     if (ref($map)) {
 8330:         $randomorder = $map->randomorder();
 8331:         $randompick = $map->randompick();
 8332:     } else {
 8333:         $r->print(&navmap_errormsg());
 8334:         return '';
 8335:     }
 8336:     my $nav_error;
 8337:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8338:     if ($randomorder || $randompick) {
 8339:         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8340:         if ($nav_error) {
 8341:             $r->print(&navmap_errormsg());
 8342:             return '';
 8343:         }
 8344:     }
 8345:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8346:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 8347: 
 8348:     my ($uname,$udom);
 8349:     my $result= <<SCANTRONFORM;
 8350: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 8351:   <input type="hidden" name="command" value="scantron_configphase" />
 8352:   $default_form_data
 8353: SCANTRONFORM
 8354:     $r->print($result);
 8355: 
 8356:     my @delayqueue;
 8357:     my (%completedstudents,%scandata);
 8358:     
 8359:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 8360:     my $count=&get_todo_count($scanlines,$scan_data);
 8361:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 8362:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
 8363:     $r->print('<br />');
 8364:     my $start=&Time::HiRes::time();
 8365:     my $i=-1;
 8366:     my $started;
 8367: 
 8368:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 8369:     if ($nav_error) {
 8370:         $r->print(&navmap_errormsg());
 8371:         return '';
 8372:     }
 8373: 
 8374:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 8375:     # the user and return.
 8376: 
 8377:     if ($ssi_error) {
 8378: 	$r->print("</form>");
 8379: 	&ssi_print_error($r);
 8380:         &Apache::lonnet::remove_lock($lock);
 8381: 	return '';		# Dunno why the other returns return '' rather than just returning.
 8382:     }
 8383: 
 8384:     my %lettdig = &letter_to_digits();
 8385:     my $numletts = scalar(keys(%lettdig));
 8386:     my %orderedforcode;
 8387: 
 8388:     while ($i<$scanlines->{'count'}) {
 8389:  	($uname,$udom)=('','');
 8390:  	$i++;
 8391:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8392:  	if ($line=~/^[\s\cz]*$/) { next; }
 8393: 	if ($started) {
 8394: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
 8395: 	}
 8396: 	$started=1;
 8397:         my %respnumlookup = ();
 8398:         my %startline = ();
 8399:         my $total;
 8400:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8401:                                                  $scan_data,undef,\%idmap,$randomorder,
 8402:                                                  $randompick,$sequence,\@master_seq,
 8403:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 8404:                                                  \%orderedforcode,\%respnumlookup,\%startline,
 8405:                                                  \$total);
 8406:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 8407:  					      \%idmap,$i)) {
 8408:   	    &scantron_add_delay(\@delayqueue,$line,
 8409:  				'Unable to find a student that matches',1);
 8410:  	    next;
 8411:   	}
 8412:  	if (exists $completedstudents{$uname}) {
 8413:  	    &scantron_add_delay(\@delayqueue,$line,
 8414:  				'Student '.$uname.' has multiple sheets',2);
 8415:  	    next;
 8416:  	}
 8417:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 8418:         my $user = $uname.':'.$usec;
 8419:   	($uname,$udom)=split(/:/,$uname);
 8420: 
 8421:         my $scancode;
 8422:         if ((exists($scan_record->{'scantron.CODE'})) &&
 8423:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 8424:             $scancode = $scan_record->{'scantron.CODE'};
 8425:         } else {
 8426:             $scancode = '';
 8427:         }
 8428: 
 8429:         my @mapresources = @resources;
 8430:         if ($randomorder || $randompick) {
 8431:             @mapresources = 
 8432:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
 8433:                              \%orderedforcode);
 8434:         }
 8435:         my (%partids_by_symb,$res_error);
 8436:         foreach my $resource (@mapresources) {
 8437:             my $ressymb;
 8438:             if (ref($resource)) {
 8439:                 $ressymb = $resource->symb();
 8440:             } else {
 8441:                 $res_error = 1;
 8442:                 last;
 8443:             }
 8444:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 8445:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 8446:                 my ($analysis,$parts) =
 8447:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 8448:                                               $uname,$udom,undef,$bubbles_per_row);
 8449:                 $partids_by_symb{$ressymb} = $parts;
 8450:             } else {
 8451:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
 8452:             }
 8453:         }
 8454: 
 8455:         if ($res_error) {
 8456:             &scantron_add_delay(\@delayqueue,$line,
 8457:                                 'An error occurred while grading student '.$uname,2);
 8458:             next;
 8459:         }
 8460: 
 8461: 	&Apache::lonxml::clear_problem_counter();
 8462:   	&Apache::lonnet::appenv($scan_record);
 8463: 
 8464: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 8465: 	    &scantron_putfile($scanlines,$scan_data);
 8466: 	}
 8467: 	
 8468:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 8469:                                    \@mapresources,\%partids_by_symb,
 8470:                                    $bubbles_per_row,$randomorder,$randompick,
 8471:                                    \%respnumlookup,\%startline) 
 8472:             eq 'ssi_error') {
 8473:             $ssi_error = 0; # So end of handler error message does not trigger.
 8474:             $r->print("</form>");
 8475:             &ssi_print_error($r);
 8476:             &Apache::lonnet::remove_lock($lock);
 8477:             return '';      # Why return ''?  Beats me.
 8478:         }
 8479: 
 8480:         if (($scancode) && ($randomorder || $randompick)) {
 8481:             my $parmresult =
 8482:                 &Apache::lonparmset::storeparm_by_symb($symb,
 8483:                                                        '0_examcode',2,$scancode,
 8484:                                                        'string_examcode',$uname,
 8485:                                                        $udom);
 8486:         }
 8487: 	$completedstudents{$uname}={'line'=>$line};
 8488:         if ($env{'form.verifyrecord'}) {
 8489:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 8490:             if ($randompick) {
 8491:                 if ($total) {
 8492:                     $lastpos = $total*$scantron_config{'Qlength'};
 8493:                 }
 8494:             }
 8495: 
 8496:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 8497:             chomp($studentdata);
 8498:             $studentdata =~ s/\r$//;
 8499:             my $studentrecord = '';
 8500:             my $counter = -1;
 8501:             foreach my $resource (@mapresources) {
 8502:                 my $ressymb = $resource->symb();
 8503:                 ($counter,my $recording) =
 8504:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 8505:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
 8506:                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
 8507:                                              $randompick,\%respnumlookup,\%startline);
 8508:                 $studentrecord .= $recording;
 8509:             }
 8510:             if ($studentrecord ne $studentdata) {
 8511:                 &Apache::lonxml::clear_problem_counter();
 8512:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 8513:                                            \@mapresources,\%partids_by_symb,
 8514:                                            $bubbles_per_row,$randomorder,$randompick,
 8515:                                            \%respnumlookup,\%startline) 
 8516:                     eq 'ssi_error') {
 8517:                     $ssi_error = 0; # So end of handler error message does not trigger.
 8518:                     $r->print("</form>");
 8519:                     &ssi_print_error($r);
 8520:                     &Apache::lonnet::remove_lock($lock);
 8521:                     delete($completedstudents{$uname});
 8522:                     return '';
 8523:                 }
 8524:                 $counter = -1;
 8525:                 $studentrecord = '';
 8526:                 foreach my $resource (@mapresources) {
 8527:                     my $ressymb = $resource->symb();
 8528:                     ($counter,my $recording) =
 8529:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 8530:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 8531:                                                  \%scantron_config,\%lettdig,$numletts,
 8532:                                                  $randomorder,$randompick,\%respnumlookup,
 8533:                                                  \%startline);
 8534:                     $studentrecord .= $recording;
 8535:                 }
 8536:                 if ($studentrecord ne $studentdata) {
 8537:                     $r->print('<p><span class="LC_warning">');
 8538:                     if ($scancode eq '') {
 8539:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
 8540:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 8541:                     } else {
 8542:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
 8543:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 8544:                     }
 8545:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 8546:                               &Apache::loncommon::start_data_table_header_row()."\n".
 8547:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 8548:                               &Apache::loncommon::end_data_table_header_row()."\n".
 8549:                               &Apache::loncommon::start_data_table_row().
 8550:                               '<td>'.&mt('Bubblesheet').'</td>'.
 8551:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
 8552:                               &Apache::loncommon::end_data_table_row().
 8553:                               &Apache::loncommon::start_data_table_row().
 8554:                               '<td>'.&mt('Stored submissions').'</td>'.
 8555:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
 8556:                               &Apache::loncommon::end_data_table_row().
 8557:                               &Apache::loncommon::end_data_table().'</p>');
 8558:                 } else {
 8559:                     $r->print('<br /><span class="LC_warning">'.
 8560:                              &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 />'.
 8561:                              &mt("As a consequence, this user's submission history records two tries.").
 8562:                                  '</span><br />');
 8563:                 }
 8564:             }
 8565:         }
 8566:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 8567:     } continue {
 8568: 	&Apache::lonxml::clear_problem_counter();
 8569: 	&Apache::lonnet::delenv('scantron.');
 8570:     }
 8571:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 8572:     &Apache::lonnet::remove_lock($lock);
 8573: #    my $lasttime = &Time::HiRes::time()-$start;
 8574: #    $r->print("<p>took $lasttime</p>");
 8575: 
 8576:     $r->print("</form>");
 8577:     return '';
 8578: }
 8579: 
 8580: sub graders_resources_pass {
 8581:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
 8582:         $bubbles_per_row) = @_;
 8583:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
 8584:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
 8585:         foreach my $resource (@{$resources}) {
 8586:             my $ressymb = $resource->symb();
 8587:             my ($analysis,$parts) =
 8588:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
 8589:                                           $env{'user.name'},$env{'user.domain'},
 8590:                                           1,$bubbles_per_row);
 8591:             $grader_partids_by_symb->{$ressymb} = $parts;
 8592:             if (ref($analysis) eq 'HASH') {
 8593:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 8594:                     $grader_randomlists_by_symb->{$ressymb} =
 8595:                         $analysis->{'parts_withrandomlist'};
 8596:                 }
 8597:             }
 8598:         }
 8599:     }
 8600:     return;
 8601: }
 8602: 
 8603: =pod
 8604: 
 8605: =item users_order
 8606: 
 8607:   Returns array of resources in current map, ordered based on either CODE,
 8608:   if this is a CODEd exam, or based on student's identity if this is a 
 8609:   "NAMEd" exam.
 8610: 
 8611:   Should be used when randomorder and/or randompick applied when the 
 8612:   corresponding exam was printed, prior to students completing bubblesheets 
 8613:   for the version of the exam the student received.
 8614: 
 8615: =cut
 8616: 
 8617: sub users_order  {
 8618:     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
 8619:     my @mapresources;
 8620:     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
 8621:         return @mapresources;
 8622:     }
 8623:     if ($scancode) {
 8624:         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
 8625:             @mapresources = @{$orderedforcode->{$scancode}};
 8626:         } else {
 8627:             $env{'form.CODE'} = $scancode;
 8628:             my $actual_seq =
 8629:                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 8630:                                                                $master_seq,
 8631:                                                                $user,$scancode,1);
 8632:             if (ref($actual_seq) eq 'ARRAY') {
 8633:                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
 8634:                 if (ref($orderedforcode) eq 'HASH') {
 8635:                     if (@mapresources > 0) { 
 8636:                         $orderedforcode->{$scancode} = \@mapresources;
 8637:                     }
 8638:                 }
 8639:             }
 8640:             delete($env{'form.CODE'});
 8641:         }
 8642:     } else {
 8643:         my $actual_seq =
 8644:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 8645:                                                            $master_seq,
 8646:                                                            $user,undef,1);
 8647:         if (ref($actual_seq) eq 'ARRAY') {
 8648:             @mapresources = 
 8649:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
 8650:         }
 8651:     }
 8652:     return @mapresources;
 8653: }
 8654: 
 8655: sub grade_student_bubbles {
 8656:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
 8657:         $randomorder,$randompick,$respnumlookup,$startline) = @_;
 8658:     my $uselookup = 0;
 8659:     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
 8660:         (ref($startline) eq 'HASH')) {
 8661:         $uselookup = 1;
 8662:     }
 8663: 
 8664:     if (ref($resources) eq 'ARRAY') {
 8665:         my $count = 0;
 8666:         foreach my $resource (@{$resources}) {
 8667:             my $ressymb = $resource->symb();
 8668:             my %form = ('submitted'      => 'scantron',
 8669:                         'grade_target'   => 'grade',
 8670:                         'grade_username' => $uname,
 8671:                         'grade_domain'   => $udom,
 8672:                         'grade_courseid' => $env{'request.course.id'},
 8673:                         'grade_symb'     => $ressymb,
 8674:                         'CODE'           => $scancode
 8675:                        );
 8676:             if ($bubbles_per_row ne '') {
 8677:                 $form{'bubbles_per_row'} = $bubbles_per_row;
 8678:             }
 8679:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
 8680:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
 8681:             }
 8682:             if (ref($parts) eq 'HASH') {
 8683:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 8684:                     foreach my $part (@{$parts->{$ressymb}}) {
 8685:                         if ($uselookup) {
 8686:                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
 8687:                         } else {
 8688:                             $form{'scantron_questnum_start.'.$part} =
 8689:                                 1+$env{'form.scantron.first_bubble_line.'.$count};
 8690:                         }
 8691:                         $count++;
 8692:                     }
 8693:                 }
 8694:             }
 8695:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 8696:             return 'ssi_error' if ($ssi_error);
 8697:             last if (&Apache::loncommon::connection_aborted($r));
 8698:         }
 8699:     }
 8700:     return;
 8701: }
 8702: 
 8703: sub scantron_upload_scantron_data {
 8704:     my ($r,$symb)=@_;
 8705:     my $dom = $env{'request.role.domain'};
 8706:     my $domdesc = &Apache::lonnet::domain($dom,'description');
 8707:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
 8708:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 8709: 							  'domainid',
 8710: 							  'coursename',$dom);
 8711:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
 8712:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
 8713:     my $default_form_data=&defaultFormData($symb);
 8714:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
 8715:     &js_escape(\$nofile_alert);
 8716:     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.");
 8717:     &js_escape(\$nocourseid_alert);
 8718:     $r->print(&Apache::lonhtmlcommon::scripttag('
 8719:     function checkUpload(formname) {
 8720: 	if (formname.upfile.value == "") {
 8721: 	    alert("'.$nofile_alert.'");
 8722: 	    return false;
 8723: 	}
 8724:         if (formname.courseid.value == "") {
 8725:             alert("'.$nocourseid_alert.'");
 8726:             return false;
 8727:         }
 8728: 	formname.submit();
 8729:     }
 8730: 
 8731:     function ToSyllabus() {
 8732:         var cdom = '."'$dom'".';
 8733:         var cnum = document.rules.courseid.value;
 8734:         if (cdom == "" || cdom == null) {
 8735:             return;
 8736:         }
 8737:         if (cnum == "" || cnum == null) {
 8738:            return;
 8739:         }
 8740:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
 8741:                             "height=350,width=350,scrollbars=yes,menubar=no");
 8742:         return;
 8743:     }
 8744: 
 8745: '));
 8746:     $r->print('
 8747: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
 8748: 
 8749: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 8750: '.$default_form_data.
 8751:   &Apache::lonhtmlcommon::start_pick_box().
 8752:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
 8753:   '<input name="courseid" type="text" size="30" />'.$select_link.
 8754:   &Apache::lonhtmlcommon::row_closure().
 8755:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
 8756:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
 8757:   &Apache::lonhtmlcommon::row_closure().
 8758:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
 8759:   '<input name="domainid" type="hidden" />'.$domdesc.
 8760:   &Apache::lonhtmlcommon::row_closure().
 8761:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
 8762:   '<input type="file" name="upfile" size="50" />'.
 8763:   &Apache::lonhtmlcommon::row_closure(1).
 8764:   &Apache::lonhtmlcommon::end_pick_box().'<br />
 8765: 
 8766: <input name="command" value="scantronupload_save" type="hidden" />
 8767: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 8768: </form>
 8769: ');
 8770:     return '';
 8771: }
 8772: 
 8773: 
 8774: sub scantron_upload_scantron_data_save {
 8775:     my($r,$symb)=@_;
 8776:     my $doanotherupload=
 8777: 	'<br /><form action="/adm/grades" method="post">'."\n".
 8778: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 8779: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 8780: 	'</form>'."\n";
 8781:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 8782: 	!&Apache::lonnet::allowed('usc',
 8783: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 8784: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
 8785: 	unless ($symb) {
 8786: 	    $r->print($doanotherupload);
 8787: 	}
 8788: 	return '';
 8789:     }
 8790:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 8791:     my $uploadedfile;
 8792:     $r->print('<p>'.&mt('Uploading file to [_1]','"'.$coursedata{'description'}.'"').'</p>');
 8793:     if (length($env{'form.upfile'}) < 2) {
 8794:         $r->print(
 8795:             &Apache::lonhtmlcommon::confirm_success(
 8796:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
 8797:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
 8798:     } else {
 8799:         my $result = 
 8800:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
 8801:                                             $env{'form.courseid'},$env{'form.domainid'});
 8802:         if ($result =~ m{^/uploaded/}) {
 8803:             $r->print(
 8804:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
 8805:                 &mt('Uploaded [_1] bytes of data into location: [_2]',
 8806:                         (length($env{'form.upfile'})-1),
 8807:                         '<span class="LC_filename">'.$result.'</span>'));
 8808:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
 8809:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
 8810:                                                        $env{'form.courseid'},$uploadedfile));
 8811:         } else {
 8812:             $r->print(
 8813:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
 8814:                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
 8815:                           $result,
 8816: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 8817: 	}
 8818:     }
 8819:     if ($symb) {
 8820: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
 8821:     } else {
 8822: 	$r->print($doanotherupload);
 8823:     }
 8824:     return '';
 8825: }
 8826: 
 8827: sub validate_uploaded_scantron_file {
 8828:     my ($cdom,$cname,$fname) = @_;
 8829:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
 8830:     my @lines;
 8831:     if ($scanlines ne '-1') {
 8832:         @lines=split("\n",$scanlines,-1);
 8833:     }
 8834:     my $output;
 8835:     if (@lines) {
 8836:         my (%counts,$max_match_format);
 8837:         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
 8838:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
 8839:         my %idmap = &username_to_idmap($classlist);
 8840:         foreach my $key (keys(%idmap)) {
 8841:             my $lckey = lc($key);
 8842:             $idmap{$lckey} = $idmap{$key};
 8843:         }
 8844:         my %unique_formats;
 8845:         my @formatlines = &get_scantronformat_file();
 8846:         foreach my $line (@formatlines) {
 8847:             chomp($line);
 8848:             my @config = split(/:/,$line);
 8849:             my $idstart = $config[5];
 8850:             my $idlength = $config[6];
 8851:             if (($idstart ne '') && ($idlength > 0)) {
 8852:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
 8853:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
 8854:                 } else {
 8855:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
 8856:                 }
 8857:             }
 8858:         }
 8859:         foreach my $key (keys(%unique_formats)) {
 8860:             my ($idstart,$idlength) = split(':',$key);
 8861:             %{$counts{$key}} = (
 8862:                                'found'   => 0,
 8863:                                'total'   => 0,
 8864:                               );
 8865:             foreach my $line (@lines) {
 8866:                 next if ($line =~ /^#/);
 8867:                 next if ($line =~ /^[\s\cz]*$/);
 8868:                 my $id = substr($line,$idstart-1,$idlength);
 8869:                 $id = lc($id);
 8870:                 if (exists($idmap{$id})) {
 8871:                     $counts{$key}{'found'} ++;
 8872:                 }
 8873:                 $counts{$key}{'total'} ++;
 8874:             }
 8875:             if ($counts{$key}{'total'}) {
 8876:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
 8877:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
 8878:                     $max_match_pct = $percent_match;
 8879:                     $max_match_format = $key;
 8880:                     $found_match_count = $counts{$key}{'found'};
 8881:                     $max_match_count = $counts{$key}{'total'};
 8882:                 }
 8883:             }
 8884:         }
 8885:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
 8886:             my $format_descs;
 8887:             my $numwithformat = @{$unique_formats{$max_match_format}};
 8888:             for (my $i=0; $i<$numwithformat; $i++) {
 8889:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
 8890:                 if ($i<$numwithformat-2) {
 8891:                     $format_descs .= '"<i>'.$desc.'</i>", ';
 8892:                 } elsif ($i==$numwithformat-2) {
 8893:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
 8894:                 } elsif ($i==$numwithformat-1) {
 8895:                     $format_descs .= '"<i>'.$desc.'</i>"';
 8896:                 }
 8897:             }
 8898:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
 8899:             $output .= '<br />';
 8900:             if ($found_match_count == $max_match_count) {
 8901:                 # 100% matching entries
 8902:                 $output .= &Apache::lonhtmlcommon::confirm_success(
 8903:                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
 8904:                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
 8905:                 &mt('Comparison of student IDs in the uploaded file with'.
 8906:                     ' the course roster found matches for [_1] of the [_2] entries'.
 8907:                     ' in the file (for the format defined for [_3]).',
 8908:                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
 8909:             } else {
 8910:                 # Not all entries matching? -> Show warning and additional info
 8911:                 $output .=
 8912:                     &Apache::lonhtmlcommon::confirm_success(
 8913:                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
 8914:                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
 8915:                         &mt('Not all entries could be matched!'),1).'<br />'.
 8916:                     &mt('Comparison of student IDs in the uploaded file with'.
 8917:                         ' the course roster found matches for [_1] of the [_2] entries'.
 8918:                         ' in the file (for the format defined for [_3]).',
 8919:                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
 8920:                     '<p class="LC_info">'.
 8921:                     &mt('A low percentage of matches results from one of the following:').
 8922:                     '</p><ul>'.
 8923:                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
 8924:                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
 8925:                                '<i>'.$cdom.'</i>').'</li>'.
 8926:                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
 8927:                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
 8928:                     '</ul>';
 8929:             }
 8930:         }
 8931:     } else {
 8932:         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
 8933:     }
 8934:     return $output;
 8935: }
 8936: 
 8937: sub valid_file {
 8938:     my ($requested_file)=@_;
 8939:     foreach my $filename (sort(&scantron_filenames())) {
 8940: 	if ($requested_file eq $filename) { return 1; }
 8941:     }
 8942:     return 0;
 8943: }
 8944: 
 8945: sub scantron_download_scantron_data {
 8946:     my ($r,$symb)=@_;
 8947:     my $default_form_data=&defaultFormData($symb);
 8948:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 8949:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8950:     my $file=$env{'form.scantron_selectfile'};
 8951:     if (! &valid_file($file)) {
 8952: 	$r->print('
 8953: 	<p>
 8954: 	    '.&mt('The requested filename was invalid.').'
 8955:         </p>
 8956: ');
 8957: 	return;
 8958:     }
 8959:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 8960:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 8961:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 8962:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 8963:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 8964:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 8965:     $r->print('
 8966:     <p>
 8967: 	'.&mt('[_1]Original[_2] file as uploaded by the bubblesheet scanning office.',
 8968: 	      '<a href="'.$orig.'">','</a>').'
 8969:     </p>
 8970:     <p>
 8971: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 8972: 	      '<a href="'.$corrected.'">','</a>').'
 8973:     </p>
 8974:     <p>
 8975: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 8976: 	      '<a href="'.$skipped.'">','</a>').'
 8977:     </p>
 8978: ');
 8979:     return '';
 8980: }
 8981: 
 8982: sub checkscantron_results {
 8983:     my ($r,$symb) = @_;
 8984:     if (!$symb) {return '';}
 8985:     my $cid = $env{'request.course.id'};
 8986:     my %lettdig = &letter_to_digits();
 8987:     my $numletts = scalar(keys(%lettdig));
 8988:     my $cnum = $env{'course.'.$cid.'.num'};
 8989:     my $cdom = $env{'course.'.$cid.'.domain'};
 8990:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8991:     my %record;
 8992:     my %scantron_config =
 8993:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
 8994:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8995:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
 8996:     my $classlist=&Apache::loncoursedata::get_classlist();
 8997:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 8998:     my $navmap=Apache::lonnavmaps::navmap->new();
 8999:     unless (ref($navmap)) {
 9000:         $r->print(&navmap_errormsg());
 9001:         return '';
 9002:     }
 9003:     my $map=$navmap->getResourceByUrl($sequence);
 9004:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 9005:         %grader_randomlists_by_symb,%orderedforcode);
 9006:     if (ref($map)) { 
 9007:         $randomorder=$map->randomorder();
 9008:         $randompick=$map->randompick();
 9009:     }
 9010:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 9011:     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 9012:     if ($nav_error) {
 9013:         $r->print(&navmap_errormsg());
 9014:         return '';
 9015:     }
 9016:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 9017:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 9018:     my ($uname,$udom);
 9019:     my (%scandata,%lastname,%bylast);
 9020:     $r->print('
 9021: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 9022: 
 9023:     my @delayqueue;
 9024:     my %completedstudents;
 9025: 
 9026:     my $count=&get_todo_count($scanlines,$scan_data);
 9027:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 9028:     my ($username,$domain,$started);
 9029:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 9030:     if ($nav_error) {
 9031:         $r->print(&navmap_errormsg());
 9032:         return '';
 9033:     }
 9034: 
 9035:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
 9036:     my $start=&Time::HiRes::time();
 9037:     my $i=-1;
 9038: 
 9039:     while ($i<$scanlines->{'count'}) {
 9040:         ($username,$domain,$uname)=('','','');
 9041:         $i++;
 9042:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 9043:         if ($line=~/^[\s\cz]*$/) { next; }
 9044:         if ($started) {
 9045:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
 9046:         }
 9047:         $started=1;
 9048:         my $scan_record=
 9049:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 9050:                                                      $scan_data);
 9051:         unless ($uname=&scantron_find_student($scan_record,$scan_data,
 9052:                                               \%idmap,$i)) {
 9053:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 9054:                                 'Unable to find a student that matches',1);
 9055:             next;
 9056:         }
 9057:         if (exists $completedstudents{$uname}) {
 9058:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 9059:                                 'Student '.$uname.' has multiple sheets',2);
 9060:             next;
 9061:         }
 9062:         my $pid = $scan_record->{'scantron.ID'};
 9063:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 9064:         push(@{$bylast{$lastname{$pid}}},$pid);
 9065:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 9066:         my $user = $uname.':'.$usec;
 9067:         ($username,$domain)=split(/:/,$uname);
 9068: 
 9069:         my $scancode;
 9070:         if ((exists($scan_record->{'scantron.CODE'})) &&
 9071:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 9072:             $scancode = $scan_record->{'scantron.CODE'};
 9073:         } else {
 9074:             $scancode = '';
 9075:         }
 9076: 
 9077:         my @mapresources = @resources;
 9078:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 9079:         my %respnumlookup=();
 9080:         my %startline=();
 9081:         if ($randomorder || $randompick) {
 9082:             @mapresources =
 9083:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
 9084:                              \%orderedforcode);
 9085:             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
 9086:                                              $scan_record,\@master_seq,\%symb_to_resource,
 9087:                                              \%grader_partids_by_symb,\%orderedforcode,
 9088:                                              \%respnumlookup,\%startline);
 9089:             if ($randompick && $total) {
 9090:                 $lastpos = $total*$scantron_config{'Qlength'};
 9091:             }
 9092:         }
 9093:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 9094:         chomp($scandata{$pid});
 9095:         $scandata{$pid} =~ s/\r$//;
 9096: 
 9097:         my $counter = -1;
 9098:         foreach my $resource (@mapresources) {
 9099:             my $parts;
 9100:             my $ressymb = $resource->symb();
 9101:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 9102:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 9103:                 (my $analysis,$parts) =
 9104:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 9105:                                               $username,$domain,undef,
 9106:                                               $bubbles_per_row);
 9107:             } else {
 9108:                 $parts = $grader_partids_by_symb{$ressymb};
 9109:             }
 9110:             ($counter,my $recording) =
 9111:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
 9112:                                          $scandata{$pid},$parts,
 9113:                                          \%scantron_config,\%lettdig,$numletts,
 9114:                                          $randomorder,$randompick,
 9115:                                          \%respnumlookup,\%startline);
 9116:             $record{$pid} .= $recording;
 9117:         }
 9118:     }
 9119:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 9120:     $r->print('<br />');
 9121:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 9122:     $passed = 0;
 9123:     $failed = 0;
 9124:     $numstudents = 0;
 9125:     foreach my $last (sort(keys(%bylast))) {
 9126:         if (ref($bylast{$last}) eq 'ARRAY') {
 9127:             foreach my $pid (sort(@{$bylast{$last}})) {
 9128:                 my $showscandata = $scandata{$pid};
 9129:                 my $showrecord = $record{$pid};
 9130:                 $showscandata =~ s/\s/&nbsp;/g;
 9131:                 $showrecord =~ s/\s/&nbsp;/g;
 9132:                 if ($scandata{$pid} eq $record{$pid}) {
 9133:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 9134:                     $okstudents .= '<tr class="'.$css_class.'">'.
 9135: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 9136: '</tr>'."\n".
 9137: '<tr class="'.$css_class.'">'."\n".
 9138: '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
 9139:                     $passed ++;
 9140:                 } else {
 9141:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
 9142:                     $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".
 9143: '</tr>'."\n".
 9144: '<tr class="'.$css_class.'">'."\n".
 9145: '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
 9146: '</tr>'."\n";
 9147:                     $failed ++;
 9148:                 }
 9149:                 $numstudents ++;
 9150:             }
 9151:         }
 9152:     }
 9153:     $r->print(
 9154:         '<p>'
 9155:        .&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).',
 9156:             '<b>',
 9157:             $numstudents,
 9158:             '</b>',
 9159:             $env{'form.scantron_maxbubble'})
 9160:        .'</p>'
 9161:     );
 9162:     $r->print('<p>'
 9163:              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
 9164:              .'<br />'
 9165:              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
 9166:              .'</p>'
 9167:     );
 9168:     if ($passed) {
 9169:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
 9170:         $r->print(&Apache::loncommon::start_data_table()."\n".
 9171:                  &Apache::loncommon::start_data_table_header_row()."\n".
 9172:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 9173:                  &Apache::loncommon::end_data_table_header_row()."\n".
 9174:                  $okstudents."\n".
 9175:                  &Apache::loncommon::end_data_table().'<br />');
 9176:     }
 9177:     if ($failed) {
 9178:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
 9179:         $r->print(&Apache::loncommon::start_data_table()."\n".
 9180:                  &Apache::loncommon::start_data_table_header_row()."\n".
 9181:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 9182:                  &Apache::loncommon::end_data_table_header_row()."\n".
 9183:                  $badstudents."\n".
 9184:                  &Apache::loncommon::end_data_table()).'<br />'.
 9185:                  &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.');  
 9186:     }
 9187:     $r->print('</form><br />');
 9188:     return;
 9189: }
 9190: 
 9191: sub verify_scantron_grading {
 9192:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
 9193:         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
 9194:         $respnumlookup,$startline) = @_;
 9195:     my ($record,%expected,%startpos);
 9196:     return ($counter,$record) if (!ref($resource));
 9197:     return ($counter,$record) if (!$resource->is_problem());
 9198:     my $symb = $resource->symb();
 9199:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
 9200:     foreach my $part_id (@{$partids}) {
 9201:         $counter ++;
 9202:         $expected{$part_id} = 0;
 9203:         my $respnum = $counter;
 9204:         if ($randomorder || $randompick) {
 9205:             $respnum = $respnumlookup->{$counter};
 9206:             $startpos{$part_id} = $startline->{$counter} + 1;
 9207:         } else {
 9208:             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
 9209:         }
 9210:         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
 9211:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
 9212:             foreach my $item (@sub_lines) {
 9213:                 $expected{$part_id} += $item;
 9214:             }
 9215:         } else {
 9216:             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
 9217:         }
 9218:     }
 9219:     if ($symb) {
 9220:         my %recorded;
 9221:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
 9222:         if ($returnhash{'version'}) {
 9223:             my %lasthash=();
 9224:             my $version;
 9225:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 9226:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 9227:                     $lasthash{$key}=$returnhash{$version.':'.$key};
 9228:                 }
 9229:             }
 9230:             foreach my $key (keys(%lasthash)) {
 9231:                 if ($key =~ /\.scantron$/) {
 9232:                     my $value = &unescape($lasthash{$key});
 9233:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
 9234:                     if ($value eq '') {
 9235:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
 9236:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
 9237:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9238:                             }
 9239:                         }
 9240:                     } else {
 9241:                         my @tocheck;
 9242:                         my @items = split(//,$value);
 9243:                         if (($scantron_config->{'Qon'} eq 'letter') ||
 9244:                             ($scantron_config->{'Qon'} eq 'number')) {
 9245:                             if (@items < $expected{$part_id}) {
 9246:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
 9247:                                 my @singles = split(//,$fragment);
 9248:                                 foreach my $pos (@singles) {
 9249:                                     if ($pos eq ' ') {
 9250:                                         push(@tocheck,$pos);
 9251:                                     } else {
 9252:                                         my $next = shift(@items);
 9253:                                         push(@tocheck,$next);
 9254:                                     }
 9255:                                 }
 9256:                             } else {
 9257:                                 @tocheck = @items;
 9258:                             }
 9259:                             foreach my $letter (@tocheck) {
 9260:                                 if ($scantron_config->{'Qon'} eq 'letter') {
 9261:                                     if ($letter !~ /^[A-J]$/) {
 9262:                                         $letter = $scantron_config->{'Qoff'};
 9263:                                     }
 9264:                                     $recorded{$part_id} .= $letter;
 9265:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
 9266:                                     my $digit;
 9267:                                     if ($letter !~ /^[A-J]$/) {
 9268:                                         $digit = $scantron_config->{'Qoff'};
 9269:                                     } else {
 9270:                                         $digit = $lettdig->{$letter};
 9271:                                     }
 9272:                                     $recorded{$part_id} .= $digit;
 9273:                                 }
 9274:                             }
 9275:                         } else {
 9276:                             @tocheck = @items;
 9277:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
 9278:                                 my $curr_sub = shift(@tocheck);
 9279:                                 my $digit;
 9280:                                 if ($curr_sub =~ /^[A-J]$/) {
 9281:                                     $digit = $lettdig->{$curr_sub}-1;
 9282:                                 }
 9283:                                 if ($curr_sub eq 'J') {
 9284:                                     $digit += scalar($numletts);
 9285:                                 }
 9286:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 9287:                                     if ($j == $digit) {
 9288:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
 9289:                                     } else {
 9290:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9291:                                     }
 9292:                                 }
 9293:                             }
 9294:                         }
 9295:                     }
 9296:                 }
 9297:             }
 9298:         }
 9299:         foreach my $part_id (@{$partids}) {
 9300:             if ($recorded{$part_id} eq '') {
 9301:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
 9302:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 9303:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9304:                     }
 9305:                 }
 9306:             }
 9307:             $record .= $recorded{$part_id};
 9308:         }
 9309:     }
 9310:     return ($counter,$record);
 9311: }
 9312: 
 9313: sub letter_to_digits {
 9314:     my %lettdig = (
 9315:                     A => 1,
 9316:                     B => 2,
 9317:                     C => 3,
 9318:                     D => 4,
 9319:                     E => 5,
 9320:                     F => 6,
 9321:                     G => 7,
 9322:                     H => 8,
 9323:                     I => 9,
 9324:                     J => 0,
 9325:                   );
 9326:     return %lettdig;
 9327: }
 9328: 
 9329: 
 9330: #-------- end of section for handling grading scantron forms -------
 9331: #
 9332: #-------------------------------------------------------------------
 9333: 
 9334: #-------------------------- Menu interface -------------------------
 9335: #
 9336: #--- Href with symb and command ---
 9337: 
 9338: sub href_symb_cmd {
 9339:     my ($symb,$cmd)=@_;
 9340:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
 9341: }
 9342: 
 9343: sub grading_menu {
 9344:     my ($request,$symb) = @_;
 9345:     if (!$symb) {return '';}
 9346: 
 9347:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 9348:                   'command'=>'individual');
 9349:     
 9350:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9351: 
 9352:     $fields{'command'}='ungraded';
 9353:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9354: 
 9355:     $fields{'command'}='table';
 9356:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9357: 
 9358:     $fields{'command'}='all_for_one';
 9359:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9360: 
 9361:     $fields{'command'}='downloadfilesselect';
 9362:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9363: 
 9364:     $fields{'command'} = 'csvform';
 9365:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9366:     
 9367:     $fields{'command'} = 'processclicker';
 9368:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9369:     
 9370:     $fields{'command'} = 'scantron_selectphase';
 9371:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9372: 
 9373:     $fields{'command'} = 'initialverifyreceipt';
 9374:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9375:     
 9376:     my @menu = ({	categorytitle=>'Hand Grading',
 9377:             items =>[
 9378:                         {	linktext => 'Select individual students to grade',
 9379:                     		url => $url1a,
 9380:                     		permission => 'F',
 9381:                     		icon => 'grade_students.png',
 9382:                     		linktitle => 'Grade current resource for a selection of students.'
 9383:                         }, 
 9384:                         {       linktext => 'Grade ungraded submissions.',
 9385:                                 url => $url1b,
 9386:                                 permission => 'F',
 9387:                                 icon => 'ungrade_sub.png',
 9388:                                 linktitle => 'Grade all submissions that have not been graded yet.'
 9389:                         },
 9390: 
 9391:                         {       linktext => 'Grading table',
 9392:                                 url => $url1c,
 9393:                                 permission => 'F',
 9394:                                 icon => 'grading_table.png',
 9395:                                 linktitle => 'Grade current resource for all students.'
 9396:                         },
 9397:                         {       linktext => 'Grade page/folder for one student',
 9398:                                 url => $url1d,
 9399:                                 permission => 'F',
 9400:                                 icon => 'grade_PageFolder.png',
 9401:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
 9402:                         },
 9403:                         {       linktext => 'Download submissions',
 9404:                                 url => $url1e,
 9405:                                 permission => 'F',
 9406:                                 icon => 'download_sub.png',
 9407:                                 linktitle => 'Download all students submissions.'
 9408:                         }]},
 9409:                          { categorytitle=>'Automated Grading',
 9410:                items =>[
 9411: 
 9412:                 	    {	linktext => 'Upload Scores',
 9413:                     		url => $url2,
 9414:                     		permission => 'F',
 9415:                     		icon => 'uploadscores.png',
 9416:                     		linktitle => 'Specify a file containing the class scores for current resource.'
 9417:                 	    },
 9418:                 	    {	linktext => 'Process Clicker',
 9419:                     		url => $url3,
 9420:                     		permission => 'F',
 9421:                     		icon => 'addClickerInfoFile.png',
 9422:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
 9423:                 	    },
 9424:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
 9425:                     		url => $url4,
 9426:                     		permission => 'F',
 9427:                     		icon => 'bubblesheet.png',
 9428:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
 9429:                 	    },
 9430:                             {   linktext => 'Verify Receipt Number',
 9431:                                 url => $url5,
 9432:                                 permission => 'F',
 9433:                                 icon => 'receipt_number.png',
 9434:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
 9435:                             }
 9436: 
 9437:                     ]
 9438:             });
 9439: 
 9440:     # Create the menu
 9441:     my $Str;
 9442:     $Str .= '<form method="post" action="" name="gradingMenu">';
 9443:     $Str .= '<input type="hidden" name="command" value="" />'.
 9444:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 9445: 
 9446:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
 9447:     return $Str;    
 9448: }
 9449: 
 9450: 
 9451: sub ungraded {
 9452:     my ($request)=@_;
 9453:     &submit_options($request);
 9454: }
 9455: 
 9456: sub submit_options_sequence {
 9457:     my ($request,$symb) = @_;
 9458:     if (!$symb) {return '';}
 9459:     &commonJSfunctions($request);
 9460:     my $result;
 9461: 
 9462:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 9463:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 9464:     $result.=&selectfield(0).
 9465:             '<input type="hidden" name="command" value="pickStudentPage" />
 9466:             <div>
 9467:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 9468:             </div>
 9469:         </div>
 9470:   </form>';
 9471:     return $result;
 9472: }
 9473: 
 9474: sub submit_options_table {
 9475:     my ($request,$symb) = @_;
 9476:     if (!$symb) {return '';}
 9477:     &commonJSfunctions($request);
 9478:     my $result;
 9479: 
 9480:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 9481:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 9482: 
 9483:     $result.=&selectfield(0).
 9484:             '<input type="hidden" name="command" value="viewgrades" />
 9485:             <div>
 9486:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 9487:             </div>
 9488:         </div>
 9489:   </form>';
 9490:     return $result;
 9491: }
 9492: 
 9493: sub submit_options_download {
 9494:     my ($request,$symb) = @_;
 9495:     if (!$symb) {return '';}
 9496: 
 9497:     &commonJSfunctions($request);
 9498: 
 9499:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 9500:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 9501:     $result.='
 9502: <h2>
 9503:   '.&mt('Select Students for Which to Download Submissions').'
 9504: </h2>'.&selectfield(1).'
 9505:                 <input type="hidden" name="command" value="downloadfileslink" /> 
 9506:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 9507:             </div>
 9508:           </div>
 9509: 
 9510: 
 9511:   </form>';
 9512:     return $result;
 9513: }
 9514: 
 9515: #--- Displays the submissions first page -------
 9516: sub submit_options {
 9517:     my ($request,$symb) = @_;
 9518:     if (!$symb) {return '';}
 9519: 
 9520:     &commonJSfunctions($request);
 9521:     my $result;
 9522: 
 9523:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 9524: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 9525:     $result.=&selectfield(1).'
 9526:                 <input type="hidden" name="command" value="submission" /> 
 9527: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
 9528:             </div>
 9529:           </div>
 9530: 
 9531: 
 9532:   </form>';
 9533:     return $result;
 9534: }
 9535: 
 9536: sub selectfield {
 9537:    my ($full)=@_;
 9538:    my %options = 
 9539:           (&Apache::lonlocal::texthash(
 9540:              'yes'       => 'with submissions',
 9541:              'queued'    => 'in grading queue',
 9542:              'graded'    => 'with ungraded submissions',
 9543:              'incorrect' => 'with incorrect submissions',
 9544:              'all'       => 'with any status'),
 9545:              'select_form_order' => ['yes','queued','graded','incorrect','all']);
 9546:    my $result='<div class="LC_columnSection">
 9547:   
 9548:     <fieldset>
 9549:       <legend>
 9550:        '.&mt('Sections').'
 9551:       </legend>
 9552:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
 9553:     </fieldset>
 9554:   
 9555:     <fieldset>
 9556:       <legend>
 9557:         '.&mt('Groups').'
 9558:       </legend>
 9559:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
 9560:     </fieldset>
 9561:   
 9562:     <fieldset>
 9563:       <legend>
 9564:         '.&mt('Access Status').'
 9565:       </legend>
 9566:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
 9567:     </fieldset>';
 9568:     if ($full) {
 9569:        $result.='
 9570:     <fieldset>
 9571:       <legend>
 9572:         '.&mt('Submission Status').'
 9573:       </legend>'.
 9574:        &Apache::loncommon::select_form('all','submitonly',\%options).
 9575:    '</fieldset>';
 9576:     }
 9577:     $result.='</div><br />';
 9578:     return $result;
 9579: }
 9580: 
 9581: sub reset_perm {
 9582:     undef(%perm);
 9583: }
 9584: 
 9585: sub init_perm {
 9586:     &reset_perm();
 9587:     foreach my $test_perm ('vgr','mgr','opa') {
 9588: 
 9589: 	my $scope = $env{'request.course.id'};
 9590: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
 9591: 
 9592: 	    $scope .= '/'.$env{'request.course.sec'};
 9593: 	    if ( $perm{$test_perm}=
 9594: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
 9595: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
 9596: 	    } else {
 9597: 		delete($perm{$test_perm});
 9598: 	    }
 9599: 	}
 9600:     }
 9601: }
 9602: 
 9603: sub init_old_essays {
 9604:     my ($symb,$apath,$adom,$aname) = @_;
 9605:     if ($symb ne '') {
 9606:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
 9607:         if (keys(%essays) > 0) {
 9608:             $old_essays{$symb} = \%essays;
 9609:         }
 9610:     }
 9611:     return;
 9612: }
 9613: 
 9614: sub reset_old_essays {
 9615:     undef(%old_essays);
 9616: }
 9617: 
 9618: sub gather_clicker_ids {
 9619:     my %clicker_ids;
 9620: 
 9621:     my $classlist = &Apache::loncoursedata::get_classlist();
 9622: 
 9623:     # Set up a couple variables.
 9624:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
 9625:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
 9626:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
 9627: 
 9628:     foreach my $student (keys(%$classlist)) {
 9629:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
 9630:         my $username = $classlist->{$student}->[$username_idx];
 9631:         my $domain   = $classlist->{$student}->[$domain_idx];
 9632:         my $clickers =
 9633: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
 9634:         foreach my $id (split(/\,/,$clickers)) {
 9635:             $id=~s/^[\#0]+//;
 9636:             $id=~s/[\-\:]//g;
 9637:             if (exists($clicker_ids{$id})) {
 9638: 		$clicker_ids{$id}.=','.$username.':'.$domain;
 9639:             } else {
 9640: 		$clicker_ids{$id}=$username.':'.$domain;
 9641:             }
 9642:         }
 9643:     }
 9644:     return %clicker_ids;
 9645: }
 9646: 
 9647: sub gather_adv_clicker_ids {
 9648:     my %clicker_ids;
 9649:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 9650:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9651:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
 9652:     foreach my $element (sort(keys(%coursepersonnel))) {
 9653:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
 9654:             my ($puname,$pudom)=split(/\:/,$person);
 9655:             my $clickers =
 9656: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
 9657:             foreach my $id (split(/\,/,$clickers)) {
 9658: 		$id=~s/^[\#0]+//;
 9659:                 $id=~s/[\-\:]//g;
 9660: 		if (exists($clicker_ids{$id})) {
 9661: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
 9662: 		} else {
 9663: 		    $clicker_ids{$id}=$puname.':'.$pudom;
 9664: 		}
 9665:             }
 9666:         }
 9667:     }
 9668:     return %clicker_ids;
 9669: }
 9670: 
 9671: sub clicker_grading_parameters {
 9672:     return ('gradingmechanism' => 'scalar',
 9673:             'upfiletype' => 'scalar',
 9674:             'specificid' => 'scalar',
 9675:             'pcorrect' => 'scalar',
 9676:             'pincorrect' => 'scalar');
 9677: }
 9678: 
 9679: sub process_clicker {
 9680:     my ($r,$symb)=@_;
 9681:     if (!$symb) {return '';}
 9682:     my $result=&checkforfile_js();
 9683:     $result.=&Apache::loncommon::start_data_table().
 9684:              &Apache::loncommon::start_data_table_header_row().
 9685:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
 9686:              &Apache::loncommon::end_data_table_header_row().
 9687:              &Apache::loncommon::start_data_table_row()."<td>\n";
 9688: # Attempt to restore parameters from last session, set defaults if not present
 9689:     my %Saveable_Parameters=&clicker_grading_parameters();
 9690:     &Apache::loncommon::restore_course_settings('grades_clicker',
 9691:                                                  \%Saveable_Parameters);
 9692:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
 9693:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
 9694:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
 9695:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
 9696: 
 9697:     my %checked;
 9698:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
 9699:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
 9700:           $checked{$gradingmechanism}=' checked="checked"';
 9701:        }
 9702:     }
 9703: 
 9704:     my $upload=&mt("Evaluate File");
 9705:     my $type=&mt("Type");
 9706:     my $attendance=&mt("Award points just for participation");
 9707:     my $personnel=&mt("Correctness determined from response by course personnel");
 9708:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
 9709:     my $given=&mt("Correctness determined from given list of answers").' '.
 9710:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
 9711:     my $pcorrect=&mt("Percentage points for correct solution");
 9712:     my $pincorrect=&mt("Percentage points for incorrect solution");
 9713:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
 9714: 						   {'iclicker' => 'i>clicker',
 9715:                                                     'interwrite' => 'interwrite PRS',
 9716:                                                     'turning' => 'Turning Technologies'});
 9717:     $symb = &Apache::lonenc::check_encrypt($symb);
 9718:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
 9719: function sanitycheck() {
 9720: // Accept only integer percentages
 9721:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
 9722:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
 9723: // Find out grading choice
 9724:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 9725:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
 9726:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
 9727:       }
 9728:    }
 9729: // By default, new choice equals user selection
 9730:    newgradingchoice=gradingchoice;
 9731: // Not good to give more points for false answers than correct ones
 9732:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
 9733:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
 9734:    }
 9735: // If new choice is attendance only, and old choice was correctness-based, restore defaults
 9736:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
 9737:       document.forms.gradesupload.pcorrect.value=100;
 9738:       document.forms.gradesupload.pincorrect.value=100;
 9739:    }
 9740: // If the values are different, cannot be attendance only
 9741:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
 9742:        (gradingchoice=='attendance')) {
 9743:        newgradingchoice='personnel';
 9744:    }
 9745: // Change grading choice to new one
 9746:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 9747:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
 9748:          document.forms.gradesupload.gradingmechanism[i].checked=true;
 9749:       } else {
 9750:          document.forms.gradesupload.gradingmechanism[i].checked=false;
 9751:       }
 9752:    }
 9753: // Remember the old state
 9754:    document.forms.gradesupload.waschecked.value=newgradingchoice;
 9755: }
 9756: ENDUPFORM
 9757:     $result.= <<ENDUPFORM;
 9758: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 9759: <input type="hidden" name="symb" value="$symb" />
 9760: <input type="hidden" name="command" value="processclickerfile" />
 9761: <input type="file" name="upfile" size="50" />
 9762: <br /><label>$type: $selectform</label>
 9763: ENDUPFORM
 9764:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
 9765:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
 9766:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
 9767: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
 9768: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
 9769: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
 9770: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
 9771: <br />&nbsp;&nbsp;&nbsp;
 9772: <input type="text" name="givenanswer" size="50" />
 9773: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
 9774: ENDGRADINGFORM
 9775:          $result.='</td>'.&Apache::loncommon::end_data_table_row().
 9776:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
 9777:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
 9778: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
 9779: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 9780: </form>'
 9781: ENDPERCFORM
 9782:     $result.='</td>'.
 9783:              &Apache::loncommon::end_data_table_row().
 9784:              &Apache::loncommon::end_data_table();
 9785:     return $result;
 9786: }
 9787: 
 9788: sub process_clicker_file {
 9789:     my ($r,$symb)=@_;
 9790:     if (!$symb) {return '';}
 9791: 
 9792:     my %Saveable_Parameters=&clicker_grading_parameters();
 9793:     &Apache::loncommon::store_course_settings('grades_clicker',
 9794:                                               \%Saveable_Parameters);
 9795:     my $result='';
 9796:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
 9797: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
 9798: 	return $result;
 9799:     }
 9800:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
 9801:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
 9802:         return $result;
 9803:     }
 9804:     my $foundgiven=0;
 9805:     if ($env{'form.gradingmechanism'} eq 'given') {
 9806:         $env{'form.givenanswer'}=~s/^\s*//gs;
 9807:         $env{'form.givenanswer'}=~s/\s*$//gs;
 9808:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
 9809:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
 9810:         my @answers=split(/\,/,$env{'form.givenanswer'});
 9811:         $foundgiven=$#answers+1;
 9812:     }
 9813:     my %clicker_ids=&gather_clicker_ids();
 9814:     my %correct_ids;
 9815:     if ($env{'form.gradingmechanism'} eq 'personnel') {
 9816: 	%correct_ids=&gather_adv_clicker_ids();
 9817:     }
 9818:     if ($env{'form.gradingmechanism'} eq 'specific') {
 9819: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
 9820: 	   $correct_id=~tr/a-z/A-Z/;
 9821: 	   $correct_id=~s/\s//gs;
 9822: 	   $correct_id=~s/^[\#0]+//;
 9823:            $correct_id=~s/[\-\:]//g;
 9824:            if ($correct_id) {
 9825: 	      $correct_ids{$correct_id}='specified';
 9826:            }
 9827:         }
 9828:     }
 9829:     if ($env{'form.gradingmechanism'} eq 'attendance') {
 9830: 	$result.=&mt('Score based on attendance only');
 9831:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
 9832:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
 9833:     } else {
 9834: 	my $number=0;
 9835: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
 9836: 	foreach my $id (sort(keys(%correct_ids))) {
 9837: 	    $result.='<br /><tt>'.$id.'</tt> - ';
 9838: 	    if ($correct_ids{$id} eq 'specified') {
 9839: 		$result.=&mt('specified');
 9840: 	    } else {
 9841: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
 9842: 		$result.=&Apache::loncommon::plainname($uname,$udom);
 9843: 	    }
 9844: 	    $number++;
 9845: 	}
 9846:         $result.="</p>\n";
 9847:         if ($number==0) {
 9848:             $result .=
 9849:                  &Apache::lonhtmlcommon::confirm_success(
 9850:                      &mt('No IDs found to determine correct answer'),1);
 9851:             return $result;
 9852:         }
 9853:     }
 9854:     if (length($env{'form.upfile'}) < 2) {
 9855:         $result .=
 9856:             &Apache::lonhtmlcommon::confirm_success(
 9857:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
 9858:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
 9859:         return $result;
 9860:     }
 9861: 
 9862: # Were able to get all the info needed, now analyze the file
 9863: 
 9864:     $result.=&Apache::loncommon::studentbrowser_javascript();
 9865:     $symb = &Apache::lonenc::check_encrypt($symb);
 9866:     $result.=&Apache::loncommon::start_data_table().
 9867:              &Apache::loncommon::start_data_table_header_row().
 9868:              '<th>'.&mt('Evaluate clicker file').'</th>'.
 9869:              &Apache::loncommon::end_data_table_header_row().
 9870:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
 9871: <td>
 9872: <form method="post" action="/adm/grades" name="clickeranalysis">
 9873: <input type="hidden" name="symb" value="$symb" />
 9874: <input type="hidden" name="command" value="assignclickergrades" />
 9875: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
 9876: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
 9877: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
 9878: ENDHEADER
 9879:     if ($env{'form.gradingmechanism'} eq 'given') {
 9880:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
 9881:     } 
 9882:     my %responses;
 9883:     my @questiontitles;
 9884:     my $errormsg='';
 9885:     my $number=0;
 9886:     if ($env{'form.upfiletype'} eq 'iclicker') {
 9887: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
 9888:     }
 9889:     if ($env{'form.upfiletype'} eq 'interwrite') {
 9890:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
 9891:     }
 9892:     if ($env{'form.upfiletype'} eq 'turning') {
 9893:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
 9894:     }
 9895:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
 9896:              '<input type="hidden" name="number" value="'.$number.'" />'.
 9897:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
 9898:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
 9899:              '<br />';
 9900:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
 9901:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
 9902:        return $result;
 9903:     } 
 9904: # Remember Question Titles
 9905: # FIXME: Possibly need delimiter other than ":"
 9906:     for (my $i=0;$i<$number;$i++) {
 9907:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
 9908:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
 9909:     }
 9910:     my $correct_count=0;
 9911:     my $student_count=0;
 9912:     my $unknown_count=0;
 9913: # Match answers with usernames
 9914: # FIXME: Possibly need delimiter other than ":"
 9915:     foreach my $id (keys(%responses)) {
 9916:        if ($correct_ids{$id}) {
 9917:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
 9918:           $correct_count++;
 9919:        } elsif ($clicker_ids{$id}) {
 9920:           if ($clicker_ids{$id}=~/\,/) {
 9921: # More than one user with the same clicker!
 9922:              $result.="</td>".&Apache::loncommon::end_data_table_row().
 9923:                            &Apache::loncommon::start_data_table_row()."<td>".
 9924:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
 9925:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 9926:                            "<select name='multi".$id."'>";
 9927:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
 9928:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
 9929:              }
 9930:              $result.='</select>';
 9931:              $unknown_count++;
 9932:           } else {
 9933: # Good: found one and only one user with the right clicker
 9934:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
 9935:              $student_count++;
 9936:           }
 9937:        } else {
 9938:           $result.="</td>".&Apache::loncommon::end_data_table_row().
 9939:                            &Apache::loncommon::start_data_table_row()."<td>".
 9940:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
 9941:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 9942:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
 9943:                    "\n".&mt("Domain").": ".
 9944:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
 9945:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,0,$id);
 9946:           $unknown_count++;
 9947:        }
 9948:     }
 9949:     $result.='<hr />'.
 9950:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
 9951:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
 9952:        if ($correct_count==0) {
 9953:           $errormsg.="Found no correct answers for grading!";
 9954:        } elsif ($correct_count>1) {
 9955:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
 9956:        }
 9957:     }
 9958:     if ($number<1) {
 9959:        $errormsg.="Found no questions.";
 9960:     }
 9961:     if ($errormsg) {
 9962:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
 9963:     } else {
 9964:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
 9965:     }
 9966:     $result.='</form></td>'.
 9967:              &Apache::loncommon::end_data_table_row().
 9968:              &Apache::loncommon::end_data_table();
 9969:     return $result;
 9970: }
 9971: 
 9972: sub iclicker_eval {
 9973:     my ($questiontitles,$responses)=@_;
 9974:     my $number=0;
 9975:     my $errormsg='';
 9976:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 9977:         my %components=&Apache::loncommon::record_sep($line);
 9978:         my @entries=map {$components{$_}} (sort(keys(%components)));
 9979: 	if ($entries[0] eq 'Question') {
 9980: 	    for (my $i=3;$i<$#entries;$i+=6) {
 9981: 		$$questiontitles[$number]=$entries[$i];
 9982: 		$number++;
 9983: 	    }
 9984: 	}
 9985: 	if ($entries[0]=~/^\#/) {
 9986: 	    my $id=$entries[0];
 9987: 	    my @idresponses;
 9988: 	    $id=~s/^[\#0]+//;
 9989: 	    for (my $i=0;$i<$number;$i++) {
 9990: 		my $idx=3+$i*6;
 9991:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
 9992: 		push(@idresponses,$entries[$idx]);
 9993: 	    }
 9994: 	    $$responses{$id}=join(',',@idresponses);
 9995: 	}
 9996:     }
 9997:     return ($errormsg,$number);
 9998: }
 9999: 
10000: sub interwrite_eval {
10001:     my ($questiontitles,$responses)=@_;
10002:     my $number=0;
10003:     my $errormsg='';
10004:     my $skipline=1;
10005:     my $questionnumber=0;
10006:     my %idresponses=();
10007:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10008:         my %components=&Apache::loncommon::record_sep($line);
10009:         my @entries=map {$components{$_}} (sort(keys(%components)));
10010:         if ($entries[1] eq 'Time') { $skipline=0; next; }
10011:         if ($entries[1] eq 'Response') { $skipline=1; }
10012:         next if $skipline;
10013:         if ($entries[0]!=$questionnumber) {
10014:            $questionnumber=$entries[0];
10015:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
10016:            $number++;
10017:         }
10018:         my $id=$entries[4];
10019:         $id=~s/^[\#0]+//;
10020:         $id=~s/^v\d*\://i;
10021:         $id=~s/[\-\:]//g;
10022:         $idresponses{$id}[$number]=$entries[6];
10023:     }
10024:     foreach my $id (keys(%idresponses)) {
10025:        $$responses{$id}=join(',',@{$idresponses{$id}});
10026:        $$responses{$id}=~s/^\s*\,//;
10027:     }
10028:     return ($errormsg,$number);
10029: }
10030: 
10031: sub turning_eval {
10032:     my ($questiontitles,$responses)=@_;
10033:     my $number=0;
10034:     my $errormsg='';
10035:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10036:         my %components=&Apache::loncommon::record_sep($line);
10037:         my @entries=map {$components{$_}} (sort(keys(%components)));
10038:         if ($#entries>$number) { $number=$#entries; }
10039:         my $id=$entries[0];
10040:         my @idresponses;
10041:         $id=~s/^[\#0]+//;
10042:         unless ($id) { next; }
10043:         for (my $idx=1;$idx<=$#entries;$idx++) {
10044:             $entries[$idx]=~s/\,/\;/g;
10045:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
10046:             push(@idresponses,$entries[$idx]);
10047:         }
10048:         $$responses{$id}=join(',',@idresponses);
10049:     }
10050:     for (my $i=1; $i<=$number; $i++) {
10051:         $$questiontitles[$i]=&mt('Question [_1]',$i);
10052:     }
10053:     return ($errormsg,$number);
10054: }
10055: 
10056: 
10057: sub assign_clicker_grades {
10058:     my ($r,$symb)=@_;
10059:     if (!$symb) {return '';}
10060: # See which part we are saving to
10061:     my $res_error;
10062:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
10063:     if ($res_error) {
10064:         return &navmap_errormsg();
10065:     }
10066: # FIXME: This should probably look for the first handgradeable part
10067:     my $part=$$partlist[0];
10068: # Start screen output
10069:     my $result=&Apache::loncommon::start_data_table().
10070:              &Apache::loncommon::start_data_table_header_row().
10071:              '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
10072:              &Apache::loncommon::end_data_table_header_row().
10073:              &Apache::loncommon::start_data_table_row().'<td>';
10074: # Get correct result
10075: # FIXME: Possibly need delimiter other than ":"
10076:     my @correct=();
10077:     my $gradingmechanism=$env{'form.gradingmechanism'};
10078:     my $number=$env{'form.number'};
10079:     if ($gradingmechanism ne 'attendance') {
10080:        foreach my $key (keys(%env)) {
10081:           if ($key=~/^form\.correct\:/) {
10082:              my @input=split(/\,/,$env{$key});
10083:              for (my $i=0;$i<=$#input;$i++) {
10084:                  if (($correct[$i]) && ($input[$i]) &&
10085:                      ($correct[$i] ne $input[$i])) {
10086:                     $result.='<br /><span class="LC_warning">'.
10087:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
10088:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
10089:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
10090:                     $correct[$i]=$input[$i];
10091:                  }
10092:              }
10093:           }
10094:        }
10095:        for (my $i=0;$i<$number;$i++) {
10096:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
10097:              $result.='<br /><span class="LC_error">'.
10098:                       &mt('No correct result given for question "[_1]"!',
10099:                           $env{'form.question:'.$i}).'</span>';
10100:           }
10101:        }
10102:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
10103:     }
10104: # Start grading
10105:     my $pcorrect=$env{'form.pcorrect'};
10106:     my $pincorrect=$env{'form.pincorrect'};
10107:     my $storecount=0;
10108:     my %users=();
10109:     foreach my $key (keys(%env)) {
10110:        my $user='';
10111:        if ($key=~/^form\.student\:(.*)$/) {
10112:           $user=$1;
10113:        }
10114:        if ($key=~/^form\.unknown\:(.*)$/) {
10115:           my $id=$1;
10116:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
10117:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
10118:           } elsif ($env{'form.multi'.$id}) {
10119:              $user=$env{'form.multi'.$id};
10120:           }
10121:        }
10122:        if ($user) {
10123:           if ($users{$user}) {
10124:              $result.='<br /><span class="LC_warning">'.
10125:                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
10126:                       '</span><br />';
10127:           }
10128:           $users{$user}=1; 
10129:           my @answer=split(/\,/,$env{$key});
10130:           my $sum=0;
10131:           my $realnumber=$number;
10132:           for (my $i=0;$i<$number;$i++) {
10133:              if  ($correct[$i] eq '-') {
10134:                 $realnumber--;
10135:              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/))  {
10136:                 if ($gradingmechanism eq 'attendance') {
10137:                    $sum+=$pcorrect;
10138:                 } elsif ($correct[$i] eq '*') {
10139:                    $sum+=$pcorrect;
10140:                 } else {
10141: # We actually grade if correct or not
10142:                    my $increment=$pincorrect;
10143: # Special case: numerical answer "0"
10144:                    if ($correct[$i] eq '0') {
10145:                       if ($answer[$i]=~/^[0\.]+$/) {
10146:                          $increment=$pcorrect;
10147:                       }
10148: # General numerical answer, both evaluate to something non-zero
10149:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
10150:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
10151:                          $increment=$pcorrect;
10152:                       }
10153: # Must be just alphanumeric
10154:                    } elsif ($answer[$i] eq $correct[$i]) {
10155:                       $increment=$pcorrect;
10156:                    }
10157:                    $sum+=$increment;
10158:                 }
10159:              }
10160:           }
10161:           my $ave=$sum/(100*$realnumber);
10162: # Store
10163:           my ($username,$domain)=split(/\:/,$user);
10164:           my %grades=();
10165:           $grades{"resource.$part.solved"}='correct_by_override';
10166:           $grades{"resource.$part.awarded"}=$ave;
10167:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
10168:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
10169:                                                  $env{'request.course.id'},
10170:                                                  $domain,$username);
10171:           if ($returncode ne 'ok') {
10172:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
10173:           } else {
10174:              $storecount++;
10175:           }
10176:        }
10177:     }
10178: # We are done
10179:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
10180:              '</td>'.
10181:              &Apache::loncommon::end_data_table_row().
10182:              &Apache::loncommon::end_data_table();
10183:     return $result;
10184: }
10185: 
10186: sub navmap_errormsg {
10187:     return '<div class="LC_error">'.
10188:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
10189:            &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>').
10190:            '</div>';
10191: }
10192: 
10193: sub startpage {
10194:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$js) = @_;
10195:     if ($nomenu) {
10196:         $r->print(&Apache::loncommon::start_page("Student's Version",$js,{'only_body' => '1'}));
10197:     } else {
10198:         unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
10199:         $r->print(&Apache::loncommon::start_page('Grading',$js,
10200:                                                  {'bread_crumbs' => $crumbs}));
10201:         &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
10202:     }
10203:     unless ($nodisplayflag) {
10204:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp));
10205:     }
10206: }
10207: 
10208: sub select_problem {
10209:     my ($r)=@_;
10210:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
10211:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1));
10212:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
10213:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
10214: }
10215: 
10216: sub handler {
10217:     my $request=$_[0];
10218:     &reset_caches();
10219:     if ($request->header_only) {
10220:         &Apache::loncommon::content_type($request,'text/html');
10221:         $request->send_http_header;
10222:         return OK;
10223:     }
10224:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
10225: 
10226: # see what command we need to execute
10227: 
10228:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
10229:     my $command=$commands[0];
10230: 
10231:     &init_perm();
10232:     if (!$env{'request.course.id'}) {
10233:         unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
10234:                 ($command =~ /^scantronupload/)) {
10235:             # Not in a course.
10236:             $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
10237:             return HTTP_NOT_ACCEPTABLE;
10238:         }
10239:     } elsif (!%perm) {
10240:         $request->internal_redirect('/adm/quickgrades');
10241:         return OK;
10242:     }
10243:     &Apache::loncommon::content_type($request,'text/html');
10244:     $request->send_http_header;
10245: 
10246:     if ($#commands > 0) {
10247: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
10248:     }
10249: 
10250: # see what the symb is
10251: 
10252:     my $symb=$env{'form.symb'};
10253:     unless ($symb) {
10254:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
10255:        $symb=&Apache::lonnet::symbread($url);
10256:     }
10257:     &Apache::lonenc::check_decrypt(\$symb);
10258: 
10259:     $ssi_error = 0;
10260:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
10261: #
10262: # Not called from a resource, but inside a course
10263: #    
10264:         &startpage($request,undef,[],1,1);
10265:         &select_problem($request);
10266:     } else {
10267: 	if ($command eq 'submission' && $perm{'vgr'}) {
10268:             my ($stuvcurrent,$stuvdisp,$versionform,$js);
10269:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
10270:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
10271:                     &choose_task_version_form($symb,$env{'form.student'},
10272:                                               $env{'form.userdom'});
10273:             }
10274:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,$stuvcurrent,$stuvdisp,undef,$js);
10275:             if ($versionform) {
10276:                 $request->print($versionform);
10277:             }
10278:             $request->print('<br clear="all" />');
10279: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
10280:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
10281:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
10282:                 &choose_task_version_form($symb,$env{'form.student'},
10283:                                           $env{'form.userdom'},
10284:                                           $env{'form.inhibitmenu'});
10285:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,$stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$js);
10286:             if ($versionform) {
10287:                 $request->print($versionform);
10288:             }
10289:             $request->print('<br clear="all" />');
10290:             $request->print(&show_previous_task_version($request,$symb));
10291: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
10292:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
10293:                                        {href=>'',text=>'Select student'}],1,1);
10294: 	    &pickStudentPage($request,$symb);
10295: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
10296:             &startpage($request,$symb,
10297:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
10298:                                        {href=>'',text=>'Select student'},
10299:                                        {href=>'',text=>'Grade student'}],1,1);
10300: 	    &displayPage($request,$symb);
10301: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
10302:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
10303:                                        {href=>'',text=>'Select student'},
10304:                                        {href=>'',text=>'Grade student'},
10305:                                        {href=>'',text=>'Store grades'}],1,1);
10306: 	    &updateGradeByPage($request,$symb);
10307: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
10308:             &startpage($request,$symb,[{href=>'',text=>'...'},
10309:                                        {href=>'',text=>'Modify grades'}]);
10310: 	    &processGroup($request,$symb);
10311: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
10312:             &startpage($request,$symb);
10313: 	    $request->print(&grading_menu($request,$symb));
10314: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
10315:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
10316: 	    $request->print(&submit_options($request,$symb));
10317:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
10318:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}]);
10319:             $request->print(&listStudents($request,$symb,'graded'));
10320:         } elsif ($command eq 'table' && $perm{'vgr'}) {
10321:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
10322:             $request->print(&submit_options_table($request,$symb));
10323:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
10324:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
10325:             $request->print(&submit_options_sequence($request,$symb));
10326: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
10327:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
10328: 	    $request->print(&viewgrades($request,$symb));
10329: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
10330:             &startpage($request,$symb,[{href=>'',text=>'...'},
10331:                                        {href=>'',text=>'Store grades'}]);
10332: 	    $request->print(&processHandGrade($request,$symb));
10333: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
10334:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
10335:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
10336:                                                                              text=>"Modify grades"},
10337:                                        {href=>'', text=>"Store grades"}]);
10338: 	    $request->print(&editgrades($request,$symb));
10339:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
10340:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
10341:             $request->print(&initialverifyreceipt($request,$symb));
10342: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
10343:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
10344:                                        {href=>'',text=>'Verification Result'}]);
10345: 	    $request->print(&verifyreceipt($request,$symb));
10346:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
10347:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
10348:             $request->print(&process_clicker($request,$symb));
10349:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
10350:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
10351:                                        {href=>'', text=>'Process clicker file'}]);
10352:             $request->print(&process_clicker_file($request,$symb));
10353:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
10354:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
10355:                                        {href=>'', text=>'Process clicker file'},
10356:                                        {href=>'', text=>'Store grades'}]);
10357:             $request->print(&assign_clicker_grades($request,$symb));
10358: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
10359:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10360: 	    $request->print(&upcsvScores_form($request,$symb));
10361: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
10362:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10363: 	    $request->print(&csvupload($request,$symb));
10364: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
10365:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10366: 	    $request->print(&csvuploadmap($request,$symb));
10367: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
10368: 	    if ($env{'form.associate'} ne 'Reverse Association') {
10369:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10370: 		$request->print(&csvuploadoptions($request,$symb));
10371: 	    } else {
10372: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
10373: 		    $env{'form.upfile_associate'} = 'reverse';
10374: 		} else {
10375: 		    $env{'form.upfile_associate'} = 'forward';
10376: 		}
10377:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10378: 		$request->print(&csvuploadmap($request,$symb));
10379: 	    }
10380: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
10381:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10382: 	    $request->print(&csvuploadassign($request,$symb));
10383: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
10384:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10385: 	    $request->print(&scantron_selectphase($request,undef,$symb));
10386:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
10387:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10388:  	    $request->print(&scantron_do_warning($request,$symb));
10389: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
10390:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10391: 	    $request->print(&scantron_validate_file($request,$symb));
10392: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
10393:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10394: 	    $request->print(&scantron_process_students($request,$symb));
10395:  	} elsif ($command eq 'scantronupload' && 
10396:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
10397: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
10398:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10399:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
10400:  	} elsif ($command eq 'scantronupload_save' &&
10401:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
10402: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
10403:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10404:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
10405:  	} elsif ($command eq 'scantron_download' &&
10406: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
10407:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10408:  	    $request->print(&scantron_download_scantron_data($request,$symb));
10409:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
10410:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10411:             $request->print(&checkscantron_results($request,$symb));
10412:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
10413:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}]);
10414:             $request->print(&submit_options_download($request,$symb));
10415:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
10416:             &startpage($request,$symb,
10417:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
10418:     {href=>'', text=>'Download submissions'}]);
10419:             &submit_download_link($request,$symb);
10420: 	} elsif ($command) {
10421:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
10422: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
10423: 	}
10424:     }
10425:     if ($ssi_error) {
10426: 	&ssi_print_error($request);
10427:     }
10428:     if ($env{'form.inhibitmenu'}) {
10429:         $request->print(&Apache::loncommon::end_page());
10430:     } else {
10431:         &Apache::lonquickgrades::endGradeScreen($request);
10432:     }
10433:     &reset_caches();
10434:     return OK;
10435: }
10436: 
10437: 1;
10438: 
10439: __END__;
10440: 
10441: 
10442: =head1 NAME
10443: 
10444: Apache::grades
10445: 
10446: =head1 SYNOPSIS
10447: 
10448: Handles the viewing of grades.
10449: 
10450: This is part of the LearningOnline Network with CAPA project
10451: described at http://www.lon-capa.org.
10452: 
10453: =head1 OVERVIEW
10454: 
10455: Do an ssi with retries:
10456: While I'd love to factor out this with the version in lonprintout,
10457: 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
10458: I'm not quite ready to invent (e.g. an ssi_with_retry object).
10459: 
10460: At least the logic that drives this has been pulled out into loncommon.
10461: 
10462: 
10463: 
10464: ssi_with_retries - Does the server side include of a resource.
10465:                      if the ssi call returns an error we'll retry it up to
10466:                      the number of times requested by the caller.
10467:                      If we still have a problem, no text is appended to the
10468:                      output and we set some global variables.
10469:                      to indicate to the caller an SSI error occurred.  
10470:                      All of this is supposed to deal with the issues described
10471:                      in LON-CAPA BZ 5631 see:
10472:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
10473:                      by informing the user that this happened.
10474: 
10475: Parameters:
10476:   resource   - The resource to include.  This is passed directly, without
10477:                interpretation to lonnet::ssi.
10478:   form       - The form hash parameters that guide the interpretation of the resource
10479:                
10480:   retries    - Number of retries allowed before giving up completely.
10481: Returns:
10482:   On success, returns the rendered resource identified by the resource parameter.
10483: Side Effects:
10484:   The following global variables can be set:
10485:    ssi_error                - If an unrecoverable error occurred this becomes true.
10486:                               It is up to the caller to initialize this to false
10487:                               if desired.
10488:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
10489:                               of the resource that could not be rendered by the ssi
10490:                               call.
10491:    ssi_error_message   - The error string fetched from the ssi response
10492:                               in the event of an error.
10493: 
10494: 
10495: =head1 HANDLER SUBROUTINE
10496: 
10497: ssi_with_retries()
10498: 
10499: =head1 SUBROUTINES
10500: 
10501: =over
10502: 
10503: =head1 Routines to display previous version of a Task for a specific student
10504: 
10505: Tasks are graded pass/fail. Students who have yet to pass a particular Task
10506: can receive another opportunity. Access to tasks is slot-based. If a slot
10507: requires a proctor to check-in the student, a new version of the Task will
10508: be created when the student is checked in to the new opportunity.
10509: 
10510: If a particular student has tried two or more versions of a particular task,
10511: the submission screen provides a user with vgr privileges (e.g., a Course
10512: Coordinator) the ability to display a previous version worked on by the
10513: student.  By default, the current version is displayed. If a previous version
10514: has been selected for display, submission data are only shown that pertain
10515: to that particular version, and the interface to submit grades is not shown.
10516: 
10517: =over 4
10518: 
10519: =item show_previous_task_version()
10520: 
10521: Displays a specified version of a student's Task, as the student sees it.
10522: 
10523: Inputs: 2
10524:         request - request object
10525:         symb    - unique symb for current instance of resource
10526: 
10527: Output: None.
10528: 
10529: Side Effects: calls &show_problem() to print version of Task, with
10530:               version contained in form item: $env{'form.previousversion'}
10531: 
10532: =item choose_task_version_form()
10533: 
10534: Displays a web form used to select which version of a student's view of a
10535: Task should be displayed.  Either launches a pop-up window, or replaces
10536: content in existing pop-up, or replaces page in main window.
10537: 
10538: Inputs: 4
10539:         symb    - unique symb for current instance of resource
10540:         uname   - username of student
10541:         udom    - domain of student
10542:         nomenu  - 1 if display is in a pop-up window, and hence no menu
10543:                   breadcrumbs etc., are displayed
10544: 
10545: Output: 4
10546:         current   - student's current version
10547:         displayed - student's version being displayed
10548:         result    - scalar containing HTML for web form used to switch to
10549:                     a different version (or a link to close window, if pop-up).
10550:         js        - javascript for processing selection in versions web form
10551: 
10552: Side Effects: None.
10553: 
10554: =item previous_display_javascript()
10555: 
10556: Inputs: 2
10557:         nomenu  - 1 if display is in a pop-up window, and hence no menu
10558:                   breadcrumbs etc., are displayed.
10559:         current - student's current version number.
10560: 
10561: Output: 1
10562:         js      - javascript for processing selection in versions web form.
10563: 
10564: Side Effects: None.
10565: 
10566: =back
10567: 
10568: =head1 Routines to process bubblesheet data.
10569: 
10570: =over 4
10571: 
10572: =item scantron_get_correction() : 
10573: 
10574:    Builds the interface screen to interact with the operator to fix a
10575:    specific error condition in a specific scanline
10576: 
10577:  Arguments:
10578:     $r           - Apache request object
10579:     $i           - number of the current scanline
10580:     $scan_record - hash ref as returned from &scantron_parse_scanline()
10581:     $scan_config - hash ref as returned from &get_scantron_config()
10582:     $line        - full contents of the current scanline
10583:     $error       - error condition, valid values are
10584:                    'incorrectCODE', 'duplicateCODE',
10585:                    'doublebubble', 'missingbubble',
10586:                    'duplicateID', 'incorrectID'
10587:     $arg         - extra information needed
10588:        For errors:
10589:          - duplicateID   - paper number that this studentID was seen before on
10590:          - duplicateCODE - array ref of the paper numbers this CODE was
10591:                            seen on before
10592:          - incorrectCODE - current incorrect CODE 
10593:          - doublebubble  - array ref of the bubble lines that have double
10594:                            bubble errors
10595:          - missingbubble - array ref of the bubble lines that have missing
10596:                            bubble errors
10597: 
10598:    $randomorder - True if exam folder has randomorder set
10599:    $randompick  - True if exam folder has randompick set
10600:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
10601:                      for current line to question number used for same question
10602:                      in "Master Seqence" (as seen by Course Coordinator).
10603:    $startline   - Reference to hash where key is question number (0 is first)
10604:                   and value is number of first bubble line for current student
10605:                   or code-based randompick and/or randomorder.
10606: 
10607: 
10608: 
10609: =item  scantron_get_maxbubble() : 
10610: 
10611:    Arguments:
10612:        $nav_error  - Reference to scalar which is a flag to indicate a
10613:                       failure to retrieve a navmap object.
10614:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
10615:        calling routine should trap the error condition and display the warning
10616:        found in &navmap_errormsg().
10617: 
10618:        $scantron_config - Reference to bubblesheet format configuration hash.
10619: 
10620:    Returns the maximum number of bubble lines that are expected to
10621:    occur. Does this by walking the selected sequence rendering the
10622:    resource and then checking &Apache::lonxml::get_problem_counter()
10623:    for what the current value of the problem counter is.
10624: 
10625:    Caches the results to $env{'form.scantron_maxbubble'},
10626:    $env{'form.scantron.bubble_lines.n'}, 
10627:    $env{'form.scantron.first_bubble_line.n'} and
10628:    $env{"form.scantron.sub_bubblelines.n"}
10629:    which are the total number of bubble lines, the number of bubble
10630:    lines for response n and number of the first bubble line for response n,
10631:    and a comma separated list of numbers of bubble lines for sub-questions
10632:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
10633: 
10634: 
10635: =item  scantron_validate_missingbubbles() : 
10636: 
10637:    Validates all scanlines in the selected file to not have any
10638:     answers that don't have bubbles that have not been verified
10639:     to be bubble free.
10640: 
10641: =item  scantron_process_students() : 
10642: 
10643:    Routine that does the actual grading of the bubblesheet information.
10644: 
10645:    The parsed scanline hash is added to %env 
10646: 
10647:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
10648:    foreach resource , with the form data of
10649: 
10650: 	'submitted'     =>'scantron' 
10651: 	'grade_target'  =>'grade',
10652: 	'grade_username'=> username of student
10653: 	'grade_domain'  => domain of student
10654: 	'grade_courseid'=> of course
10655: 	'grade_symb'    => symb of resource to grade
10656: 
10657:     This triggers a grading pass. The problem grading code takes care
10658:     of converting the bubbled letter information (now in %env) into a
10659:     valid submission.
10660: 
10661: =item  scantron_upload_scantron_data() :
10662: 
10663:     Creates the screen for adding a new bubblesheet data file to a course.
10664: 
10665: =item  scantron_upload_scantron_data_save() : 
10666: 
10667:    Adds a provided bubble information data file to the course if user
10668:    has the correct privileges to do so. 
10669: 
10670: =item  valid_file() :
10671: 
10672:    Validates that the requested bubble data file exists in the course.
10673: 
10674: =item  scantron_download_scantron_data() : 
10675: 
10676:    Shows a list of the three internal files (original, corrected,
10677:    skipped) for a specific bubblesheet data file that exists in the
10678:    course.
10679: 
10680: =item  scantron_validate_ID() : 
10681: 
10682:    Validates all scanlines in the selected file to not have any
10683:    invalid or underspecified student/employee IDs
10684: 
10685: =item navmap_errormsg() :
10686: 
10687:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
10688:    Should be called whenever the request to instantiate a navmap object fails.
10689: 
10690: =back
10691: 
10692: =back
10693: 
10694: =cut

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