File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.668: download - view: text, annotated - select for diffs
Fri Dec 23 20:04:46 2011 UTC (12 years, 4 months ago) by www
Branches: MAIN
CVS tags: HEAD
Bug #6165: leave it to the browser to decide whether or not to have scrollbars
when composing messages to students

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.668 2011/12/23 20:04:46 www 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: 
   58: #  These variables are used to recover from ssi errors
   59: 
   60: my $ssi_retries = 5;
   61: my $ssi_error;
   62: my $ssi_error_resource;
   63: my $ssi_error_message;
   64: 
   65: 
   66: sub ssi_with_retries {
   67:     my ($resource, $retries, %form) = @_;
   68:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
   69:     if ($response->is_error) {
   70: 	$ssi_error          = 1;
   71: 	$ssi_error_resource = $resource;
   72: 	$ssi_error_message  = $response->code . " " . $response->message;
   73:     }
   74: 
   75:     return $content;
   76: 
   77: }
   78: #
   79: #  Prodcuces an ssi retry failure error message to the user:
   80: #
   81: 
   82: sub ssi_print_error {
   83:     my ($r) = @_;
   84:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
   85:     $r->print('
   86: <br />
   87: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
   88: <p>
   89: '.&mt('Unable to retrieve a resource from a server:').'<br />
   90: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
   91: '.&mt('Error:').' '.$ssi_error_message.'
   92: </p>
   93: <p>'.
   94: &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 />'.
   95: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
   96: '</p>');
   97:     return;
   98: }
   99: 
  100: #
  101: # --- Retrieve the parts from the metadata file.---
  102: # Returns an array of everything that the resources stores away
  103: #
  104: 
  105: sub getpartlist {
  106:     my ($symb,$errorref) = @_;
  107: 
  108:     my $navmap   = Apache::lonnavmaps::navmap->new();
  109:     unless (ref($navmap)) {
  110:         if (ref($errorref)) { 
  111:             $$errorref = 'navmap';
  112:             return;
  113:         }
  114:     }
  115:     my $res      = $navmap->getBySymb($symb);
  116:     my $partlist = $res->parts();
  117:     my $url      = $res->src();
  118:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
  119: 
  120:     my @stores;
  121:     foreach my $part (@{ $partlist }) {
  122: 	foreach my $key (@metakeys) {
  123: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
  124: 	}
  125:     }
  126:     return @stores;
  127: }
  128: 
  129: #--- Format fullname, username:domain if different for display
  130: #--- Use anywhere where the student names are listed
  131: sub nameUserString {
  132:     my ($type,$fullname,$uname,$udom) = @_;
  133:     if ($type eq 'header') {
  134: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
  135:     } else {
  136: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
  137: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
  138:     }
  139: }
  140: 
  141: #--- Get the partlist and the response type for a given problem. ---
  142: #--- Indicate if a response type is coded handgraded or not. ---
  143: #--- Sets response_error pointer to "1" if navmaps object broken ---
  144: sub response_type {
  145:     my ($symb,$response_error) = @_;
  146: 
  147:     my $navmap = Apache::lonnavmaps::navmap->new();
  148:     unless (ref($navmap)) {
  149:         if (ref($response_error)) {
  150:             $$response_error = 1;
  151:         }
  152:         return;
  153:     }
  154:     my $res = $navmap->getBySymb($symb);
  155:     unless (ref($res)) {
  156:         $$response_error = 1;
  157:         return;
  158:     }
  159:     my $partlist = $res->parts();
  160:     my %vPart = 
  161: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
  162:     my (%response_types,%handgrade);
  163:     foreach my $part (@{ $partlist }) {
  164: 	next if (%vPart && !exists($vPart{$part}));
  165: 
  166: 	my @types = $res->responseType($part);
  167: 	my @ids = $res->responseIds($part);
  168: 	for (my $i=0; $i < scalar(@ids); $i++) {
  169: 	    $response_types{$part}{$ids[$i]} = $types[$i];
  170: 	    $handgrade{$part.'_'.$ids[$i]} = 
  171: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
  172: 				     '.handgrade',$symb);
  173: 	}
  174:     }
  175:     return ($partlist,\%handgrade,\%response_types);
  176: }
  177: 
  178: sub flatten_responseType {
  179:     my ($responseType) = @_;
  180:     my @part_response_id =
  181: 	map { 
  182: 	    my $part = $_;
  183: 	    map {
  184: 		[$part,$_]
  185: 		} sort(keys(%{ $responseType->{$part} }));
  186: 	} sort(keys(%$responseType));
  187:     return @part_response_id;
  188: }
  189: 
  190: sub get_display_part {
  191:     my ($partID,$symb)=@_;
  192:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
  193:     if (defined($display) and $display ne '') {
  194:         $display.= ' (<span class="LC_internal_info">'
  195:                   .&mt('Part ID: [_1]',$partID).'</span>)';
  196:     } else {
  197: 	$display=$partID;
  198:     }
  199:     return $display;
  200: }
  201: 
  202: sub reset_caches {
  203:     &reset_analyze_cache();
  204:     &reset_perm();
  205: }
  206: 
  207: {
  208:     my %analyze_cache;
  209:     my %analyze_cache_formkeys;
  210: 
  211:     sub reset_analyze_cache {
  212: 	undef(%analyze_cache);
  213:         undef(%analyze_cache_formkeys);
  214:     }
  215: 
  216:     sub get_analyze {
  217: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash,$type,$trial,$rndseed,$bubbles_per_row)=@_;
  218: 	my $key = "$symb\0$uname\0$udom";
  219:         if ($type eq 'randomizetry') {
  220:             if ($trial ne '') {
  221:                 $key .= "\0".$trial;
  222:             }
  223:         }
  224: 	if (exists($analyze_cache{$key})) {
  225:             my $getupdate = 0;
  226:             if (ref($add_to_hash) eq 'HASH') {
  227:                 foreach my $item (keys(%{$add_to_hash})) {
  228:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
  229:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
  230:                             $getupdate = 1;
  231:                             last;
  232:                         }
  233:                     } else {
  234:                         $getupdate = 1;
  235:                     }
  236:                 }
  237:             }
  238:             if (!$getupdate) {
  239:                 return $analyze_cache{$key};
  240:             }
  241:         }
  242: 
  243: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
  244: 	$url=&Apache::lonnet::clutter($url);
  245:         my %form = ('grade_target'      => 'analyze',
  246:                     'grade_domain'      => $udom,
  247:                     'grade_symb'        => $symb,
  248:                     'grade_courseid'    =>  $env{'request.course.id'},
  249:                     'grade_username'    => $uname,
  250:                     'grade_noincrement' => $no_increment);
  251:         if ($bubbles_per_row ne '') {
  252:             $form{'bubbles_per_row'} = $bubbles_per_row;
  253:         }
  254:         if ($type eq 'randomizetry') {
  255:             $form{'grade_questiontype'} = $type;
  256:             if ($rndseed ne '') {
  257:                 $form{'grade_rndseed'} = $rndseed;
  258:             }
  259:         }
  260:         if (ref($add_to_hash)) {
  261:             %form = (%form,%{$add_to_hash});
  262:         }
  263: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
  264: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
  265: 	my %analyze=&Apache::lonnet::str2hash($subresult);
  266:         if (ref($add_to_hash) eq 'HASH') {
  267:             $analyze_cache_formkeys{$key} = $add_to_hash;
  268:         } else {
  269:             $analyze_cache_formkeys{$key} = {};
  270:         }
  271: 	return $analyze_cache{$key} = \%analyze;
  272:     }
  273: 
  274:     sub get_order {
  275: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment,$type,$trial,$rndseed)=@_;
  276: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment,undef,$type,$trial,$rndseed);
  277: 	return $analyze->{"$partid.$respid.shown"};
  278:     }
  279: 
  280:     sub get_radiobutton_correct_foil {
  281: 	my ($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed)=@_;
  282: 	my $analyze = &get_analyze($symb,$uname,$udom,undef,undef,$type,$trial,$rndseed);
  283:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom,undef,$type,$trial,$rndseed);
  284:         if (ref($foils) eq 'ARRAY') {
  285: 	    foreach my $foil (@{$foils}) {
  286: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
  287: 		    return $foil;
  288: 	        }
  289: 	    }
  290: 	}
  291:     }
  292: 
  293:     sub scantron_partids_tograde {
  294:         my ($resource,$cid,$uname,$udom,$check_for_randomlist,$bubbles_per_row) = @_;
  295:         my (%analysis,@parts);
  296:         if (ref($resource)) {
  297:             my $symb = $resource->symb();
  298:             my $add_to_form;
  299:             if ($check_for_randomlist) {
  300:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
  301:             }
  302:             my $analyze = 
  303:                 &get_analyze($symb,$uname,$udom,undef,$add_to_form,
  304:                              undef,undef,undef,$bubbles_per_row);
  305:             if (ref($analyze) eq 'HASH') {
  306:                 %analysis = %{$analyze};
  307:             }
  308:             if (ref($analysis{'parts'}) eq 'ARRAY') {
  309:                 foreach my $part (@{$analysis{'parts'}}) {
  310:                     my ($id,$respid) = split(/\./,$part);
  311:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
  312:                         push(@parts,$part);
  313:                     }
  314:                 }
  315:             }
  316:         }
  317:         return (\%analysis,\@parts);
  318:     }
  319: 
  320: }
  321: 
  322: #--- Clean response type for display
  323: #--- Currently filters option/rank/radiobutton/match/essay/Task
  324: #        response types only.
  325: sub cleanRecord {
  326:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
  327: 	$uname,$udom,$type,$trial,$rndseed) = @_;
  328:     my $grayFont = '<span class="LC_internal_info">';
  329:     if ($response =~ /^(option|rank)$/) {
  330: 	my %answer=&Apache::lonnet::str2hash($answer);
  331: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  332: 	my ($toprow,$bottomrow);
  333: 	foreach my $foil (@$order) {
  334: 	    if ($grading{$foil} == 1) {
  335: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
  336: 	    } else {
  337: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
  338: 	    }
  339: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  340: 	}
  341: 	return '<blockquote><table border="1">'.
  342: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  343: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  344: 	    $bottomrow.'</tr></table></blockquote>';
  345:     } elsif ($response eq 'match') {
  346: 	my %answer=&Apache::lonnet::str2hash($answer);
  347: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  348: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
  349: 	my ($toprow,$middlerow,$bottomrow);
  350: 	foreach my $foil (@$order) {
  351: 	    my $item=shift(@items);
  352: 	    if ($grading{$foil} == 1) {
  353: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
  354: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
  355: 	    } else {
  356: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
  357: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
  358: 	    }
  359: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  360: 	}
  361: 	return '<blockquote><table border="1">'.
  362: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  363: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
  364: 	    $middlerow.'</tr>'.
  365: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  366: 	    $bottomrow.'</tr></table></blockquote>';
  367:     } elsif ($response eq 'radiobutton') {
  368: 	my %answer=&Apache::lonnet::str2hash($answer);
  369: 	my ($toprow,$bottomrow);
  370: 	my $correct = 
  371: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
  372: 	foreach my $foil (@$order) {
  373: 	    if (exists($answer{$foil})) {
  374: 		if ($foil eq $correct) {
  375: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
  376: 		} else {
  377: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
  378: 		}
  379: 	    } else {
  380: 		$toprow.='<td>'.&mt('false').'</td>';
  381: 	    }
  382: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  383: 	}
  384: 	return '<blockquote><table border="1">'.
  385: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  386: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  387: 	    $bottomrow.'</tr></table></blockquote>';
  388:     } elsif ($response eq 'essay') {
  389: 	if (! exists ($env{'form.'.$symb})) {
  390: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
  391: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
  392: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
  393: 
  394: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
  395: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
  396: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
  397: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
  398: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
  399: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
  400: 	}
  401: 	$answer =~ s-\n-<br />-g;
  402: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
  403:     } elsif ( $response eq 'organic') {
  404: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
  405: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
  406: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
  407: 	return $result;
  408:     } elsif ( $response eq 'Task') {
  409: 	if ( $answer eq 'SUBMITTED') {
  410: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
  411: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
  412: 	    return $result;
  413: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
  414: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
  415: 			       keys(%{$record}));
  416: 	    return join('<br />',($version,@matches));
  417: 			       
  418: 			       
  419: 	} else {
  420: 	    my $result =
  421: 		'<p>'
  422: 		.&mt('Overall result: [_1]',
  423: 		     $record->{$version."resource.$respid.$partid.status"})
  424: 		.'</p>';
  425: 	    
  426: 	    $result .= '<ul>';
  427: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
  428: 			     keys(%{$record}));
  429: 	    foreach my $grade (sort(@grade)) {
  430: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
  431: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
  432: 				     $dim, $record->{$grade}).
  433: 			  '</li>';
  434: 	    }
  435: 	    $result.='</ul>';
  436: 	    return $result;
  437: 	}
  438:     } elsif ( $response =~ m/(?:numerical|formula)/) {
  439: 	$answer = 
  440: 	    &Apache::loncommon::format_previous_attempt_value('submission',
  441: 							      $answer);
  442:     }
  443:     return $answer;
  444: }
  445: 
  446: #-- A couple of common js functions
  447: sub commonJSfunctions {
  448:     my $request = shift;
  449:     $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
  450:     function radioSelection(radioButton) {
  451: 	var selection=null;
  452: 	if (radioButton.length > 1) {
  453: 	    for (var i=0; i<radioButton.length; i++) {
  454: 		if (radioButton[i].checked) {
  455: 		    return radioButton[i].value;
  456: 		}
  457: 	    }
  458: 	} else {
  459: 	    if (radioButton.checked) return radioButton.value;
  460: 	}
  461: 	return selection;
  462:     }
  463: 
  464:     function pullDownSelection(selectOne) {
  465: 	var selection="";
  466: 	if (selectOne.length > 1) {
  467: 	    for (var i=0; i<selectOne.length; i++) {
  468: 		if (selectOne[i].selected) {
  469: 		    return selectOne[i].value;
  470: 		}
  471: 	    }
  472: 	} else {
  473:             // only one value it must be the selected one
  474: 	    return selectOne.value;
  475: 	}
  476:     }
  477: COMMONJSFUNCTIONS
  478: }
  479: 
  480: #--- Dumps the class list with usernames,list of sections,
  481: #--- section, ids and fullnames for each user.
  482: sub getclasslist {
  483:     my ($getsec,$filterlist,$getgroup) = @_;
  484:     my @getsec;
  485:     my @getgroup;
  486:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  487:     if (!ref($getsec)) {
  488: 	if ($getsec ne '' && $getsec ne 'all') {
  489: 	    @getsec=($getsec);
  490: 	}
  491:     } else {
  492: 	@getsec=@{$getsec};
  493:     }
  494:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
  495:     if (!ref($getgroup)) {
  496: 	if ($getgroup ne '' && $getgroup ne 'all') {
  497: 	    @getgroup=($getgroup);
  498: 	}
  499:     } else {
  500: 	@getgroup=@{$getgroup};
  501:     }
  502:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
  503: 
  504:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
  505:     # Bail out if we were unable to get the classlist
  506:     return if (! defined($classlist));
  507:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
  508:     #
  509:     my %sections;
  510:     my %fullnames;
  511:     foreach my $student (keys(%$classlist)) {
  512:         my $end      = 
  513:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
  514:         my $start    = 
  515:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
  516:         my $id       = 
  517:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
  518:         my $section  = 
  519:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
  520:         my $fullname = 
  521:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
  522:         my $status   = 
  523:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
  524:         my $group   = 
  525:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
  526: 	# filter students according to status selected
  527: 	if ($filterlist && (!($stu_status =~ /Any/))) {
  528: 	    if (!($stu_status =~ $status)) {
  529: 		delete($classlist->{$student});
  530: 		next;
  531: 	    }
  532: 	}
  533: 	# filter students according to groups selected
  534: 	my @stu_groups = split(/,/,$group);
  535: 	if (@getgroup) {
  536: 	    my $exclude = 1;
  537: 	    foreach my $grp (@getgroup) {
  538: 	        foreach my $stu_group (@stu_groups) {
  539: 	            if ($stu_group eq $grp) {
  540: 	                $exclude = 0;
  541:     	            } 
  542: 	        }
  543:     	        if (($grp eq 'none') && !$group) {
  544:         	        $exclude = 0;
  545:         	}
  546: 	    }
  547: 	    if ($exclude) {
  548: 	        delete($classlist->{$student});
  549: 	    }
  550: 	}
  551: 	$section = ($section ne '' ? $section : 'none');
  552: 	if (&canview($section)) {
  553: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
  554: 		$sections{$section}++;
  555: 		if ($classlist->{$student}) {
  556: 		    $fullnames{$student}=$fullname;
  557: 		}
  558: 	    } else {
  559: 		delete($classlist->{$student});
  560: 	    }
  561: 	} else {
  562: 	    delete($classlist->{$student});
  563: 	}
  564:     }
  565:     my %seen = ();
  566:     my @sections = sort(keys(%sections));
  567:     return ($classlist,\@sections,\%fullnames);
  568: }
  569: 
  570: sub canmodify {
  571:     my ($sec)=@_;
  572:     if ($perm{'mgr'}) {
  573: 	if (!defined($perm{'mgr_section'})) {
  574: 	    # can modify whole class
  575: 	    return 1;
  576: 	} else {
  577: 	    if ($sec eq $perm{'mgr_section'}) {
  578: 		#can modify the requested section
  579: 		return 1;
  580: 	    } else {
  581: 		# can't modify the request section
  582: 		return 0;
  583: 	    }
  584: 	}
  585:     }
  586:     #can't modify
  587:     return 0;
  588: }
  589: 
  590: sub canview {
  591:     my ($sec)=@_;
  592:     if ($perm{'vgr'}) {
  593: 	if (!defined($perm{'vgr_section'})) {
  594: 	    # can modify whole class
  595: 	    return 1;
  596: 	} else {
  597: 	    if ($sec eq $perm{'vgr_section'}) {
  598: 		#can modify the requested section
  599: 		return 1;
  600: 	    } else {
  601: 		# can't modify the request section
  602: 		return 0;
  603: 	    }
  604: 	}
  605:     }
  606:     #can't modify
  607:     return 0;
  608: }
  609: 
  610: #--- Retrieve the grade status of a student for all the parts
  611: sub student_gradeStatus {
  612:     my ($symb,$udom,$uname,$partlist) = @_;
  613:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
  614:     my %partstatus = ();
  615:     foreach (@$partlist) {
  616: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
  617: 	$status              = 'nothing' if ($status eq '');
  618: 	$partstatus{$_}      = $status;
  619: 	my $subkey           = "resource.$_.submitted_by";
  620: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
  621:     }
  622:     return %partstatus;
  623: }
  624: 
  625: # hidden form and javascript that calls the form
  626: # Use by verifyscript and viewgrades
  627: # Shows a student's view of problem and submission
  628: sub jscriptNform {
  629:     my ($symb) = @_;
  630:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  631:     my $jscript= &Apache::lonhtmlcommon::scripttag(
  632: 	'    function viewOneStudent(user,domain) {'."\n".
  633: 	'	document.onestudent.student.value = user;'."\n".
  634: 	'	document.onestudent.userdom.value = domain;'."\n".
  635: 	'	document.onestudent.submit();'."\n".
  636: 	'    }'."\n".
  637: 	"\n");
  638:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
  639: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  640: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
  641: 	'<input type="hidden" name="command" value="submission" />'."\n".
  642: 	'<input type="hidden" name="student" value="" />'."\n".
  643: 	'<input type="hidden" name="userdom" value="" />'."\n".
  644: 	'</form>'."\n";
  645:     return $jscript;
  646: }
  647: 
  648: 
  649: 
  650: # Given the score (as a number [0-1] and the weight) what is the final
  651: # point value? This function will round to the nearest tenth, third,
  652: # or quarter if one of those is within the tolerance of .00001.
  653: sub compute_points {
  654:     my ($score, $weight) = @_;
  655:     
  656:     my $tolerance = .00001;
  657:     my $points = $score * $weight;
  658: 
  659:     # Check for nearness to 1/x.
  660:     my $check_for_nearness = sub {
  661:         my ($factor) = @_;
  662:         my $num = ($points * $factor) + $tolerance;
  663:         my $floored_num = floor($num);
  664:         if ($num - $floored_num < 2 * $tolerance * $factor) {
  665:             return $floored_num / $factor;
  666:         }
  667:         return $points;
  668:     };
  669: 
  670:     $points = $check_for_nearness->(10);
  671:     $points = $check_for_nearness->(3);
  672:     $points = $check_for_nearness->(4);
  673:     
  674:     return $points;
  675: }
  676: 
  677: #------------------ End of general use routines --------------------
  678: 
  679: #
  680: # Find most similar essay
  681: #
  682: 
  683: sub most_similar {
  684:     my ($uname,$udom,$uessay,$old_essays)=@_;
  685: 
  686: # ignore spaces and punctuation
  687: 
  688:     $uessay=~s/\W+/ /gs;
  689: 
  690: # ignore empty submissions (occuring when only files are sent)
  691: 
  692:     unless ($uessay=~/\w+/s) { return ''; }
  693: 
  694: # these will be returned. Do not care if not at least 50 percent similar
  695:     my $limit=0.6;
  696:     my $sname='';
  697:     my $sdom='';
  698:     my $scrsid='';
  699:     my $sessay='';
  700: # go through all essays ...
  701:     foreach my $tkey (keys(%$old_essays)) {
  702: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
  703: # ... except the same student
  704:         next if (($tname eq $uname) && ($tdom eq $udom));
  705: 	my $tessay=$old_essays->{$tkey};
  706: 	$tessay=~s/\W+/ /gs;
  707: # String similarity gives up if not even limit
  708: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
  709: # Found one
  710: 	if ($tsimilar>$limit) {
  711: 	    $limit=$tsimilar;
  712: 	    $sname=$tname;
  713: 	    $sdom=$tdom;
  714: 	    $scrsid=$tcrsid;
  715: 	    $sessay=$old_essays->{$tkey};
  716: 	}
  717:     }
  718:     if ($limit>0.6) {
  719:        return ($sname,$sdom,$scrsid,$sessay,$limit);
  720:     } else {
  721:        return ('','','','',0);
  722:     }
  723: }
  724: 
  725: #-------------------------------------------------------------------
  726: 
  727: #------------------------------------ Receipt Verification Routines
  728: #
  729: 
  730: sub initialverifyreceipt {
  731:    my ($request,$symb) = @_;
  732:    &commonJSfunctions($request);
  733:    return '<form name="gradingMenu"><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
  734:         &Apache::lonnet::recprefix($env{'request.course.id'}).
  735:         '-<input type="text" name="receipt" size="4" />'.
  736:         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  737:         '<input type="hidden" name="command" value="verify" />'.
  738:         "</form>\n";
  739: }
  740: 
  741: #--- Check whether a receipt number is valid.---
  742: sub verifyreceipt {
  743:     my ($request,$symb)  = @_;
  744: 
  745:     my $courseid = $env{'request.course.id'};
  746:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
  747: 	$env{'form.receipt'};
  748:     $receipt     =~ s/[^\-\d]//g;
  749: 
  750:     my $title.=
  751: 	'<h3><span class="LC_info">'.
  752: 	&mt('Verifying Receipt Number [_1]',$receipt).
  753: 	'</span></h3>'."\n";
  754: 
  755:     my ($string,$contents,$matches) = ('','',0);
  756:     my (undef,undef,$fullname) = &getclasslist('all','0');
  757:     
  758:     my $receiptparts=0;
  759:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
  760: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
  761:     my $parts=['0'];
  762:     if ($receiptparts) {
  763:         my $res_error; 
  764:         ($parts)=&response_type($symb,\$res_error);
  765:         if ($res_error) {
  766:             return &navmap_errormsg();
  767:         } 
  768:     }
  769:     
  770:     my $header = 
  771: 	&Apache::loncommon::start_data_table().
  772: 	&Apache::loncommon::start_data_table_header_row().
  773: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
  774: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
  775: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
  776:     if ($receiptparts) {
  777: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
  778:     }
  779:     $header.=
  780: 	&Apache::loncommon::end_data_table_header_row();
  781: 
  782:     foreach (sort 
  783: 	     {
  784: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  785: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  786: 		 }
  787: 		 return $a cmp $b;
  788: 	     } (keys(%$fullname))) {
  789: 	my ($uname,$udom)=split(/\:/);
  790: 	foreach my $part (@$parts) {
  791: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
  792: 		$contents.=
  793: 		    &Apache::loncommon::start_data_table_row().
  794: 		    '<td>&nbsp;'."\n".
  795: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
  796: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
  797: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
  798: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
  799: 		if ($receiptparts) {
  800: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
  801: 		}
  802: 		$contents.= 
  803: 		    &Apache::loncommon::end_data_table_row()."\n";
  804: 		
  805: 		$matches++;
  806: 	    }
  807: 	}
  808:     }
  809:     if ($matches == 0) {
  810:         $string = $title
  811:                  .'<p class="LC_warning">'
  812:                  .&mt('No match found for the above receipt number.')
  813:                  .'</p>';
  814:     } else {
  815: 	$string = &jscriptNform($symb).$title.
  816: 	    '<p>'.
  817: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
  818: 	    '</p>'.
  819: 	    $header.
  820: 	    $contents.
  821: 	    &Apache::loncommon::end_data_table()."\n";
  822:     }
  823:     return $string;
  824: }
  825: 
  826: #--- This is called by a number of programs.
  827: #--- Called from the Grading Menu - View/Grade an individual student
  828: #--- Also called directly when one clicks on the subm button 
  829: #    on the problem page.
  830: sub listStudents {
  831:     my ($request,$symb,$submitonly) = @_;
  832: 
  833:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
  834:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
  835:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
  836:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
  837:     unless ($submitonly) {
  838:        $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
  839:     }
  840: 
  841:     my $result='';
  842:     my $res_error;
  843:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
  844: 
  845:     my %lt = &Apache::lonlocal::texthash (
  846: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
  847: 		'single'   => 'Please select the student before clicking on the Next button.',
  848: 	     );
  849:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
  850:     function checkSelect(checkBox) {
  851: 	var ctr=0;
  852: 	var sense="";
  853: 	if (checkBox.length > 1) {
  854: 	    for (var i=0; i<checkBox.length; i++) {
  855: 		if (checkBox[i].checked) {
  856: 		    ctr++;
  857: 		}
  858: 	    }
  859: 	    sense = '$lt{'multiple'}';
  860: 	} else {
  861: 	    if (checkBox.checked) {
  862: 		ctr = 1;
  863: 	    }
  864: 	    sense = '$lt{'single'}';
  865: 	}
  866: 	if (ctr == 0) {
  867: 	    alert(sense);
  868: 	    return false;
  869: 	}
  870: 	document.gradesub.submit();
  871:     }
  872: 
  873:     function reLoadList(formname) {
  874: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
  875: 	formname.command.value = 'submission';
  876: 	formname.submit();
  877:     }
  878: LISTJAVASCRIPT
  879: 
  880:     &commonJSfunctions($request);
  881:     $request->print($result);
  882: 
  883:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
  884: 	"\n";
  885: 	
  886:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
  887:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
  888:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
  889:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
  890:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
  891:                   .&Apache::lonhtmlcommon::row_closure();
  892:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
  893:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
  894:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
  895:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
  896:                   .&Apache::lonhtmlcommon::row_closure();
  897: 
  898:     my $submission_options;
  899:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  900:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
  901:     $env{'form.Status'} = $saveStatus;
  902:     $submission_options.=
  903:         '<span class="LC_nobreak">'.
  904:         '<label><input type="radio" name="lastSub" value="lastonly" /> '.
  905:         &mt('last submission only').' </label></span>'."\n".
  906:         '<span class="LC_nobreak">'.
  907:         '<label><input type="radio" name="lastSub" value="last" /> '.
  908:         &mt('last submission &amp; parts info').' </label></span>'."\n".
  909:         '<span class="LC_nobreak">'.
  910:         '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.
  911:         &mt('by dates and submissions').'</label></span>'."\n".
  912:         '<span class="LC_nobreak">'.
  913:         '<label><input type="radio" name="lastSub" value="all" /> '.
  914:         &mt('all details').'</label></span>';
  915:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
  916:                   .$submission_options
  917:                   .&Apache::lonhtmlcommon::row_closure();
  918: 
  919:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
  920:                   .'<select name="increment">'
  921:                   .'<option value="1">'.&mt('Whole Points').'</option>'
  922:                   .'<option value=".5">'.&mt('Half Points').'</option>'
  923:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
  924:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
  925:                   .'</select>'
  926:                   .&Apache::lonhtmlcommon::row_closure();
  927: 
  928:     $gradeTable .= 
  929:         &build_section_inputs().
  930: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
  931: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  932: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
  933: 
  934:     if (exists($env{'form.Status'})) {
  935: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
  936:     } else {
  937:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
  938:                       .&Apache::lonhtmlcommon::StatusOptions(
  939:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
  940:                       .&Apache::lonhtmlcommon::row_closure();
  941:     }
  942: 
  943:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
  944:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
  945:                   .&Apache::lonhtmlcommon::row_closure(1)
  946:                   .&Apache::lonhtmlcommon::end_pick_box();
  947: 
  948:     $gradeTable .= '<p>'
  949:                   .&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"
  950:                   .'<input type="hidden" name="command" value="processGroup" />'
  951:                   .'</p>';
  952: 
  953: # checkall buttons
  954:     $gradeTable.=&check_script('gradesub', 'stuinfo');
  955:     $gradeTable.='<input type="button" '."\n".
  956:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
  957:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
  958:     $gradeTable.=&check_buttons();
  959:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
  960:     $gradeTable.= &Apache::loncommon::start_data_table().
  961: 	&Apache::loncommon::start_data_table_header_row();
  962:     my $loop = 0;
  963:     while ($loop < 2) {
  964: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
  965: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
  966: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
  967: 	    foreach my $part (sort(@$partlist)) {
  968: 		my $display_part=
  969: 		    &get_display_part((split(/_/,$part))[0],$symb);
  970: 		$gradeTable.=
  971: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
  972: 	    }
  973: 	} elsif ($submitonly eq 'queued') {
  974: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
  975: 	}
  976: 	$loop++;
  977: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
  978:     }
  979:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
  980: 
  981:     my $ctr = 0;
  982:     foreach my $student (sort 
  983: 			 {
  984: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  985: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  986: 			     }
  987: 			     return $a cmp $b;
  988: 			 }
  989: 			 (keys(%$fullname))) {
  990: 	my ($uname,$udom) = split(/:/,$student);
  991: 
  992: 	my %status = ();
  993: 
  994: 	if ($submitonly eq 'queued') {
  995: 	    my %queue_status = 
  996: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
  997: 							$udom,$uname);
  998: 	    next if (!defined($queue_status{'gradingqueue'}));
  999: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
 1000: 	}
 1001: 
 1002: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1003: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
 1004: 	    my $submitted = 0;
 1005: 	    my $graded = 0;
 1006: 	    my $incorrect = 0;
 1007: 	    foreach (keys(%status)) {
 1008: 		$submitted = 1 if ($status{$_} ne 'nothing');
 1009: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
 1010: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
 1011: 		
 1012: 		my ($foo,$partid,$foo1) = split(/\./,$_);
 1013: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 1014: 		    $submitted = 0;
 1015: 		    my ($part)=split(/\./,$partid);
 1016: 		    $gradeTable.='<input type="hidden" name="'.
 1017: 			$student.':'.$part.':submitted_by" value="'.
 1018: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
 1019: 		}
 1020: 	    }
 1021: 	    
 1022: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 1023: 				     $submitonly eq 'incorrect' ||
 1024: 				     $submitonly eq 'graded'));
 1025: 	    next if (!$graded && ($submitonly eq 'graded'));
 1026: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 1027: 	}
 1028: 
 1029: 	$ctr++;
 1030: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
 1031:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
 1032: 	if ( $perm{'vgr'} eq 'F' ) {
 1033: 	    if ($ctr%2 ==1) {
 1034: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
 1035: 	    }
 1036: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
 1037:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
 1038:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
 1039: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
 1040: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
 1041: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
 1042: 
 1043: 	    if ($submitonly ne 'all') {
 1044: 		foreach (sort(keys(%status))) {
 1045: 		    next if ($_ =~ /^resource.*?submitted_by$/);
 1046: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
 1047: 		}
 1048: 	    }
 1049: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
 1050: 	    if ($ctr%2 ==0) {
 1051: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
 1052: 	    }
 1053: 	}
 1054:     }
 1055:     if ($ctr%2 ==1) {
 1056: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
 1057: 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1058: 		foreach (@$partlist) {
 1059: 		    $gradeTable.='<td>&nbsp;</td>';
 1060: 		}
 1061: 	    } elsif ($submitonly eq 'queued') {
 1062: 		$gradeTable.='<td>&nbsp;</td>';
 1063: 	    }
 1064: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
 1065:     }
 1066: 
 1067:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
 1068:         '<input type="button" '.
 1069:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
 1070:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
 1071:     if ($ctr == 0) {
 1072: 	my $num_students=(scalar(keys(%$fullname)));
 1073: 	if ($num_students eq 0) {
 1074: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
 1075: 	} else {
 1076: 	    my $submissions='submissions';
 1077: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
 1078: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
 1079: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
 1080: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
 1081: 		&mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
 1082: 		    $num_students).
 1083: 		'</span><br />';
 1084: 	}
 1085:     } elsif ($ctr == 1) {
 1086: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
 1087:     }
 1088:     $request->print($gradeTable);
 1089:     return '';
 1090: }
 1091: 
 1092: #---- Called from the listStudents routine
 1093: 
 1094: sub check_script {
 1095:     my ($form, $type)=@_;
 1096:     my $chkallscript= &Apache::lonhtmlcommon::scripttag('
 1097:     function checkall() {
 1098:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1099:             ele = document.forms.'.$form.'.elements[i];
 1100:             if (ele.name == "'.$type.'") {
 1101:             document.forms.'.$form.'.elements[i].checked=true;
 1102:                                        }
 1103:         }
 1104:     }
 1105: 
 1106:     function checksec() {
 1107:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1108:             ele = document.forms.'.$form.'.elements[i];
 1109:            string = document.forms.'.$form.'.chksec.value;
 1110:            if
 1111:           (ele.value.indexOf(":::SECTION"+string)>0) {
 1112:               document.forms.'.$form.'.elements[i].checked=true;
 1113:             }
 1114:         }
 1115:     }
 1116: 
 1117: 
 1118:     function uncheckall() {
 1119:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1120:             ele = document.forms.'.$form.'.elements[i];
 1121:             if (ele.name == "'.$type.'") {
 1122:             document.forms.'.$form.'.elements[i].checked=false;
 1123:                                        }
 1124:         }
 1125:     }
 1126: 
 1127: '."\n");
 1128:     return $chkallscript;
 1129: }
 1130: 
 1131: sub check_buttons {
 1132:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
 1133:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
 1134:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
 1135:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
 1136:     return $buttons;
 1137: }
 1138: 
 1139: #     Displays the submissions for one student or a group of students
 1140: sub processGroup {
 1141:     my ($request,$symb)  = @_;
 1142:     my $ctr        = 0;
 1143:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1144:     my $total      = scalar(@stuchecked)-1;
 1145: 
 1146:     foreach my $student (@stuchecked) {
 1147: 	my ($uname,$udom,$fullname) = split(/:/,$student);
 1148: 	$env{'form.student'}        = $uname;
 1149: 	$env{'form.userdom'}        = $udom;
 1150: 	$env{'form.fullname'}       = $fullname;
 1151: 	&submission($request,$ctr,$total,$symb);
 1152: 	$ctr++;
 1153:     }
 1154:     return '';
 1155: }
 1156: 
 1157: #------------------------------------------------------------------------------------
 1158: #
 1159: #-------------------------- Next few routines handles grading by student, essentially
 1160: #                           handles essay response type problem/part
 1161: #
 1162: #--- Javascript to handle the submission page functionality ---
 1163: sub sub_page_js {
 1164:     my $request = shift;
 1165: 	    my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 1166:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1167:     function updateRadio(formname,id,weight) {
 1168: 	var gradeBox = formname["GD_BOX"+id];
 1169: 	var radioButton = formname["RADVAL"+id];
 1170: 	var oldpts = formname["oldpts"+id].value;
 1171: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
 1172: 	gradeBox.value = pts;
 1173: 	var resetbox = false;
 1174: 	if (isNaN(pts) || pts < 0) {
 1175: 	    alert("$alertmsg"+pts);
 1176: 	    for (var i=0; i<radioButton.length; i++) {
 1177: 		if (radioButton[i].checked) {
 1178: 		    gradeBox.value = i;
 1179: 		    resetbox = true;
 1180: 		}
 1181: 	    }
 1182: 	    if (!resetbox) {
 1183: 		formtextbox.value = "";
 1184: 	    }
 1185: 	    return;
 1186: 	}
 1187: 
 1188: 	if (pts > weight) {
 1189: 	    var resp = confirm("You entered a value ("+pts+
 1190: 			       ") greater than the weight for the part. Accept?");
 1191: 	    if (resp == false) {
 1192: 		gradeBox.value = oldpts;
 1193: 		return;
 1194: 	    }
 1195: 	}
 1196: 
 1197: 	for (var i=0; i<radioButton.length; i++) {
 1198: 	    radioButton[i].checked=false;
 1199: 	    if (pts == i && pts != "") {
 1200: 		radioButton[i].checked=true;
 1201: 	    }
 1202: 	}
 1203: 	updateSelect(formname,id);
 1204: 	formname["stores"+id].value = "0";
 1205:     }
 1206: 
 1207:     function writeBox(formname,id,pts) {
 1208: 	var gradeBox = formname["GD_BOX"+id];
 1209: 	if (checkSolved(formname,id) == 'update') {
 1210: 	    gradeBox.value = pts;
 1211: 	} else {
 1212: 	    var oldpts = formname["oldpts"+id].value;
 1213: 	    gradeBox.value = oldpts;
 1214: 	    var radioButton = formname["RADVAL"+id];
 1215: 	    for (var i=0; i<radioButton.length; i++) {
 1216: 		radioButton[i].checked=false;
 1217: 		if (i == oldpts) {
 1218: 		    radioButton[i].checked=true;
 1219: 		}
 1220: 	    }
 1221: 	}
 1222: 	formname["stores"+id].value = "0";
 1223: 	updateSelect(formname,id);
 1224: 	return;
 1225:     }
 1226: 
 1227:     function clearRadBox(formname,id) {
 1228: 	if (checkSolved(formname,id) == 'noupdate') {
 1229: 	    updateSelect(formname,id);
 1230: 	    return;
 1231: 	}
 1232: 	gradeSelect = formname["GD_SEL"+id];
 1233: 	for (var i=0; i<gradeSelect.length; i++) {
 1234: 	    if (gradeSelect[i].selected) {
 1235: 		var selectx=i;
 1236: 	    }
 1237: 	}
 1238: 	var stores = formname["stores"+id];
 1239: 	if (selectx == stores.value) { return };
 1240: 	var gradeBox = formname["GD_BOX"+id];
 1241: 	gradeBox.value = "";
 1242: 	var radioButton = formname["RADVAL"+id];
 1243: 	for (var i=0; i<radioButton.length; i++) {
 1244: 	    radioButton[i].checked=false;
 1245: 	}
 1246: 	stores.value = selectx;
 1247:     }
 1248: 
 1249:     function checkSolved(formname,id) {
 1250: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
 1251: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
 1252: 	    if (!reply) {return "noupdate";}
 1253: 	    formname.overRideScore.value = 'yes';
 1254: 	}
 1255: 	return "update";
 1256:     }
 1257: 
 1258:     function updateSelect(formname,id) {
 1259: 	formname["GD_SEL"+id][0].selected = true;
 1260: 	return;
 1261:     }
 1262: 
 1263: //=========== Check that a point is assigned for all the parts  ============
 1264:     function checksubmit(formname,val,total,parttot) {
 1265: 	formname.gradeOpt.value = val;
 1266: 	if (val == "Save & Next") {
 1267: 	    for (i=0;i<=total;i++) {
 1268: 		for (j=0;j<parttot;j++) {
 1269: 		    var partid = formname["partid"+i+"_"+j].value;
 1270: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1271: 			var points = formname["GD_BOX"+i+"_"+partid].value;
 1272: 			if (points == "") {
 1273: 			    var name = formname["name"+i].value;
 1274: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
 1275: 			    var resp = confirm("You did not assign a score for "+studentID+
 1276: 					       ", part "+partid+". Continue?");
 1277: 			    if (resp == false) {
 1278: 				formname["GD_BOX"+i+"_"+partid].focus();
 1279: 				return false;
 1280: 			    }
 1281: 			}
 1282: 		    }
 1283: 		    
 1284: 		}
 1285: 	    }
 1286: 	    
 1287: 	}
 1288: 	formname.submit();
 1289:     }
 1290: 
 1291: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1292:     function checkSubmitPage(formname,total) {
 1293: 	noscore = new Array(100);
 1294: 	var ptr = 0;
 1295: 	for (i=1;i<total;i++) {
 1296: 	    var partid = formname["q_"+i].value;
 1297: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1298: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1299: 		var status = formname["solved"+i+"_"+partid].value;
 1300: 		if (points == "" && status != "correct_by_student") {
 1301: 		    noscore[ptr] = i;
 1302: 		    ptr++;
 1303: 		}
 1304: 	    }
 1305: 	}
 1306: 	if (ptr != 0) {
 1307: 	    var sense = ptr == 1 ? ": " : "s: ";
 1308: 	    var prolist = "";
 1309: 	    if (ptr == 1) {
 1310: 		prolist = noscore[0];
 1311: 	    } else {
 1312: 		var i = 0;
 1313: 		while (i < ptr-1) {
 1314: 		    prolist += noscore[i]+", ";
 1315: 		    i++;
 1316: 		}
 1317: 		prolist += "and "+noscore[i];
 1318: 	    }
 1319: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1320: 	    if (resp == false) {
 1321: 		return false;
 1322: 	    }
 1323: 	}
 1324: 
 1325: 	formname.submit();
 1326:     }
 1327: SUBJAVASCRIPT
 1328: }
 1329: 
 1330: #--- javascript for essay type problem --
 1331: sub sub_page_kw_js {
 1332:     my $request = shift;
 1333:     my $iconpath = $request->dir_config('lonIconsURL');
 1334:     &commonJSfunctions($request);
 1335: 
 1336:     my $inner_js_msg_central= (<<INNERJS);
 1337: <script type="text/javascript">
 1338:     function checkInput() {
 1339:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1340:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1341:       var usrctr = document.msgcenter.usrctr.value;
 1342:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1343:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1344: 
 1345:       var msgchk = "";
 1346:       if (document.msgcenter.subchk.checked) {
 1347:          msgchk = "msgsub,";
 1348:       }
 1349:       var includemsg = 0;
 1350:       for (var i=1; i<=nmsg; i++) {
 1351:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1352:           var frmmsg = document.msgcenter["msg"+i];
 1353:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1354:           var showflg = opener.document.SCORE["shownOnce"+i];
 1355:           showflg.value = "1";
 1356:           var chkbox = document.msgcenter["msgn"+i];
 1357:           if (chkbox.checked) {
 1358:              msgchk += "savemsg"+i+",";
 1359:              includemsg = 1;
 1360:           }
 1361:       }
 1362:       if (document.msgcenter.newmsgchk.checked) {
 1363:          msgchk += "newmsg"+usrctr;
 1364:          includemsg = 1;
 1365:       }
 1366:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1367:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1368:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1369:       includemsg.value = msgchk;
 1370: 
 1371:       self.close()
 1372: 
 1373:     }
 1374: </script>
 1375: INNERJS
 1376: 
 1377:     my $inner_js_highlight_central= (<<INNERJS);
 1378: <script type="text/javascript">
 1379:     function updateChoice(flag) {
 1380:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1381:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1382:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1383:       opener.document.SCORE.refresh.value = "on";
 1384:       if (opener.document.SCORE.keywords.value!=""){
 1385:          opener.document.SCORE.submit();
 1386:       }
 1387:       self.close()
 1388:     }
 1389: </script>
 1390: INNERJS
 1391: 
 1392:     my $start_page_msg_central = 
 1393:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1394: 				       {'js_ready'  => 1,
 1395: 					'only_body' => 1,
 1396: 					'bgcolor'   =>'#FFFFFF',});
 1397:     my $end_page_msg_central = 
 1398: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1399: 
 1400: 
 1401:     my $start_page_highlight_central = 
 1402:         &Apache::loncommon::start_page('Highlight Central',
 1403: 				       $inner_js_highlight_central,
 1404: 				       {'js_ready'  => 1,
 1405: 					'only_body' => 1,
 1406: 					'bgcolor'   =>'#FFFFFF',});
 1407:     my $end_page_highlight_central = 
 1408: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1409: 
 1410:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1411:     $docopen=~s/^document\.//;
 1412:     my %lt = &Apache::lonlocal::texthash(
 1413:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
 1414:                 plse => 'Please select a word or group of words from document and then click this link.',
 1415:                 adds => 'Add selection to keyword list? Edit if desired.',
 1416:                 comp => 'Compose Message for: ',
 1417:                 incl => 'Include',
 1418:                 type => 'Type',
 1419:                 subj => 'Subject',
 1420:                 mesa => 'Message',
 1421:                 new  => 'New',
 1422:                 save => 'Save',
 1423:                 canc => 'Cancel',
 1424:                 kehi => 'Keyword Highlight Options',
 1425:                 txtc => 'Text Color',
 1426:                 font => 'Font Size',
 1427:                 fnst => 'Font Style',
 1428:              );
 1429:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1430: 
 1431: //===================== Show list of keywords ====================
 1432:   function keywords(formname) {
 1433:     var nret = prompt("$lt{'keyw'}",formname.keywords.value);
 1434:     if (nret==null) return;
 1435:     formname.keywords.value = nret;
 1436: 
 1437:     if (formname.keywords.value != "") {
 1438: 	formname.refresh.value = "on";
 1439: 	formname.submit();
 1440:     }
 1441:     return;
 1442:   }
 1443: 
 1444: //===================== Script to view submitted by ==================
 1445:   function viewSubmitter(submitter) {
 1446:     document.SCORE.refresh.value = "on";
 1447:     document.SCORE.NCT.value = "1";
 1448:     document.SCORE.unamedom0.value = submitter;
 1449:     document.SCORE.submit();
 1450:     return;
 1451:   }
 1452: 
 1453: //===================== Script to add keyword(s) ==================
 1454:   function getSel() {
 1455:     if (document.getSelection) txt = document.getSelection();
 1456:     else if (document.selection) txt = document.selection.createRange().text;
 1457:     else return;
 1458:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1459:     if (cleantxt=="") {
 1460: 	alert("$lt{'plse'}");
 1461: 	return;
 1462:     }
 1463:     var nret = prompt("$lt{'adds'}",cleantxt);
 1464:     if (nret==null) return;
 1465:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1466:     if (document.SCORE.keywords.value != "") {
 1467: 	document.SCORE.refresh.value = "on";
 1468: 	document.SCORE.submit();
 1469:     }
 1470:     return;
 1471:   }
 1472: 
 1473: //====================== Script for composing message ==============
 1474:    // preload images
 1475:    img1 = new Image();
 1476:    img1.src = "$iconpath/mailbkgrd.gif";
 1477:    img2 = new Image();
 1478:    img2.src = "$iconpath/mailto.gif";
 1479: 
 1480:   function msgCenter(msgform,usrctr,fullname) {
 1481:     var Nmsg  = msgform.savemsgN.value;
 1482:     savedMsgHeader(Nmsg,usrctr,fullname);
 1483:     var subject = msgform.msgsub.value;
 1484:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1485:     re = /msgsub/;
 1486:     var shwsel = "";
 1487:     if (re.test(msgchk)) { shwsel = "checked" }
 1488:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1489:     displaySubject(checkEntities(subject),shwsel);
 1490:     for (var i=1; i<=Nmsg; i++) {
 1491: 	var testmsg = "savemsg"+i+",";
 1492: 	re = new RegExp(testmsg,"g");
 1493: 	shwsel = "";
 1494: 	if (re.test(msgchk)) { shwsel = "checked" }
 1495: 	var message = document.SCORE["savemsg"+i].value;
 1496: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1497: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1498: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1499:     }
 1500:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1501:     shwsel = "";
 1502:     re = /newmsg/;
 1503:     if (re.test(msgchk)) { shwsel = "checked" }
 1504:     newMsg(newmsg,shwsel);
 1505:     msgTail(); 
 1506:     return;
 1507:   }
 1508: 
 1509:   function checkEntities(strx) {
 1510:     if (strx.length == 0) return strx;
 1511:     var orgStr = ["&", "<", ">", '"']; 
 1512:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1513:     var counter = 0;
 1514:     while (counter < 4) {
 1515: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1516: 	counter++;
 1517:     }
 1518:     return strx;
 1519:   }
 1520: 
 1521:   function strReplace(strx, orgStr, newStr) {
 1522:     return strx.split(orgStr).join(newStr);
 1523:   }
 1524: 
 1525:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1526:     var height = 70*Nmsg+250;
 1527:     if (height > 600) {
 1528: 	height = 600;
 1529:     }
 1530:     var xpos = (screen.width-600)/2;
 1531:     xpos = (xpos < 0) ? '0' : xpos;
 1532:     var ypos = (screen.height-height)/2-30;
 1533:     ypos = (ypos < 0) ? '0' : ypos;
 1534: 
 1535:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
 1536:     pWin.focus();
 1537:     pDoc = pWin.document;
 1538:     pDoc.$docopen;
 1539:     pDoc.write('$start_page_msg_central');
 1540: 
 1541:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1542:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1543:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;$lt{'comp'}\"+fullname+\"<\\/span><\\/h3><br /><br />");
 1544: 
 1545:     pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
 1546:     pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
 1547:     pDoc.write("<td><b>$lt{'type'}<\\/b><\\/td><td><b>$lt{'incl'}<\\/b><\\/td><td><b>$lt{'mesa'}<\\/td><\\/tr>");
 1548: }
 1549:     function displaySubject(msg,shwsel) {
 1550:     pDoc = pWin.document;
 1551:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1552:     pDoc.write("<td>$lt{'subj'}<\\/td>");
 1553:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1554:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
 1555: }
 1556: 
 1557:   function displaySavedMsg(ctr,msg,shwsel) {
 1558:     pDoc = pWin.document;
 1559:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1560:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
 1561:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1562:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
 1563: }
 1564: 
 1565:   function newMsg(newmsg,shwsel) {
 1566:     pDoc = pWin.document;
 1567:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1568:     pDoc.write("<td align=\\"center\\">$lt{'new'}<\\/td>");
 1569:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1570:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
 1571: }
 1572: 
 1573:   function msgTail() {
 1574:     pDoc = pWin.document;
 1575:     pDoc.write("<\\/table>");
 1576:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1577:     pDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1578:     pDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
 1579:     pDoc.write("<\\/form>");
 1580:     pDoc.write('$end_page_msg_central');
 1581:     pDoc.close();
 1582: }
 1583: 
 1584: //====================== Script for keyword highlight options ==============
 1585:   function kwhighlight() {
 1586:     var kwclr    = document.SCORE.kwclr.value;
 1587:     var kwsize   = document.SCORE.kwsize.value;
 1588:     var kwstyle  = document.SCORE.kwstyle.value;
 1589:     var redsel = "";
 1590:     var grnsel = "";
 1591:     var blusel = "";
 1592:     if (kwclr=="red")   {var redsel="checked"};
 1593:     if (kwclr=="green") {var grnsel="checked"};
 1594:     if (kwclr=="blue")  {var blusel="checked"};
 1595:     var sznsel = "";
 1596:     var sz1sel = "";
 1597:     var sz2sel = "";
 1598:     if (kwsize=="0")  {var sznsel="checked"};
 1599:     if (kwsize=="+1") {var sz1sel="checked"};
 1600:     if (kwsize=="+2") {var sz2sel="checked"};
 1601:     var synsel = "";
 1602:     var syisel = "";
 1603:     var sybsel = "";
 1604:     if (kwstyle=="")    {var synsel="checked"};
 1605:     if (kwstyle=="<i>") {var syisel="checked"};
 1606:     if (kwstyle=="<b>") {var sybsel="checked"};
 1607:     highlightCentral();
 1608:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
 1609:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
 1610:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
 1611:     highlightend();
 1612:     return;
 1613:   }
 1614: 
 1615:   function highlightCentral() {
 1616: //    if (window.hwdWin) window.hwdWin.close();
 1617:     var xpos = (screen.width-400)/2;
 1618:     xpos = (xpos < 0) ? '0' : xpos;
 1619:     var ypos = (screen.height-330)/2-30;
 1620:     ypos = (ypos < 0) ? '0' : ypos;
 1621: 
 1622:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1623:     hwdWin.focus();
 1624:     var hDoc = hwdWin.document;
 1625:     hDoc.$docopen;
 1626:     hDoc.write('$start_page_highlight_central');
 1627:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1628:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;$lt{'kehi'}<\\/span><\\/h3><br /><br />");
 1629: 
 1630:     hDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
 1631:     hDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
 1632:     hDoc.write("<td><b>$lt{'txtc'}<\\/b><\\/td><td><b>$lt{'font'}<\\/b><\\/td><td><b>$lt{'fnst'}<\\/td><\\/tr>");
 1633:   }
 1634: 
 1635:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1636:     var hDoc = hwdWin.document;
 1637:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1638:     hDoc.write("<td align=\\"left\\">");
 1639:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
 1640:     hDoc.write("<td align=\\"left\\">");
 1641:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
 1642:     hDoc.write("<td align=\\"left\\">");
 1643:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
 1644:     hDoc.write("<\\/tr>");
 1645:   }
 1646: 
 1647:   function highlightend() { 
 1648:     var hDoc = hwdWin.document;
 1649:     hDoc.write("<\\/table>");
 1650:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1651:     hDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
 1652:     hDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
 1653:     hDoc.write("<\\/form>");
 1654:     hDoc.write('$end_page_highlight_central');
 1655:     hDoc.close();
 1656:   }
 1657: 
 1658: SUBJAVASCRIPT
 1659: }
 1660: 
 1661: sub get_increment {
 1662:     my $increment = $env{'form.increment'};
 1663:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1664:         $increment != .1) {
 1665:         $increment = 1;
 1666:     }
 1667:     return $increment;
 1668: }
 1669: 
 1670: sub gradeBox_start {
 1671:     return (
 1672:         &Apache::loncommon::start_data_table()
 1673:        .&Apache::loncommon::start_data_table_header_row()
 1674:        .'<th>'.&mt('Part').'</th>'
 1675:        .'<th>'.&mt('Points').'</th>'
 1676:        .'<th>&nbsp;</th>'
 1677:        .'<th>'.&mt('Assign Grade').'</th>'
 1678:        .'<th>'.&mt('Weight').'</th>'
 1679:        .'<th>'.&mt('Grade Status').'</th>'
 1680:        .&Apache::loncommon::end_data_table_header_row()
 1681:     );
 1682: }
 1683: 
 1684: sub gradeBox_end {
 1685:     return (
 1686:         &Apache::loncommon::end_data_table()
 1687:     );
 1688: }
 1689: #--- displays the grading box, used in essay type problem and grading by page/sequence
 1690: sub gradeBox {
 1691:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 1692:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1693: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 1694:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 1695:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
 1696:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
 1697:     $wgt       = ($wgt > 0 ? $wgt : '1');
 1698:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 1699: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 1700:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 1701:     my $display_part= &get_display_part($partid,$symb);
 1702:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 1703: 				       [$partid]);
 1704:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 1705:     if ($last_resets{$partid}) {
 1706:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 1707:     }
 1708:     $result.=&Apache::loncommon::start_data_table_row();
 1709:     my $ctr = 0;
 1710:     my $thisweight = 0;
 1711:     my $increment = &get_increment();
 1712: 
 1713:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 1714:     while ($thisweight<=$wgt) {
 1715: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 1716:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 1717: 	    $thisweight.')" value="'.$thisweight.'" '.
 1718: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 1719: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 1720:         $thisweight += $increment;
 1721: 	$ctr++;
 1722:     }
 1723:     $radio.='</tr></table>';
 1724: 
 1725:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 1726: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 1727: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 1728: 	$wgt.')" /></td>'."\n";
 1729:     $line.='<td>/'.$wgt.' '.$wgtmsg.
 1730: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 1731: 	' </td>'."\n";
 1732:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
 1733: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 1734:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 1735: 	$line.='<option></option>'.
 1736: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
 1737:     } else {
 1738: 	$line.='<option selected="selected"></option>'.
 1739: 	    '<option value="excused" >'.&mt('excused').'</option>';
 1740:     }
 1741:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
 1742: 
 1743: 
 1744:     $result .= 
 1745: 	    '<td>'.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
 1746:     $result.=&Apache::loncommon::end_data_table_row();
 1747:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 1748: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 1749: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 1750: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 1751:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 1752:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 1753:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 1754:         $aggtries.'" />'."\n";
 1755:     my $res_error;
 1756:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
 1757:     if ($res_error) {
 1758:         return &navmap_errormsg();
 1759:     }
 1760:     return $result;
 1761: }
 1762: 
 1763: sub handback_box {
 1764:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
 1765:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error_pointer);
 1766:     my (@respids);
 1767:     my @part_response_id = &flatten_responseType($responseType);
 1768:     foreach my $part_response_id (@part_response_id) {
 1769:     	my ($part,$resp) = @{ $part_response_id };
 1770:         if ($part eq $partid) {
 1771:             push(@respids,$resp);
 1772:         }
 1773:     }
 1774:     my $result;
 1775:     foreach my $respid (@respids) {
 1776: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 1777: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 1778: 	next if (!@$files);
 1779: 	my $file_counter = 0;
 1780: 	foreach my $file (@$files) {
 1781: 	    if ($file =~ /\/portfolio\//) {
 1782:                 $file_counter++;
 1783:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 1784:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
 1785:     	        $file_disp = "$name.$ext";
 1786:     	        $file = $file_path.$file_disp;
 1787:     	        $result.=&mt('Return commented version of [_1] to student.',
 1788:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 1789:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 1790:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
 1791: 	    }
 1792: 	}
 1793:         if ($file_counter) {
 1794:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
 1795:                        '<span class="LC_info">'.
 1796:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
 1797:         }
 1798:     }
 1799:     return $result;    
 1800: }
 1801: 
 1802: sub show_problem {
 1803:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 1804:     my $rendered;
 1805:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 1806:     &Apache::lonxml::remember_problem_counter();
 1807:     if ($mode eq 'both' or $mode eq 'text') {
 1808: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 1809: 						       $env{'request.course.id'},
 1810: 						       undef,\%form);
 1811:     }
 1812:     if ($removeform) {
 1813: 	$rendered=~s|<form(.*?)>||g;
 1814: 	$rendered=~s|</form>||g;
 1815: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 1816:     }
 1817:     my $companswer;
 1818:     if ($mode eq 'both' or $mode eq 'answer') {
 1819: 	&Apache::lonxml::restore_problem_counter();
 1820: 	$companswer=
 1821: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 1822: 						    $env{'request.course.id'},
 1823: 						    %form);
 1824:     }
 1825:     if ($removeform) {
 1826: 	$companswer=~s|<form(.*?)>||g;
 1827: 	$companswer=~s|</form>||g;
 1828: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 1829:     }
 1830:     $rendered=
 1831:         '<div class="LC_Box">'
 1832:        .'<h3 class="LC_hcell">'.&mt('View of the problem').'</h3>'
 1833:        .$rendered
 1834:        .'</div>';
 1835:     $companswer=
 1836:         '<div class="LC_Box">'
 1837:        .'<h3 class="LC_hcell">'.&mt('Correct answer').'</h3>'
 1838:        .$companswer
 1839:        .'</div>';
 1840:     my $result;
 1841:     if ($mode eq 'both') {
 1842:         $result=$rendered.$companswer;
 1843:     } elsif ($mode eq 'text') {
 1844:         $result=$rendered;
 1845:     } elsif ($mode eq 'answer') {
 1846:         $result=$companswer;
 1847:     }
 1848:     return $result;
 1849: }
 1850: 
 1851: sub files_exist {
 1852:     my ($r, $symb) = @_;
 1853:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1854: 
 1855:     foreach my $student (@students) {
 1856:         my ($uname,$udom,$fullname) = split(/:/,$student);
 1857:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 1858: 					      $udom,$uname);
 1859:         my ($string,$timestamp)= &get_last_submission(\%record);
 1860:         foreach my $submission (@$string) {
 1861:             my ($partid,$respid) =
 1862: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 1863:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 1864: 					   \%record);
 1865:             return 1 if (@$files);
 1866:         }
 1867:     }
 1868:     return 0;
 1869: }
 1870: 
 1871: sub download_all_link {
 1872:     my ($r,$symb) = @_;
 1873:     unless (&files_exist($r, $symb)) {
 1874:        $r->print(&mt('There are currently no submitted documents.'));
 1875:        return;
 1876:     }
 1877: 
 1878:     my $all_students = 
 1879: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 1880: 
 1881:     my $parts =
 1882: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 1883: 
 1884:     my $identifier = &Apache::loncommon::get_cgi_id();
 1885:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 1886:                              'cgi.'.$identifier.'.symb' => $symb,
 1887:                              'cgi.'.$identifier.'.parts' => $parts,});
 1888:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 1889: 	      &mt('Download All Submitted Documents').'</a>');
 1890:     return;
 1891: }
 1892: 
 1893: sub submit_download_link {
 1894:     my ($request,$symb) = @_;
 1895:     if (!$symb) { return ''; }
 1896: #FIXME: Figure out which type of problem this is and provide appropriate download
 1897:     &download_all_link($request,$symb);
 1898: }
 1899: 
 1900: sub build_section_inputs {
 1901:     my $section_inputs;
 1902:     if ($env{'form.section'} eq '') {
 1903:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 1904:     } else {
 1905:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 1906:         foreach my $section (@sections) {
 1907:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 1908:         }
 1909:     }
 1910:     return $section_inputs;
 1911: }
 1912: 
 1913: # --------------------------- show submissions of a student, option to grade 
 1914: sub submission {
 1915:     my ($request,$counter,$total,$symb) = @_;
 1916:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 1917:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 1918:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 1919:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 1920: 
 1921:     my $probtitle=&Apache::lonnet::gettitle($symb); 
 1922:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 1923: 
 1924:     if (!&canview($usec)) {
 1925: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
 1926: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
 1927: 			$env{'request.course.id'}.')</span>');
 1928: 	return;
 1929:     }
 1930: 
 1931:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 1932:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 1933:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 1934:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 1935:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1936: 	'" src="'.$request->dir_config('lonIconsURL').
 1937: 	'/check.gif" height="16" border="0" />';
 1938: 
 1939:     my %old_essays;
 1940:     # header info
 1941:     if ($counter == 0) {
 1942: 	&sub_page_js($request);
 1943: 	&sub_page_kw_js($request);
 1944: 
 1945: 	# option to display problem, only once else it cause problems 
 1946:         # with the form later since the problem has a form.
 1947: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 1948: 	    my $mode;
 1949: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 1950: 		$mode='both';
 1951: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 1952: 		$mode='text';
 1953: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 1954: 		$mode='answer';
 1955: 	    }
 1956: 	    &Apache::lonxml::clear_problem_counter();
 1957: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 1958: 	}
 1959: 
 1960: 	# kwclr is the only variable that is guaranteed to be non blank 
 1961:         # if this subroutine has been called once.
 1962: 	my %keyhash = ();
 1963: #	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
 1964:         if (1) {
 1965: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 1966: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 1967: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 1968: 
 1969: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 1970: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 1971: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 1972: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 1973: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 1974: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
 1975: 		$keyhash{$symb.'_subject'} : $probtitle;
 1976: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 1977: 	}
 1978: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 1979: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 1980: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 1981: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 1982: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 1983: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 1984: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 1985: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 1986: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 1987: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 1988: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 1989: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 1990: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 1991: 			&build_section_inputs().
 1992: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 1993: 			'<input type="hidden" name="NCT"'.
 1994: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 1995: #	if ($env{'form.handgrade'} eq 'yes') {
 1996:         if (1) {
 1997: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 1998: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 1999: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 2000: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
 2001: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 2002: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 2003: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 2004: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
 2005: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
 2006: 	    }
 2007: 	}
 2008: 	
 2009: 	my ($cts,$prnmsg) = (1,'');
 2010: 	while ($cts <= $env{'form.savemsgN'}) {
 2011: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 2012: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 2013: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 2014: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 2015: 		'" />'."\n".
 2016: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 2017: 	    $cts++;
 2018: 	}
 2019: 	$request->print($prnmsg);
 2020: 
 2021: #	if ($env{'form.handgrade'} eq 'yes') {
 2022:         if (1) {
 2023: 
 2024:             my %lt = &Apache::lonlocal::texthash(
 2025:                           keyw => 'Keyword Options',
 2026:                           list => 'List',
 2027:                           past => 'Paste Selection to List',
 2028:                           high => 'Highlight Attribute',
 2029:                      );    
 2030: #
 2031: # Print out the keyword options line
 2032: #
 2033: 	    $request->print(<<KEYWORDS);
 2034: <br /><b>$lt{'keyw'}:</b>&nbsp;
 2035: <a href="javascript:keywords(document.SCORE);" target="_self">$lt{'list'}</a>&nbsp; &nbsp;
 2036: <a href="#" onmousedown="javascript:getSel(); return false"
 2037:  CLASS="page">$lt{'past'}</a>&nbsp; &nbsp;
 2038: <a href="javascript:kwhighlight();" target="_self">$lt{'high'}</a><br /><br />
 2039: KEYWORDS
 2040: #
 2041: # Load the other essays for similarity check
 2042: #
 2043:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 2044: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 2045: 	    $apath=&escape($apath);
 2046: 	    $apath=~s/\W/\_/gs;
 2047: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
 2048:         }
 2049:     }
 2050: 
 2051: # This is where output for one specific student would start
 2052:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
 2053:     $request->print(
 2054:         "\n\n"
 2055:        .'<div class="LC_grade_show_user'.$add_class.'">'
 2056:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
 2057:        ."\n"
 2058:     );
 2059: 
 2060:     # Show additional functions if allowed
 2061:     if ($perm{'vgr'}) {
 2062:         $request->print(
 2063:             &Apache::loncommon::track_student_link(
 2064:                 &mt('View recent activity'),
 2065:                 $uname,$udom,'check')
 2066:            .' '
 2067:         );
 2068:     }
 2069:     if ($perm{'opa'}) {
 2070:         $request->print(
 2071:             &Apache::loncommon::pprmlink(
 2072:                 &mt('Set/Change parameters'),
 2073:                 $uname,$udom,$symb,'check'));
 2074:     }
 2075: 
 2076:     # Show Problem
 2077:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2078: 	my $mode;
 2079: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2080: 	    $mode='both';
 2081: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2082: 	    $mode='text';
 2083: 	} elsif ($env{'form.vAns'} eq 'all') {
 2084: 	    $mode='answer';
 2085: 	}
 2086: 	&Apache::lonxml::clear_problem_counter();
 2087: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2088:     }
 2089: 
 2090:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2091:     my $res_error;
 2092:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2093:     if ($res_error) {
 2094:         $request->print(&navmap_errormsg());
 2095:         return;
 2096:     }
 2097: 
 2098:     # Display student info
 2099:     $request->print(($counter == 0 ? '' : '<br />'));
 2100: 
 2101:     my $result='<div class="LC_Box">'
 2102:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
 2103:     $result.='<input type="hidden" name="name'.$counter.
 2104:              '" value="'.$env{'form.fullname'}.'" />'."\n";
 2105: #    if ($env{'form.handgrade'} eq 'no') {
 2106:     if (1) {
 2107:         $result.='<p class="LC_info">'
 2108:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
 2109:                 ."</p>\n";
 2110:     }
 2111: 
 2112:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
 2113:     my $fullname;
 2114:     my $col_fullnames = [];
 2115: #    if ($env{'form.handgrade'} eq 'yes') {
 2116:     if (1) {
 2117: 	(my $sub_result,$fullname,$col_fullnames)=
 2118: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2119: 				 $counter);
 2120: 	$result.=$sub_result;
 2121:     }
 2122:     $request->print($result."\n");
 2123: 
 2124:     # print student answer/submission
 2125:     # Options are (1) Handgraded submission only
 2126:     #             (2) Last submission, includes submission that is not handgraded 
 2127:     #                  (for multi-response type part)
 2128:     #             (3) Last submission plus the parts info
 2129:     #             (4) The whole record for this student
 2130:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
 2131: 	my ($string,$timestamp)= &get_last_submission(\%record);
 2132: 	
 2133: 	my $lastsubonly;
 2134: 
 2135:         if ($$timestamp eq '') {
 2136:             $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
 2137:         } else {
 2138:             $lastsubonly =
 2139:                 '<div class="LC_grade_submissions_body">'
 2140:                .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
 2141: 
 2142: 	    my %seenparts;
 2143: 	    my @part_response_id = &flatten_responseType($responseType);
 2144: 	    foreach my $part (@part_response_id) {
 2145: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
 2146: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
 2147: 
 2148: 		my ($partid,$respid) = @{ $part };
 2149: 		my $display_part=&get_display_part($partid,$symb);
 2150: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2151: 		    if (exists($seenparts{$partid})) { next; }
 2152: 		    $seenparts{$partid}=1;
 2153: 		    my $submitby='<b>Part:</b> '.$display_part.
 2154: 			' <b>Collaborative submission by:</b> '.
 2155: 			'<a href="javascript:viewSubmitter(\''.
 2156: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
 2157: 			'\');" target="_self">'.
 2158: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
 2159: 		    $request->print($submitby);
 2160: 		    next;
 2161: 		}
 2162: 		my $responsetype = $responseType->{$partid}->{$respid};
 2163: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
 2164:                     $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
 2165:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2166:                         ' <span class="LC_internal_info">'.
 2167:                         '('.&mt('Response ID: [_1]',$respid).')'.
 2168:                         '</span>&nbsp; &nbsp;'.
 2169: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
 2170: 		    next;
 2171: 		}
 2172: 		foreach my $submission (@$string) {
 2173: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2174: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2175: 		    my ($ressub,$hide,$subval) = split(/:/,$submission,3);
 2176: 		    # Similarity check
 2177: 		    my $similar='';
 2178:                     my ($type,$trial,$rndseed);
 2179:                     if ($hide eq 'rand') {
 2180:                         $type = 'randomizetry';
 2181:                         $trial = $record{"resource.$partid.tries"};
 2182:                         $rndseed = $record{"resource.$partid.rndseed"};
 2183:                     }
 2184: 		    if($env{'form.checkPlag'}){
 2185: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2186: 			    &most_similar($uname,$udom,$subval,\%old_essays);
 2187: 			if ($osim) {
 2188: 			    $osim=int($osim*100.0);
 2189: 			    my %old_course_desc = 
 2190: 				&Apache::lonnet::coursedescription($ocrsid,
 2191: 								   {'one_time' => 1});
 2192: 
 2193:                             if ($hide eq 'anon') {
 2194:                                 $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
 2195:                                          &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
 2196:                             } else {
 2197: 			        $similar="<hr /><h3><span class=\"LC_warning\">".
 2198: 				    &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
 2199: 				        $osim,
 2200: 				        &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
 2201: 				        $old_course_desc{'description'},
 2202: 				        $old_course_desc{'num'},
 2203: 				        $old_course_desc{'domain'}).
 2204: 				    '</span></h3><blockquote><i>'.
 2205: 				    &keywords_highlight($oessay).
 2206: 				    '</i></blockquote><hr />';
 2207:                             }
 2208: 			}
 2209: 		    }
 2210: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom,
 2211:                                          undef,$type,$trial,$rndseed);
 2212: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
 2213: 			($env{'form.lastSub'} eq 'hdgrade' && 
 2214: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
 2215: 			my $display_part=&get_display_part($partid,$symb);
 2216:                         $lastsubonly.='<div class="LC_grade_submission_part">'.
 2217:                             '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2218:                             ' <span class="LC_internal_info">'.
 2219:                             '('.&mt('Response ID: [_1]',$respid).')'.
 2220:                             '</span>&nbsp; &nbsp;';
 2221: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2222: 			if (@$files) {
 2223:                             if ($hide eq 'anon') {
 2224:                                 $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
 2225:                             } else {
 2226:                                 $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
 2227:                                 foreach my $file (@$files) {
 2228:                                     &Apache::lonnet::allowuploaded('/adm/grades',$file);
 2229:                                     $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" /> '.$file.'</a>';
 2230:                                 }
 2231:                             }
 2232: 			    $lastsubonly.='<br />';
 2233: 			}
 2234:                         if ($hide eq 'anon') {
 2235:                             $lastsubonly.='<b>'.&mt('Anonymous Survey').'</b>'; 
 2236:                         } else {
 2237: 			    $lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
 2238: 			        &cleanRecord($subval,$responsetype,$symb,$partid,
 2239: 					     $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
 2240:                         }
 2241: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2242: 			$lastsubonly.='</div>';
 2243: 		    }
 2244: 		}
 2245: 	    }
 2246: 	    $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
 2247: 	}
 2248: 	$request->print($lastsubonly);
 2249:    } elsif ($env{'form.lastSub'} eq 'datesub') {
 2250:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2251: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2252:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2253: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2254: 								 $env{'request.course.id'},
 2255: 								 $last,'.submission',
 2256: 								 'Apache::grades::keywords_highlight'));
 2257:     }
 2258:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2259: 	.$udom.'" />'."\n");
 2260:     # return if view submission with no grading option
 2261:     if (!&canmodify($usec)) {
 2262: 	$request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
 2263: 	return;
 2264:     } else {
 2265: 	$request->print('</div>'."\n");
 2266:     }
 2267: 
 2268:     # essay grading message center
 2269: #    if ($env{'form.handgrade'} eq 'yes') {
 2270:     if (1) {
 2271: 	my $result='<div class="LC_grade_message_center">';
 2272:     
 2273: 	$result.='<div class="LC_grade_message_center_header">'.
 2274: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
 2275: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2276: 	my $msgfor = $givenn.' '.$lastname;
 2277: 	if (scalar(@$col_fullnames) > 0) {
 2278: 	    my $lastone = pop(@$col_fullnames);
 2279: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2280: 	}
 2281: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2282: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2283: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
 2284: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2285: 	    ',\''.$msgfor.'\');" target="_self">'.
 2286: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
 2287: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2288: 	    '<img src="'.$request->dir_config('lonIconsURL').
 2289: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
 2290: 	    '<br />&nbsp;('.
 2291: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
 2292: 	$result.='</div></div>';
 2293: 	$request->print($result);
 2294:     }
 2295: 
 2296:     my %seen = ();
 2297:     my @partlist;
 2298:     my @gradePartRespid;
 2299:     my @part_response_id = &flatten_responseType($responseType);
 2300:     $request->print(
 2301:         '<div class="LC_Box">'
 2302:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
 2303:     );
 2304:     $request->print(&gradeBox_start());
 2305:     foreach my $part_response_id (@part_response_id) {
 2306:     	my ($partid,$respid) = @{ $part_response_id };
 2307: 	my $part_resp = join('_',@{ $part_response_id });
 2308: 	next if ($seen{$partid} > 0);
 2309: 	$seen{$partid}++;
 2310: 	next if ($$handgrade{$part_resp} ne 'yes' 
 2311: 		 && $env{'form.lastSub'} eq 'hdgrade');
 2312: 	push(@partlist,$partid);
 2313: 	push(@gradePartRespid,$partid.'.'.$respid);
 2314: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2315:     }
 2316:     $request->print(&gradeBox_end()); # </div>
 2317:     $request->print('</div>');
 2318: 
 2319:     $request->print('<div class="LC_grade_info_links">');
 2320:     $request->print('</div>');
 2321: 
 2322:     $result='<input type="hidden" name="partlist'.$counter.
 2323: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2324:     $result.='<input type="hidden" name="gradePartRespid'.
 2325: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2326:     my $ctr = 0;
 2327:     while ($ctr < scalar(@partlist)) {
 2328: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2329: 	    $partlist[$ctr].'" />'."\n";
 2330: 	$ctr++;
 2331:     }
 2332:     $request->print($result.''."\n");
 2333: 
 2334: # Done with printing info for one student
 2335: 
 2336:     $request->print('</div>');#LC_grade_show_user
 2337: 
 2338: 
 2339:     # print end of form
 2340:     if ($counter == $total) {
 2341:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
 2342: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2343: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
 2344: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2345: 	my $ntstu ='<select name="NTSTU">'.
 2346: 	    '<option>1</option><option>2</option>'.
 2347: 	    '<option>3</option><option>5</option>'.
 2348: 	    '<option>7</option><option>10</option></select>'."\n";
 2349: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2350: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2351:         $endform.=&mt('[_1]student(s)',$ntstu);
 2352: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2353: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2354: 	    '<input type="button" value="'.&mt('Next').'" '.
 2355: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2356:         $endform.='<span class="LC_warning">'.
 2357:                   &mt('(Next and Previous (student) do not save the scores.)').
 2358:                   '</span>'."\n" ;
 2359:         $endform.="<input type='hidden' value='".&get_increment().
 2360:             "' name='increment' />";
 2361: 	$endform.='</td></tr></table></form>';
 2362: 	$request->print($endform);
 2363:     }
 2364:     return '';
 2365: }
 2366: 
 2367: sub check_collaborators {
 2368:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2369:     my ($result,@col_fullnames);
 2370:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2371:     foreach my $part (keys(%$handgrade)) {
 2372: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2373: 					'.maxcollaborators',
 2374: 					$symb,$udom,$uname);
 2375: 	next if ($ncol <= 0);
 2376: 	$part =~ s/\_/\./g;
 2377: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2378: 	my (@good_collaborators, @bad_collaborators);
 2379: 	foreach my $possible_collaborator
 2380: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2381: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2382: 	    next if ($possible_collaborator eq '');
 2383: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
 2384: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2385: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2386: 	    # Doing this grep allows 'fuzzy' specification
 2387: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2388: 			       keys(%$classlist));
 2389: 	    if (! scalar(@matches)) {
 2390: 		push(@bad_collaborators, $possible_collaborator);
 2391: 	    } else {
 2392: 		push(@good_collaborators, @matches);
 2393: 	    }
 2394: 	}
 2395: 	if (scalar(@good_collaborators) != 0) {
 2396: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
 2397: 	    foreach my $name (@good_collaborators) {
 2398: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2399: 		push(@col_fullnames, $givenn.' '.$lastname);
 2400: 		$result.='<li>'.$fullname->{$name}.'</li>';
 2401: 	    }
 2402: 	    $result.='</ol><br />'."\n";
 2403: 	    my ($part)=split(/\./,$part);
 2404: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2405: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2406: 		"\n";
 2407: 	}
 2408: 	if (scalar(@bad_collaborators) > 0) {
 2409: 	    $result.='<div class="LC_warning">';
 2410: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2411: 	    $result .= '</div>';
 2412: 	}         
 2413: 	if (scalar(@bad_collaborators > $ncol)) {
 2414: 	    $result .= '<div class="LC_warning">';
 2415: 	    $result .= &mt('This student has submitted too many '.
 2416: 		'collaborators.  Maximum is [_1].',$ncol);
 2417: 	    $result .= '</div>';
 2418: 	}
 2419:     }
 2420:     return ($result,$fullname,\@col_fullnames);
 2421: }
 2422: 
 2423: #--- Retrieve the last submission for all the parts
 2424: sub get_last_submission {
 2425:     my ($returnhash)=@_;
 2426:     my (@string,$timestamp,%lasthidden);
 2427:     if ($$returnhash{'version'}) {
 2428: 	my %lasthash=();
 2429: 	my ($version);
 2430: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2431: 	    foreach my $key (sort(split(/\:/,
 2432: 					$$returnhash{$version.':keys'}))) {
 2433: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2434: 		$timestamp = 
 2435: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2436: 	    }
 2437: 	}
 2438:         my (%typeparts,%randombytry);
 2439:         my $showsurv = 
 2440:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
 2441:         foreach my $key (sort(keys(%lasthash))) {
 2442:             if ($key =~ /\.type$/) {
 2443:                 if (($lasthash{$key} eq 'anonsurvey') || 
 2444:                     ($lasthash{$key} eq 'anonsurveycred') ||
 2445:                     ($lasthash{$key} eq 'randomizetry')) {
 2446:                     my ($ign,@parts) = split(/\./,$key);
 2447:                     pop(@parts);
 2448:                     my $id = join('.',@parts);
 2449:                     if ($lasthash{$key} eq 'randomizetry') {
 2450:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
 2451:                     } else {
 2452:                         unless ($showsurv) {
 2453:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
 2454:                         }
 2455:                     }
 2456:                     delete($lasthash{$key});
 2457:                 }
 2458:             }
 2459:         }
 2460:         my @hidden = keys(%typeparts);
 2461:         my @randomize = keys(%randombytry);
 2462: 	foreach my $key (keys(%lasthash)) {
 2463: 	    next if ($key !~ /\.submission$/);
 2464:             my $hide;
 2465:             if (@hidden) {
 2466:                 foreach my $id (@hidden) {
 2467:                     if ($key =~ /^\Q$id\E/) {
 2468:                         $hide = 'anon';
 2469:                         last;
 2470:                     }
 2471:                 }
 2472:             }
 2473:             unless ($hide) {
 2474:                 if (@randomize) {
 2475:                     foreach my $id (@hidden) {
 2476:                         if ($key =~ /^\Q$id\E/) {
 2477:                             $hide = 'rand';
 2478:                             last;
 2479:                         }
 2480:                     }
 2481:                 }
 2482:             }
 2483: 	    my ($partid,$foo) = split(/submission$/,$key);
 2484: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
 2485: 		'<span class="LC_warning">Draft Copy</span> ' : '';
 2486: 	    push(@string, join(':', $key, $hide, $draft.$lasthash{$key}));
 2487: 	}
 2488:     }
 2489:     if (!@string) {
 2490: 	$string[0] =
 2491: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
 2492:     }
 2493:     return (\@string,\$timestamp);
 2494: }
 2495: 
 2496: #--- High light keywords, with style choosen by user.
 2497: sub keywords_highlight {
 2498:     my $string    = shift;
 2499:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2500:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2501:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2502:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2503:     foreach my $keyword (@keylist) {
 2504: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2505:     }
 2506:     return $string;
 2507: }
 2508: 
 2509: #--- Called from submission routine
 2510: sub processHandGrade {
 2511:     my ($request,$symb) = @_;
 2512:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2513:     my $button = $env{'form.gradeOpt'};
 2514:     my $ngrade = $env{'form.NCT'};
 2515:     my $ntstu  = $env{'form.NTSTU'};
 2516:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2517:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 2518: 
 2519:     if ($button eq 'Save & Next') {
 2520: 	my $ctr = 0;
 2521: 	while ($ctr < $ngrade) {
 2522: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 2523: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 2524: 	    if ($errorflag eq 'no_score') {
 2525: 		$ctr++;
 2526: 		next;
 2527: 	    }
 2528: 	    if ($errorflag eq 'not_allowed') {
 2529: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
 2530: 		$ctr++;
 2531: 		next;
 2532: 	    }
 2533: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 2534: 	    my ($subject,$message,$msgstatus) = ('','','');
 2535: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 2536:             my ($feedurl,$showsymb) =
 2537: 		&get_feedurl_and_symb($symb,$uname,$udom);
 2538: 	    my $messagetail;
 2539: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 2540: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 2541: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 2542: 		$subject.=' ['.$restitle.']';
 2543: 		my (@msgnum) = split(/,/,$includemsg);
 2544: 		foreach (@msgnum) {
 2545: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 2546: 		}
 2547: 		$message =&Apache::lonfeedback::clear_out_html($message);
 2548: 		if ($env{'form.withgrades'.$ctr}) {
 2549: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 2550: 		    $messagetail = " for <a href=\"".
 2551: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
 2552: 		}
 2553: 		$msgstatus = 
 2554:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 2555: 						     $message.$messagetail,
 2556:                                                      undef,$feedurl,undef,
 2557:                                                      undef,undef,$showsymb,
 2558:                                                      $restitle);
 2559: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
 2560: 				$msgstatus.'<br />');
 2561: 	    }
 2562: 	    if ($env{'form.collaborator'.$ctr}) {
 2563: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 2564: 		foreach my $collabstr (@collabstrs) {
 2565: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 2566: 		    foreach my $collaborator (@collaborators) {
 2567: 			my ($errorflag,$pts,$wgt) = 
 2568: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 2569: 					   $env{'form.unamedom'.$ctr},$part);
 2570: 			if ($errorflag eq 'not_allowed') {
 2571: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 2572: 			    next;
 2573: 			} elsif ($message ne '') {
 2574: 			    my ($baseurl,$showsymb) = 
 2575: 				&get_feedurl_and_symb($symb,$collaborator,
 2576: 						      $udom);
 2577: 			    if ($env{'form.withgrades'.$ctr}) {
 2578: 				$messagetail = " for <a href=\"".
 2579:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
 2580: 			    }
 2581: 			    $msgstatus = 
 2582: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 2583: 			}
 2584: 		    }
 2585: 		}
 2586: 	    }
 2587: 	    $ctr++;
 2588: 	}
 2589:     }
 2590: 
 2591: #    if ($env{'form.handgrade'} eq 'yes') {
 2592:     if (1) {
 2593: 	# Keywords sorted in alphabatical order
 2594: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2595: 	my %keyhash = ();
 2596: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 2597: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 2598: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 2599: 	$env{'form.keywords'} = join(' ',@keywords);
 2600: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 2601: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 2602: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 2603: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 2604: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 2605: 
 2606: 	# message center - Order of message gets changed. Blank line is eliminated.
 2607: 	# New messages are saved in env for the next student.
 2608: 	# All messages are saved in nohist_handgrade.db
 2609: 	my ($ctr,$idx) = (1,1);
 2610: 	while ($ctr <= $env{'form.savemsgN'}) {
 2611: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 2612: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 2613: 		$idx++;
 2614: 	    }
 2615: 	    $ctr++;
 2616: 	}
 2617: 	$ctr = 0;
 2618: 	while ($ctr < $ngrade) {
 2619: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 2620: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2621: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2622: 		$idx++;
 2623: 	    }
 2624: 	    $ctr++;
 2625: 	}
 2626: 	$env{'form.savemsgN'} = --$idx;
 2627: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 2628: 	my $putresult = &Apache::lonnet::put
 2629: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 2630:     }
 2631:     # Called by Save & Refresh from Highlight Attribute Window
 2632:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 2633:     if ($env{'form.refresh'} eq 'on') {
 2634: 	my ($ctr,$total) = (0,0);
 2635: 	while ($ctr < $ngrade) {
 2636: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 2637: 	    $ctr++;
 2638: 	}
 2639: 	$env{'form.NTSTU'}=$ngrade;
 2640: 	$ctr = 0;
 2641: 	while ($ctr < $total) {
 2642: 	    my $processUser = $env{'form.unamedom'.$ctr};
 2643: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2644: 	    $env{'form.fullname'} = $$fullname{$processUser};
 2645: 	    &submission($request,$ctr,$total-1,$symb);
 2646: 	    $ctr++;
 2647: 	}
 2648: 	return '';
 2649:     }
 2650: 
 2651:     # Get the next/previous one or group of students
 2652:     my $firststu = $env{'form.unamedom0'};
 2653:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 2654:     my $ctr = 2;
 2655:     while ($laststu eq '') {
 2656: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 2657: 	$ctr++;
 2658: 	$laststu = $firststu if ($ctr > $ngrade);
 2659:     }
 2660: 
 2661:     my (@parsedlist,@nextlist);
 2662:     my ($nextflg) = 0;
 2663:     foreach my $item (sort 
 2664: 	     {
 2665: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 2666: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 2667: 		 }
 2668: 		 return $a cmp $b;
 2669: 	     } (keys(%$fullname))) {
 2670: # FIXME: this is fishy, looks like the button label
 2671: 	if ($nextflg == 1 && $button =~ /Next$/) {
 2672: 	    push(@parsedlist,$item);
 2673: 	}
 2674: 	$nextflg = 1 if ($item eq $laststu);
 2675: 	if ($button eq 'Previous') {
 2676: 	    last if ($item eq $firststu);
 2677: 	    push(@parsedlist,$item);
 2678: 	}
 2679:     }
 2680:     $ctr = 0;
 2681: # FIXME: this is fishy, looks like the button label
 2682:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 2683:     my $res_error;
 2684:     my ($partlist) = &response_type($symb,\$res_error);
 2685:     if ($res_error) {
 2686:         $request->print(&navmap_errormsg());
 2687:         return;
 2688:     }
 2689:     foreach my $student (@parsedlist) {
 2690: 	my $submitonly=$env{'form.submitonly'};
 2691: 	my ($uname,$udom) = split(/:/,$student);
 2692: 	
 2693: 	if ($submitonly eq 'queued') {
 2694: 	    my %queue_status = 
 2695: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 2696: 							$udom,$uname);
 2697: 	    next if (!defined($queue_status{'gradingqueue'}));
 2698: 	}
 2699: 
 2700: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 2701: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2702: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 2703: 	    my $submitted = 0;
 2704: 	    my $ungraded = 0;
 2705: 	    my $incorrect = 0;
 2706: 	    foreach my $item (keys(%status)) {
 2707: 		$submitted = 1 if ($status{$item} ne 'nothing');
 2708: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 2709: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 2710: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 2711: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 2712: 		    $submitted = 0;
 2713: 		}
 2714: 	    }
 2715: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 2716: 				     $submitonly eq 'incorrect' ||
 2717: 				     $submitonly eq 'graded'));
 2718: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 2719: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 2720: 	}
 2721: 	push(@nextlist,$student) if ($ctr < $ntstu);
 2722: 	last if ($ctr == $ntstu);
 2723: 	$ctr++;
 2724:     }
 2725: 
 2726:     $ctr = 0;
 2727:     my $total = scalar(@nextlist)-1;
 2728: 
 2729:     foreach (sort(@nextlist)) {
 2730: 	my ($uname,$udom,$submitter) = split(/:/);
 2731: 	$env{'form.student'}  = $uname;
 2732: 	$env{'form.userdom'}  = $udom;
 2733: 	$env{'form.fullname'} = $$fullname{$_};
 2734: 	&submission($request,$ctr,$total,$symb);
 2735: 	$ctr++;
 2736:     }
 2737:     if ($total < 0) {
 2738: 	my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
 2739: 	$request->print($the_end);
 2740:     }
 2741:     return '';
 2742: }
 2743: 
 2744: #---- Save the score and award for each student, if changed
 2745: sub saveHandGrade {
 2746:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 2747:     my @version_parts;
 2748:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 2749: 					   $env{'request.course.id'});
 2750:     if (!&canmodify($usec)) { return('not_allowed'); }
 2751:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 2752:     my @parts_graded;
 2753:     my %newrecord  = ();
 2754:     my ($pts,$wgt) = ('','');
 2755:     my %aggregate = ();
 2756:     my $aggregateflag = 0;
 2757:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 2758:     foreach my $new_part (@parts) {
 2759: 	#collaborator ($submi may vary for different parts
 2760: 	if ($submitter && $new_part ne $part) { next; }
 2761: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 2762: 	if ($dropMenu eq 'excused') {
 2763: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 2764: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 2765: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 2766: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 2767: 		}
 2768: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 2769: 	    }
 2770: 	} elsif ($dropMenu eq 'reset status'
 2771: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 2772: 	    foreach my $key (keys(%record)) {
 2773: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 2774: 	    }
 2775: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2776: 		"$env{'user.name'}:$env{'user.domain'}";
 2777:             my $totaltries = $record{'resource.'.$part.'.tries'};
 2778: 
 2779:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 2780: 					       [$new_part]);
 2781:             my $aggtries =$totaltries;
 2782:             if ($last_resets{$new_part}) {
 2783:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 2784: 					   $new_part);
 2785:             }
 2786: 
 2787:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 2788:             if ($aggtries > 0) {
 2789:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 2790:                 $aggregateflag = 1;
 2791:             }
 2792: 	} elsif ($dropMenu eq '') {
 2793: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 2794: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 2795: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 2796: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 2797: 		next;
 2798: 	    }
 2799: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 2800: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 2801: 	    my $partial= $pts/$wgt;
 2802: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 2803: 		#do not update score for part if not changed.
 2804:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 2805: 		next;
 2806: 	    } else {
 2807: 	        push(@parts_graded,$new_part);
 2808: 	    }
 2809: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 2810: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 2811: 	    }
 2812: 	    my $reckey = 'resource.'.$new_part.'.solved';
 2813: 	    if ($partial == 0) {
 2814: 		if ($record{$reckey} ne 'incorrect_by_override') {
 2815: 		    $newrecord{$reckey} = 'incorrect_by_override';
 2816: 		}
 2817: 	    } else {
 2818: 		if ($record{$reckey} ne 'correct_by_override') {
 2819: 		    $newrecord{$reckey} = 'correct_by_override';
 2820: 		}
 2821: 	    }	    
 2822: 	    if ($submitter && 
 2823: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 2824: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 2825: 	    }
 2826: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2827: 		"$env{'user.name'}:$env{'user.domain'}";
 2828: 	}
 2829: 	# unless problem has been graded, set flag to version the submitted files
 2830: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 2831: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 2832: 	        $dropMenu eq 'reset status')
 2833: 	   {
 2834: 	    push(@version_parts,$new_part);
 2835: 	}
 2836:     }
 2837:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2838:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2839: 
 2840:     if (%newrecord) {
 2841:         if (@version_parts) {
 2842:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 2843:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 2844: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 2845: 	    foreach my $new_part (@version_parts) {
 2846: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 2847: 				$new_part,\%newrecord);
 2848: 	    }
 2849:         }
 2850: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 2851: 				$env{'request.course.id'},$domain,$stuname);
 2852: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 2853: 				     $cdom,$cnum,$domain,$stuname);
 2854:     }
 2855:     if ($aggregateflag) {
 2856:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 2857: 			      $cdom,$cnum);
 2858:     }
 2859:     return ('',$pts,$wgt);
 2860: }
 2861: 
 2862: sub check_and_remove_from_queue {
 2863:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 2864:     my @ungraded_parts;
 2865:     foreach my $part (@{$parts}) {
 2866: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 2867: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 2868: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 2869: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 2870: 		) {
 2871: 	    push(@ungraded_parts, $part);
 2872: 	}
 2873:     }
 2874:     if ( !@ungraded_parts ) {
 2875: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 2876: 					       $cnum,$domain,$stuname);
 2877:     }
 2878: }
 2879: 
 2880: sub handback_files {
 2881:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 2882:     my $portfolio_root = '/userfiles/portfolio';
 2883:     my $res_error;
 2884:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2885:     if ($res_error) {
 2886:         $request->print('<br />'.&navmap_errormsg().'<br />');
 2887:         return;
 2888:     }
 2889:     my @handedback;
 2890:     my $file_msg;
 2891:     my @part_response_id = &flatten_responseType($responseType);
 2892:     foreach my $part_response_id (@part_response_id) {
 2893:     	my ($part_id,$resp_id) = @{ $part_response_id };
 2894: 	my $part_resp = join('_',@{ $part_response_id });
 2895:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
 2896:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
 2897:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3' 
 2898:                 if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
 2899:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
 2900:                     my ($directory,$answer_file) = 
 2901:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
 2902:                     my ($answer_name,$answer_ver,$answer_ext) =
 2903: 		        &file_name_version_ext($answer_file);
 2904: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 2905:                     my $getpropath = 1;
 2906:                     my ($dir_list,$listerror) = 
 2907:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
 2908:                                                  $domain,$stuname,$getpropath);
 2909: 		    my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
 2910:                     # fix file name
 2911:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 2912:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 2913:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
 2914:             	                                $save_file_name);
 2915:                     if ($result !~ m|^/uploaded/|) {
 2916:                         $request->print('<br /><span class="LC_error">'.
 2917:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 2918:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
 2919:                                         '</span>');
 2920:                     } else {
 2921:                         # mark the file as read only
 2922:                         push(@handedback,$save_file_name);
 2923: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 2924: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 2925: 			}
 2926:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 2927: 			$file_msg.= '<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
 2928:                     }
 2929:                     $request->print('<br />'.&mt('[_1] will be the uploaded file name [_2]','<span class="LC_info">'.$fname.'</span>','<span class="LC_filename">'.$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter}.'</span>'));
 2930:                 }
 2931:             }
 2932:         }
 2933:     }
 2934:     if (@handedback > 0) {
 2935:         $request->print('<br />');
 2936:         my @what = ($symb,$env{'request.course.id'},'handback');
 2937:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
 2938:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});    
 2939:         my ($subject,$message);
 2940:         if (scalar(@handedback) == 1) {
 2941:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
 2942:             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
 2943:         } else {
 2944:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
 2945:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
 2946:         }
 2947:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
 2948:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
 2949:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
 2950:         my ($feedurl,$showsymb) =
 2951:             &get_feedurl_and_symb($symb,$domain,$stuname);
 2952:         my $restitle = &Apache::lonnet::gettitle($symb);
 2953:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
 2954:         my $msgstatus =
 2955:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
 2956:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
 2957:                  $restitle);
 2958:         if ($msgstatus) {
 2959:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
 2960:         }
 2961:     }
 2962:     return;
 2963: }
 2964: 
 2965: sub get_feedurl_and_symb {
 2966:     my ($symb,$uname,$udom) = @_;
 2967:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2968:     $url = &Apache::lonnet::clutter($url);
 2969:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 2970: 					$symb,$udom,$uname);
 2971:     if ($encrypturl =~ /^yes$/i) {
 2972: 	&Apache::lonenc::encrypted(\$url,1);
 2973: 	&Apache::lonenc::encrypted(\$symb,1);
 2974:     }
 2975:     return ($url,$symb);
 2976: }
 2977: 
 2978: sub get_submitted_files {
 2979:     my ($udom,$uname,$partid,$respid,$record) = @_;
 2980:     my @files;
 2981:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 2982:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 2983:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 2984:     	    push(@files,$file_url.$file);
 2985:         }
 2986:     }
 2987:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 2988:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 2989:     }
 2990:     return (\@files);
 2991: }
 2992: 
 2993: # ----------- Provides number of tries since last reset.
 2994: sub get_num_tries {
 2995:     my ($record,$last_reset,$part) = @_;
 2996:     my $timestamp = '';
 2997:     my $num_tries = 0;
 2998:     if ($$record{'version'}) {
 2999:         for (my $version=$$record{'version'};$version>=1;$version--) {
 3000:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 3001:                 $timestamp = $$record{$version.':timestamp'};
 3002:                 if ($timestamp > $last_reset) {
 3003:                     $num_tries ++;
 3004:                 } else {
 3005:                     last;
 3006:                 }
 3007:             }
 3008:         }
 3009:     }
 3010:     return $num_tries;
 3011: }
 3012: 
 3013: # ----------- Determine decrements required in aggregate totals 
 3014: sub decrement_aggs {
 3015:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 3016:     my %decrement = (
 3017:                         attempts => 0,
 3018:                         users => 0,
 3019:                         correct => 0
 3020:                     );
 3021:     $decrement{'attempts'} = $aggtries;
 3022:     if ($solvedstatus =~ /^correct/) {
 3023:         $decrement{'correct'} = 1;
 3024:     }
 3025:     if ($aggtries == $totaltries) {
 3026:         $decrement{'users'} = 1;
 3027:     }
 3028:     foreach my $type (keys(%decrement)) {
 3029:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 3030:     }
 3031:     return;
 3032: }
 3033: 
 3034: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 3035: sub get_last_resets {
 3036:     my ($symb,$courseid,$partids) =@_;
 3037:     my %last_resets;
 3038:     my $cdom = $env{'course.'.$courseid.'.domain'};
 3039:     my $cname = $env{'course.'.$courseid.'.num'};
 3040:     my @keys;
 3041:     foreach my $part (@{$partids}) {
 3042: 	push(@keys,"$symb\0$part\0resettime");
 3043:     }
 3044:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 3045: 				     $cdom,$cname);
 3046:     foreach my $part (@{$partids}) {
 3047: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 3048:     }
 3049:     return %last_resets;
 3050: }
 3051: 
 3052: # ----------- Handles creating versions for portfolio files as answers
 3053: sub version_portfiles {
 3054:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 3055:     my $version_parts = join('|',@$v_flag);
 3056:     my @returned_keys;
 3057:     my $parts = join('|', @$parts_graded);
 3058:     my $portfolio_root = '/userfiles/portfolio';
 3059:     foreach my $key (keys(%$record)) {
 3060:         my $new_portfiles;
 3061:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 3062:             my @versioned_portfiles;
 3063:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 3064:             foreach my $file (@portfiles) {
 3065:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 3066:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 3067: 		my ($answer_name,$answer_ver,$answer_ext) =
 3068: 		    &file_name_version_ext($answer_file);
 3069:                 my $getpropath = 1;    
 3070:                 my ($dir_list,$listerror) = 
 3071:                     &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,
 3072:                                              $stu_name,$getpropath);
 3073:                 my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
 3074:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
 3075:                 if ($new_answer ne 'problem getting file') {
 3076:                     push(@versioned_portfiles, $directory.$new_answer);
 3077:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
 3078:                         [$directory.$new_answer],
 3079:                         [$symb,$env{'request.course.id'},'graded']);
 3080:                 }
 3081:             }
 3082:             $$record{$key} = join(',',@versioned_portfiles);
 3083:             push(@returned_keys,$key);
 3084:         }
 3085:     } 
 3086:     return (@returned_keys);   
 3087: }
 3088: 
 3089: sub get_next_version {
 3090:     my ($answer_name, $answer_ext, $dir_list) = @_;
 3091:     my $version;
 3092:     if (ref($dir_list) eq 'ARRAY') {
 3093:         foreach my $row (@{$dir_list}) {
 3094:             my ($file) = split(/\&/,$row,2);
 3095:             my ($file_name,$file_version,$file_ext) =
 3096: 	        &file_name_version_ext($file);
 3097:             if (($file_name eq $answer_name) && 
 3098: 	        ($file_ext eq $answer_ext)) {
 3099:                      # gets here if filename and extension match, 
 3100:                      # regardless of version
 3101:                 if ($file_version ne '') {
 3102:                     # a versioned file is found  so save it for later
 3103:                     if ($file_version > $version) {
 3104: 		        $version = $file_version;
 3105: 	            }
 3106:                 }
 3107:             }
 3108:         }
 3109:     }
 3110:     $version ++;
 3111:     return($version);
 3112: }
 3113: 
 3114: sub version_selected_portfile {
 3115:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 3116:     my ($answer_name,$answer_ver,$answer_ext) =
 3117:         &file_name_version_ext($file_name);
 3118:     my $new_answer;
 3119:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 3120:     if($env{'form.copy'} eq '-1') {
 3121:         $new_answer = 'problem getting file';
 3122:     } else {
 3123:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 3124:         my $copy_result = &Apache::lonnet::finishuserfileupload(
 3125:                             $stu_name,$domain,'copy',
 3126: 		        '/portfolio'.$directory.$new_answer);
 3127:     }    
 3128:     return ($new_answer);
 3129: }
 3130: 
 3131: sub file_name_version_ext {
 3132:     my ($file)=@_;
 3133:     my @file_parts = split(/\./, $file);
 3134:     my ($name,$version,$ext);
 3135:     if (@file_parts > 1) {
 3136: 	$ext=pop(@file_parts);
 3137: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 3138: 	    $version=pop(@file_parts);
 3139: 	}
 3140: 	$name=join('.',@file_parts);
 3141:     } else {
 3142: 	$name=join('.',@file_parts);
 3143:     }
 3144:     return($name,$version,$ext);
 3145: }
 3146: 
 3147: #--------------------------------------------------------------------------------------
 3148: #
 3149: #-------------------------- Next few routines handles grading by section or whole class
 3150: #
 3151: #--- Javascript to handle grading by section or whole class
 3152: sub viewgrades_js {
 3153:     my ($request) = shift;
 3154: 
 3155:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3156:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
 3157:    function writePoint(partid,weight,point) {
 3158: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3159: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3160: 	if (point == "textval") {
 3161: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3162: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3163: 		alert("$alertmsg"+parseFloat(point));
 3164: 		var resetbox = false;
 3165: 		for (var i=0; i<radioButton.length; i++) {
 3166: 		    if (radioButton[i].checked) {
 3167: 			textbox.value = i;
 3168: 			resetbox = true;
 3169: 		    }
 3170: 		}
 3171: 		if (!resetbox) {
 3172: 		    textbox.value = "";
 3173: 		}
 3174: 		return;
 3175: 	    }
 3176: 	    if (parseFloat(point) > parseFloat(weight)) {
 3177: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3178: 				   ") greater than the weight for the part. Accept?");
 3179: 		if (resp == false) {
 3180: 		    textbox.value = "";
 3181: 		    return;
 3182: 		}
 3183: 	    }
 3184: 	    for (var i=0; i<radioButton.length; i++) {
 3185: 		radioButton[i].checked=false;
 3186: 		if (parseFloat(point) == i) {
 3187: 		    radioButton[i].checked=true;
 3188: 		}
 3189: 	    }
 3190: 
 3191: 	} else {
 3192: 	    textbox.value = parseFloat(point);
 3193: 	}
 3194: 	for (i=0;i<document.classgrade.total.value;i++) {
 3195: 	    var user = document.classgrade["ctr"+i].value;
 3196: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3197: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3198: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3199: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3200: 	    if (saveval != "correct") {
 3201: 		scorename.value = point;
 3202: 		if (selname[0].selected != true) {
 3203: 		    selname[0].selected = true;
 3204: 		}
 3205: 	    }
 3206: 	}
 3207: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3208:     }
 3209: 
 3210:     function writeRadText(partid,weight) {
 3211: 	var selval   = document.classgrade["SELVAL_"+partid];
 3212: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3213:         var override = document.classgrade["FORCE_"+partid].checked;
 3214: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3215: 	if (selval[1].selected || selval[2].selected) {
 3216: 	    for (var i=0; i<radioButton.length; i++) {
 3217: 		radioButton[i].checked=false;
 3218: 
 3219: 	    }
 3220: 	    textbox.value = "";
 3221: 
 3222: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3223: 		var user = document.classgrade["ctr"+i].value;
 3224: 		user = user.replace(new RegExp(':', 'g'),"_");
 3225: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3226: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3227: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3228: 		if ((saveval != "correct") || override) {
 3229: 		    scorename.value = "";
 3230: 		    if (selval[1].selected) {
 3231: 			selname[1].selected = true;
 3232: 		    } else {
 3233: 			selname[2].selected = true;
 3234: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3235: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3236: 		    }
 3237: 		}
 3238: 	    }
 3239: 	} else {
 3240: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3241: 		var user = document.classgrade["ctr"+i].value;
 3242: 		user = user.replace(new RegExp(':', 'g'),"_");
 3243: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3244: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3245: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3246: 		if ((saveval != "correct") || override) {
 3247: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3248: 		    selname[0].selected = true;
 3249: 		}
 3250: 	    }
 3251: 	}	    
 3252:     }
 3253: 
 3254:     function changeSelect(partid,user) {
 3255: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3256: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3257: 	var point  = textbox.value;
 3258: 	var weight = document.classgrade["weight_"+partid].value;
 3259: 
 3260: 	if (isNaN(point) || parseFloat(point) < 0) {
 3261: 	    alert("$alertmsg"+parseFloat(point));
 3262: 	    textbox.value = "";
 3263: 	    return;
 3264: 	}
 3265: 	if (parseFloat(point) > parseFloat(weight)) {
 3266: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3267: 			       ") greater than the weight of the part. Accept?");
 3268: 	    if (resp == false) {
 3269: 		textbox.value = "";
 3270: 		return;
 3271: 	    }
 3272: 	}
 3273: 	selval[0].selected = true;
 3274:     }
 3275: 
 3276:     function changeOneScore(partid,user) {
 3277: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3278: 	if (selval[1].selected || selval[2].selected) {
 3279: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3280: 	    if (selval[2].selected) {
 3281: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3282: 	    }
 3283:         }
 3284:     }
 3285: 
 3286:     function resetEntry(numpart) {
 3287: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3288: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3289: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3290: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3291: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3292: 	    for (var i=0; i<radioButton.length; i++) {
 3293: 		radioButton[i].checked=false;
 3294: 
 3295: 	    }
 3296: 	    textbox.value = "";
 3297: 	    selval[0].selected = true;
 3298: 
 3299: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3300: 		var user = document.classgrade["ctr"+i].value;
 3301: 		user = user.replace(new RegExp(':', 'g'),"_");
 3302: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3303: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3304: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3305: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3306: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3307: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3308: 		if (saveselval == "excused") {
 3309: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3310: 		} else {
 3311: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3312: 		}
 3313: 	    }
 3314: 	}
 3315:     }
 3316: 
 3317: VIEWJAVASCRIPT
 3318: }
 3319: 
 3320: #--- show scores for a section or whole class w/ option to change/update a score
 3321: sub viewgrades {
 3322:     my ($request,$symb) = @_;
 3323:     &viewgrades_js($request);
 3324: 
 3325:     #need to make sure we have the correct data for later EXT calls, 
 3326:     #thus invalidate the cache
 3327:     &Apache::lonnet::devalidatecourseresdata(
 3328:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3329:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3330:     &Apache::lonnet::clear_EXT_cache_status();
 3331: 
 3332:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3333: 
 3334:     #view individual student submission form - called using Javascript viewOneStudent
 3335:     $result.=&jscriptNform($symb);
 3336: 
 3337:     #beginning of class grading form
 3338:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3339:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3340: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3341: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3342: 	&build_section_inputs().
 3343: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3344: 
 3345:     my ($common_header,$specific_header);
 3346:     if ($env{'form.section'} eq 'all') {
 3347: 	$common_header = &mt('Assign Common Grade to Class');
 3348:         $specific_header = &mt('Assign Grade to Specific Students in Class');
 3349:     } elsif ($env{'form.section'} eq 'none') {
 3350:         $common_header = &mt('Assign Common Grade to Students in no Section');
 3351: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
 3352:     } else {
 3353:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3354:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
 3355: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
 3356:     }
 3357:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
 3358:     #radio buttons/text box for assigning points for a section or class.
 3359:     #handles different parts of a problem
 3360:     my $res_error;
 3361:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3362:     if ($res_error) {
 3363:         return &navmap_errormsg();
 3364:     }
 3365:     my %weight = ();
 3366:     my $ctsparts = 0;
 3367:     my %seen = ();
 3368:     my @part_response_id = &flatten_responseType($responseType);
 3369:     foreach my $part_response_id (@part_response_id) {
 3370:     	my ($partid,$respid) = @{ $part_response_id };
 3371: 	my $part_resp = join('_',@{ $part_response_id });
 3372: 	next if $seen{$partid};
 3373: 	$seen{$partid}++;
 3374: 	my $handgrade=$$handgrade{$part_resp};
 3375: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 3376: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 3377: 
 3378: 	my $display_part=&get_display_part($partid,$symb);
 3379: 	my $radio.='<table border="0"><tr>';  
 3380: 	my $ctr = 0;
 3381: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 3382: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 3383: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 3384: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 3385: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 3386: 	    $ctr++;
 3387: 	}
 3388: 	$radio.='</tr></table>';
 3389: 	my $line = '<input type="text" name="TEXTVAL_'.
 3390: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
 3391: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 3392: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 3393: 	$line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
 3394: 	    'onchange="javascript:writeRadText(\''.$partid.'\','.
 3395: 		$weight{$partid}.')"> '.
 3396: 	    '<option selected="selected"> </option>'.
 3397: 	    '<option value="excused">'.&mt('excused').'</option>'.
 3398: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 3399: 	    '</select></td>'.
 3400:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 3401: 	$line.='<input type="hidden" name="partid_'.
 3402: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 3403: 	$line.='<input type="hidden" name="weight_'.
 3404: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 3405: 
 3406: 	$result.=
 3407: 	    &Apache::loncommon::start_data_table_row()."\n".
 3408: 	    '<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>'.
 3409: 	    &Apache::loncommon::end_data_table_row()."\n";
 3410: 	$ctsparts++;
 3411:     }
 3412:     $result.=&Apache::loncommon::end_data_table()."\n".
 3413: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 3414:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 3415: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
 3416: 
 3417:     #table listing all the students in a section/class
 3418:     #header of table
 3419:     $result.= '<h3>'.$specific_header.'</h3>'.
 3420:               &Apache::loncommon::start_data_table().
 3421: 	      &Apache::loncommon::start_data_table_header_row().
 3422: 	      '<th>'.&mt('No.').'</th>'.
 3423: 	      '<th>'.&nameUserString('header')."</th>\n";
 3424:     my $partserror;
 3425:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3426:     if ($partserror) {
 3427:         return &navmap_errormsg();
 3428:     }
 3429:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 3430:     my @partids = ();
 3431:     foreach my $part (@parts) {
 3432: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3433:         my $narrowtext = &mt('Tries');
 3434: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 3435: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 3436: 	my ($partid) = &split_part_type($part);
 3437:         push(@partids,$partid);
 3438: #
 3439: # FIXME: Looks like $display looks at English text
 3440: #
 3441: 	my $display_part=&get_display_part($partid,$symb);
 3442: 	if ($display =~ /^Partial Credit Factor/) {
 3443: 	    $result.='<th>'.
 3444: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
 3445: 		    $display_part,$weight{$partid}).'</th>'."\n";
 3446: 	    next;
 3447: 	    
 3448: 	} else {
 3449: 	    if ($display =~ /Problem Status/) {
 3450: 		my $grade_status_mt = &mt('Grade Status');
 3451: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 3452: 	    }
 3453: 	    my $part_mt = &mt('Part:');
 3454: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 3455: 	}
 3456: 
 3457: 	$result.='<th>'.$display.'</th>'."\n";
 3458:     }
 3459:     $result.=&Apache::loncommon::end_data_table_header_row();
 3460: 
 3461:     my %last_resets = 
 3462: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 3463: 
 3464:     #get info for each student
 3465:     #list all the students - with points and grade status
 3466:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3467:     my $ctr = 0;
 3468:     foreach (sort 
 3469: 	     {
 3470: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3471: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3472: 		 }
 3473: 		 return $a cmp $b;
 3474: 	     } (keys(%$fullname))) {
 3475: 	$ctr++;
 3476: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 3477: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
 3478:     }
 3479:     $result.=&Apache::loncommon::end_data_table();
 3480:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 3481:     $result.='<input type="button" value="'.&mt('Save').'" '.
 3482: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
 3483:     if (scalar(%$fullname) eq 0) {
 3484: 	my $colspan=3+scalar(@parts);
 3485: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3486:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 3487: 	$result='<span class="LC_warning">'.
 3488: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 3489: 	        $section_display, $stu_status).
 3490: 	    '</span>';
 3491:     }
 3492:     return $result;
 3493: }
 3494: 
 3495: #--- call by previous routine to display each student
 3496: sub viewstudentgrade {
 3497:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 3498:     my ($uname,$udom) = split(/:/,$student);
 3499:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 3500:     my %aggregates = (); 
 3501:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 3502: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
 3503: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
 3504: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 3505: 	'\');" target="_self">'.$fullname.'</a> '.
 3506: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 3507:     $student=~s/:/_/; # colon doen't work in javascript for names
 3508:     foreach my $apart (@$parts) {
 3509: 	my ($part,$type) = &split_part_type($apart);
 3510: 	my $score=$record{"resource.$part.$type"};
 3511:         $result.='<td align="center">';
 3512:         my ($aggtries,$totaltries);
 3513:         unless (exists($aggregates{$part})) {
 3514: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 3515: 
 3516: 	    $aggtries = $totaltries;
 3517:             if ($$last_resets{$part}) {  
 3518:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 3519: 					   $part);
 3520:             }
 3521:             $result.='<input type="hidden" name="'.
 3522:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 3523:             $result.='<input type="hidden" name="'.
 3524:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 3525:             $aggregates{$part} = 1;
 3526:         }
 3527: 	if ($type eq 'awarded') {
 3528: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 3529: 	    $result.='<input type="hidden" name="'.
 3530: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 3531: 	    $result.='<input type="text" name="'.
 3532: 		'GD_'.$student.'_'.$part.'_awarded" '.
 3533:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
 3534: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 3535: 	} elsif ($type eq 'solved') {
 3536: 	    my ($status,$foo)=split(/_/,$score,2);
 3537: 	    $status = 'nothing' if ($status eq '');
 3538: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 3539: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 3540: 	    $result.='&nbsp;<select name="'.
 3541: 		'GD_'.$student.'_'.$part.'_solved" '.
 3542:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 3543: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 3544: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 3545: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 3546: 	    $result.="</select>&nbsp;</td>\n";
 3547: 	} else {
 3548: 	    $result.='<input type="hidden" name="'.
 3549: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 3550: 		    "\n";
 3551: 	    $result.='<input type="text" name="'.
 3552: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 3553: 		'value="'.$score.'" size="4" /></td>'."\n";
 3554: 	}
 3555:     }
 3556:     $result.=&Apache::loncommon::end_data_table_row();
 3557:     return $result;
 3558: }
 3559: 
 3560: #--- change scores for all the students in a section/class
 3561: #    record does not get update if unchanged
 3562: sub editgrades {
 3563:     my ($request,$symb) = @_;
 3564: 
 3565:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3566:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 3567:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
 3568: 
 3569:     my $result= &Apache::loncommon::start_data_table().
 3570: 	&Apache::loncommon::start_data_table_header_row().
 3571: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 3572: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 3573:     my %scoreptr = (
 3574: 		    'correct'  =>'correct_by_override',
 3575: 		    'incorrect'=>'incorrect_by_override',
 3576: 		    'excused'  =>'excused',
 3577: 		    'ungraded' =>'ungraded_attempted',
 3578:                     'credited' =>'credit_attempted',
 3579: 		    'nothing'  => '',
 3580: 		    );
 3581:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 3582: 
 3583:     my (@partid);
 3584:     my %weight = ();
 3585:     my %columns = ();
 3586:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 3587: 
 3588:     my $partserror;
 3589:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3590:     if ($partserror) {
 3591:         return &navmap_errormsg();
 3592:     }
 3593:     my $header;
 3594:     while ($ctr < $env{'form.totalparts'}) {
 3595: 	my $partid = $env{'form.partid_'.$ctr};
 3596: 	push(@partid,$partid);
 3597: 	$weight{$partid} = $env{'form.weight_'.$partid};
 3598: 	$ctr++;
 3599:     }
 3600:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3601:     foreach my $partid (@partid) {
 3602: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 3603: 	    '<th align="center">'.&mt('New Score').'</th>';
 3604: 	$columns{$partid}=2;
 3605: 	foreach my $stores (@parts) {
 3606: 	    my ($part,$type) = &split_part_type($stores);
 3607: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 3608: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 3609: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 3610: 	    $display =~ s/\[Part: \Q$part\E\]//;
 3611:             my $narrowtext = &mt('Tries');
 3612: 	    $display =~ s/Number of Attempts/$narrowtext/;
 3613: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 3614: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 3615: 	    $columns{$partid}+=2;
 3616: 	}
 3617:     }
 3618:     foreach my $partid (@partid) {
 3619: 	my $display_part=&get_display_part($partid,$symb);
 3620: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 3621: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 3622: 	    '</th>';
 3623: 
 3624:     }
 3625:     $result .= &Apache::loncommon::end_data_table_header_row().
 3626: 	&Apache::loncommon::start_data_table_header_row().
 3627: 	$header.
 3628: 	&Apache::loncommon::end_data_table_header_row();
 3629:     my @noupdate;
 3630:     my ($updateCtr,$noupdateCtr) = (1,1);
 3631:     for ($i=0; $i<$env{'form.total'}; $i++) {
 3632: 	my $line;
 3633: 	my $user = $env{'form.ctr'.$i};
 3634: 	my ($uname,$udom)=split(/:/,$user);
 3635: 	my %newrecord;
 3636: 	my $updateflag = 0;
 3637: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 3638: 	my $usec=$classlist->{"$uname:$udom"}[5];
 3639: 	if (!&canmodify($usec)) {
 3640: 	    my $numcols=scalar(@partid)*4+2;
 3641: 	    push(@noupdate,
 3642: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
 3643: 		 &mt('Not allowed to modify student')."</span></td></tr>");
 3644: 	    next;
 3645: 	}
 3646:         my %aggregate = ();
 3647:         my $aggregateflag = 0;
 3648: 	$user=~s/:/_/; # colon doen't work in javascript for names
 3649: 	foreach (@partid) {
 3650: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 3651: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 3652: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 3653: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3654: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 3655: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 3656: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 3657: 	    my $score;
 3658: 	    if ($partial eq '') {
 3659: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3660: 	    } elsif ($partial > 0) {
 3661: 		$score = 'correct_by_override';
 3662: 	    } elsif ($partial == 0) {
 3663: 		$score = 'incorrect_by_override';
 3664: 	    }
 3665: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 3666: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 3667: 
 3668: 	    $newrecord{'resource.'.$_.'.regrader'}=
 3669: 		"$env{'user.name'}:$env{'user.domain'}";
 3670: 	    if ($dropMenu eq 'reset status' &&
 3671: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 3672: 		$newrecord{'resource.'.$_.'.tries'} = '';
 3673: 		$newrecord{'resource.'.$_.'.solved'} = '';
 3674: 		$newrecord{'resource.'.$_.'.award'} = '';
 3675: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 3676: 		$updateflag = 1;
 3677:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 3678:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 3679:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 3680:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 3681:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3682:                     $aggregateflag = 1;
 3683:                 }
 3684: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 3685: 		$updateflag = 1;
 3686: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 3687: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 3688: 		$rec_update++;
 3689: 	    }
 3690: 
 3691: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3692: 		'<td align="center">'.$awarded.
 3693: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 3694: 
 3695: 
 3696: 	    my $partid=$_;
 3697: 	    foreach my $stores (@parts) {
 3698: 		my ($part,$type) = &split_part_type($stores);
 3699: 		if ($part !~ m/^\Q$partid\E/) { next;}
 3700: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 3701: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 3702: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 3703: 		if ($awarded ne '' && $awarded ne $old_aw) {
 3704: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 3705: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3706: 		    $updateflag=1;
 3707: 		}
 3708: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3709: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 3710: 	    }
 3711: 	}
 3712: 	$line.="\n";
 3713: 
 3714: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3715: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3716: 
 3717: 	if ($updateflag) {
 3718: 	    $count++;
 3719: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 3720: 				    $udom,$uname);
 3721: 
 3722: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 3723: 					      $cnum,$udom,$uname)) {
 3724: 		# need to figure out if should be in queue.
 3725: 		my %record =  
 3726: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 3727: 					     $udom,$uname);
 3728: 		my $all_graded = 1;
 3729: 		my $none_graded = 1;
 3730: 		foreach my $part (@parts) {
 3731: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 3732: 			$all_graded = 0;
 3733: 		    } else {
 3734: 			$none_graded = 0;
 3735: 		    }
 3736: 		}
 3737: 
 3738: 		if ($all_graded || $none_graded) {
 3739: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 3740: 							   $symb,$cdom,$cnum,
 3741: 							   $udom,$uname);
 3742: 		}
 3743: 	    }
 3744: 
 3745: 	    $result.=&Apache::loncommon::start_data_table_row().
 3746: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 3747: 		&Apache::loncommon::end_data_table_row();
 3748: 	    $updateCtr++;
 3749: 	} else {
 3750: 	    push(@noupdate,
 3751: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 3752: 	    $noupdateCtr++;
 3753: 	}
 3754:         if ($aggregateflag) {
 3755:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3756: 				  $cdom,$cnum);
 3757:         }
 3758:     }
 3759:     if (@noupdate) {
 3760: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
 3761: 	my $numcols=scalar(@partid)*4+2;
 3762: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 3763: 	    '<td align="center" colspan="'.$numcols.'">'.
 3764: 	    &mt('No Changes Occurred For the Students Below').
 3765: 	    '</td>'.
 3766: 	    &Apache::loncommon::end_data_table_row();
 3767: 	foreach my $line (@noupdate) {
 3768: 	    $result.=
 3769: 		&Apache::loncommon::start_data_table_row().
 3770: 		$line.
 3771: 		&Apache::loncommon::end_data_table_row();
 3772: 	}
 3773:     }
 3774:     $result .= &Apache::loncommon::end_data_table();
 3775:     my $msg = '<p><b>'.
 3776: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 3777: 	    $rec_update,$count).'</b><br />'.
 3778: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 3779: 	'</b></p>';
 3780:     return $title.$msg.$result;
 3781: }
 3782: 
 3783: sub split_part_type {
 3784:     my ($partstr) = @_;
 3785:     my ($temp,@allparts)=split(/_/,$partstr);
 3786:     my $type=pop(@allparts);
 3787:     my $part=join('_',@allparts);
 3788:     return ($part,$type);
 3789: }
 3790: 
 3791: #------------- end of section for handling grading by section/class ---------
 3792: #
 3793: #----------------------------------------------------------------------------
 3794: 
 3795: 
 3796: #----------------------------------------------------------------------------
 3797: #
 3798: #-------------------------- Next few routines handles grading by csv upload
 3799: #
 3800: #--- Javascript to handle csv upload
 3801: sub csvupload_javascript_reverse_associate {
 3802:     my $error1=&mt('You need to specify the username or the student/employee ID');
 3803:     my $error2=&mt('You need to specify at least one grading field');
 3804:   return(<<ENDPICK);
 3805:   function verify(vf) {
 3806:     var foundsomething=0;
 3807:     var founduname=0;
 3808:     var foundID=0;
 3809:     for (i=0;i<=vf.nfields.value;i++) {
 3810:       tw=eval('vf.f'+i+'.selectedIndex');
 3811:       if (i==0 && tw!=0) { foundID=1; }
 3812:       if (i==1 && tw!=0) { founduname=1; }
 3813:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 3814:     }
 3815:     if (founduname==0 && foundID==0) {
 3816: 	alert('$error1');
 3817: 	return;
 3818:     }
 3819:     if (foundsomething==0) {
 3820: 	alert('$error2');
 3821: 	return;
 3822:     }
 3823:     vf.submit();
 3824:   }
 3825:   function flip(vf,tf) {
 3826:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3827:     var i;
 3828:     for (i=0;i<=vf.nfields.value;i++) {
 3829:       //can not pick the same destination field for both name and domain
 3830:       if (((i ==0)||(i ==1)) && 
 3831:           ((tf==0)||(tf==1)) && 
 3832:           (i!=tf) &&
 3833:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3834:         eval('vf.f'+i+'.selectedIndex=0;')
 3835:       }
 3836:     }
 3837:   }
 3838: ENDPICK
 3839: }
 3840: 
 3841: sub csvupload_javascript_forward_associate {
 3842:     my $error1=&mt('You need to specify the username or the student/employee ID');
 3843:     my $error2=&mt('You need to specify at least one grading field');
 3844:   return(<<ENDPICK);
 3845:   function verify(vf) {
 3846:     var foundsomething=0;
 3847:     var founduname=0;
 3848:     var foundID=0;
 3849:     for (i=0;i<=vf.nfields.value;i++) {
 3850:       tw=eval('vf.f'+i+'.selectedIndex');
 3851:       if (tw==1) { foundID=1; }
 3852:       if (tw==2) { founduname=1; }
 3853:       if (tw>3) { foundsomething=1; }
 3854:     }
 3855:     if (founduname==0 && foundID==0) {
 3856: 	alert('$error1');
 3857: 	return;
 3858:     }
 3859:     if (foundsomething==0) {
 3860: 	alert('$error2');
 3861: 	return;
 3862:     }
 3863:     vf.submit();
 3864:   }
 3865:   function flip(vf,tf) {
 3866:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3867:     var i;
 3868:     //can not pick the same destination field twice
 3869:     for (i=0;i<=vf.nfields.value;i++) {
 3870:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3871:         eval('vf.f'+i+'.selectedIndex=0;')
 3872:       }
 3873:     }
 3874:   }
 3875: ENDPICK
 3876: }
 3877: 
 3878: sub csvuploadmap_header {
 3879:     my ($request,$symb,$datatoken,$distotal)= @_;
 3880:     my $javascript;
 3881:     if ($env{'form.upfile_associate'} eq 'reverse') {
 3882: 	$javascript=&csvupload_javascript_reverse_associate();
 3883:     } else {
 3884: 	$javascript=&csvupload_javascript_forward_associate();
 3885:     }
 3886: 
 3887:     $symb = &Apache::lonenc::check_encrypt($symb);
 3888:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
 3889:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
 3890:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
 3891:     my $reverse=&mt("Reverse Association");
 3892:     $request->print(<<ENDPICK);
 3893: <br />
 3894: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 3895: <input type="hidden" name="associate"  value="" />
 3896: <input type="hidden" name="phase"      value="three" />
 3897: <input type="hidden" name="datatoken"  value="$datatoken" />
 3898: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 3899: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 3900: <input type="hidden" name="upfile_associate" 
 3901:                                        value="$env{'form.upfile_associate'}" />
 3902: <input type="hidden" name="symb"       value="$symb" />
 3903: <input type="hidden" name="command"    value="csvuploadoptions" />
 3904: <hr />
 3905: ENDPICK
 3906:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
 3907:     return '';
 3908: 
 3909: }
 3910: 
 3911: sub csvupload_fields {
 3912:     my ($symb,$errorref) = @_;
 3913:     my (@parts) = &getpartlist($symb,$errorref);
 3914:     if (ref($errorref)) {
 3915:         if ($$errorref) {
 3916:             return;
 3917:         }
 3918:     }
 3919: 
 3920:     my @fields=(['ID','Student/Employee ID'],
 3921: 		['username','Student Username'],
 3922: 		['domain','Student Domain']);
 3923:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3924:     foreach my $part (sort(@parts)) {
 3925: 	my @datum;
 3926: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3927: 	my $name=$part;
 3928: 	if  (!$display) { $display = $name; }
 3929: 	@datum=($name,$display);
 3930: 	if ($name=~/^stores_(.*)_awarded/) {
 3931: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 3932: 	}
 3933: 	push(@fields,\@datum);
 3934:     }
 3935:     return (@fields);
 3936: }
 3937: 
 3938: sub csvuploadmap_footer {
 3939:     my ($request,$i,$keyfields) =@_;
 3940:     $request->print(<<ENDPICK);
 3941: </table>
 3942: <input type="hidden" name="nfields" value="$i" />
 3943: <input type="hidden" name="keyfields" value="$keyfields" />
 3944: <input type="button" onclick="javascript:verify(this.form)" value="Assign Grades" /><br />
 3945: </form>
 3946: ENDPICK
 3947: }
 3948: 
 3949: sub checkforfile_js {
 3950:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 3951:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
 3952:     function checkUpload(formname) {
 3953: 	if (formname.upfile.value == "") {
 3954: 	    alert("$alertmsg");
 3955: 	    return false;
 3956: 	}
 3957: 	formname.submit();
 3958:     }
 3959: CSVFORMJS
 3960:     return $result;
 3961: }
 3962: 
 3963: sub upcsvScores_form {
 3964:     my ($request,$symb) = @_;
 3965:     if (!$symb) {return '';}
 3966:     my $result=&checkforfile_js();
 3967:     $result.=&Apache::loncommon::start_data_table().
 3968:              &Apache::loncommon::start_data_table_header_row().
 3969:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
 3970:              &Apache::loncommon::end_data_table_header_row().
 3971:              &Apache::loncommon::start_data_table_row().'<td>';
 3972:     my $upload=&mt("Upload Scores");
 3973:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 3974:     my $ignore=&mt('Ignore First Line');
 3975:     $symb = &Apache::lonenc::check_encrypt($symb);
 3976:     $result.=<<ENDUPFORM;
 3977: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3978: <input type="hidden" name="symb" value="$symb" />
 3979: <input type="hidden" name="command" value="csvuploadmap" />
 3980: $upfile_select
 3981: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 3982: </form>
 3983: ENDUPFORM
 3984:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 3985:                            &mt("How do I create a CSV file from a spreadsheet")).
 3986:              '</td>'.
 3987:             &Apache::loncommon::end_data_table_row().
 3988:             &Apache::loncommon::end_data_table();
 3989:     return $result;
 3990: }
 3991: 
 3992: 
 3993: sub csvuploadmap {
 3994:     my ($request,$symb)= @_;
 3995:     if (!$symb) {return '';}
 3996: 
 3997:     my $datatoken;
 3998:     if (!$env{'form.datatoken'}) {
 3999: 	$datatoken=&Apache::loncommon::upfile_store($request);
 4000:     } else {
 4001: 	$datatoken=$env{'form.datatoken'};
 4002: 	&Apache::loncommon::load_tmp_file($request);
 4003:     }
 4004:     my @records=&Apache::loncommon::upfile_record_sep();
 4005:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 4006:     my ($i,$keyfields);
 4007:     if (@records) {
 4008:         my $fieldserror;
 4009: 	my @fields=&csvupload_fields($symb,\$fieldserror);
 4010:         if ($fieldserror) {
 4011:             $request->print(&navmap_errormsg());
 4012:             return;
 4013:         }
 4014: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 4015: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 4016: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 4017: 							  \@fields);
 4018: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 4019: 	    chop($keyfields);
 4020: 	} else {
 4021: 	    unshift(@fields,['none','']);
 4022: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 4023: 							    \@fields);
 4024:             foreach my $rec (@records) {
 4025:                 my %temp = &Apache::loncommon::record_sep($rec);
 4026:                 if (%temp) {
 4027:                     $keyfields=join(',',sort(keys(%temp)));
 4028:                     last;
 4029:                 }
 4030:             }
 4031: 	}
 4032:     }
 4033:     &csvuploadmap_footer($request,$i,$keyfields);
 4034: 
 4035:     return '';
 4036: }
 4037: 
 4038: sub csvuploadoptions {
 4039:     my ($request,$symb)= @_;
 4040:     my $overwrite=&mt('Overwrite any existing score');
 4041:     $request->print(<<ENDPICK);
 4042: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4043: <input type="hidden" name="command"    value="csvuploadassign" />
 4044: <p>
 4045: <label>
 4046:    <input type="checkbox" name="overwite_scores" checked="checked" />
 4047:    $overwrite
 4048: </label>
 4049: </p>
 4050: ENDPICK
 4051:     my %fields=&get_fields();
 4052:     if (!defined($fields{'domain'})) {
 4053: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 4054: 	$request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
 4055:     }
 4056:     foreach my $key (sort(keys(%env))) {
 4057: 	if ($key !~ /^form\.(.*)$/) { next; }
 4058: 	my $cleankey=$1;
 4059: 	if ($cleankey eq 'command') { next; }
 4060: 	$request->print('<input type="hidden" name="'.$cleankey.
 4061: 			'"  value="'.$env{$key}.'" />'."\n");
 4062:     }
 4063:     # FIXME do a check for any duplicated user ids...
 4064:     # FIXME do a check for any invalid user ids?...
 4065:     $request->print('<input type="submit" value="Assign Grades" /><br />
 4066: <hr /></form>'."\n");
 4067:     return '';
 4068: }
 4069: 
 4070: sub get_fields {
 4071:     my %fields;
 4072:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 4073:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 4074: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 4075: 	    if ($env{'form.f'.$i} ne 'none') {
 4076: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 4077: 	    }
 4078: 	} else {
 4079: 	    if ($env{'form.f'.$i} ne 'none') {
 4080: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 4081: 	    }
 4082: 	}
 4083:     }
 4084:     return %fields;
 4085: }
 4086: 
 4087: sub csvuploadassign {
 4088:     my ($request,$symb)= @_;
 4089:     if (!$symb) {return '';}
 4090:     my $error_msg = '';
 4091:     &Apache::loncommon::load_tmp_file($request);
 4092:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 4093:     my %fields=&get_fields();
 4094:     my $courseid=$env{'request.course.id'};
 4095:     my ($classlist) = &getclasslist('all',0);
 4096:     my @notallowed;
 4097:     my @skipped;
 4098:     my @warnings;
 4099:     my $countdone=0;
 4100:     foreach my $grade (@gradedata) {
 4101: 	my %entries=&Apache::loncommon::record_sep($grade);
 4102: 	my $domain;
 4103: 	if ($entries{$fields{'domain'}}) {
 4104: 	    $domain=$entries{$fields{'domain'}};
 4105: 	} else {
 4106: 	    $domain=$env{'form.default_domain'};
 4107: 	}
 4108: 	$domain=~s/\s//g;
 4109: 	my $username=$entries{$fields{'username'}};
 4110: 	$username=~s/\s//g;
 4111: 	if (!$username) {
 4112: 	    my $id=$entries{$fields{'ID'}};
 4113: 	    $id=~s/\s//g;
 4114: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 4115: 	    $username=$ids{$id};
 4116: 	}
 4117: 	if (!exists($$classlist{"$username:$domain"})) {
 4118: 	    my $id=$entries{$fields{'ID'}};
 4119: 	    $id=~s/\s//g;
 4120: 	    if ($id) {
 4121: 		push(@skipped,"$id:$domain");
 4122: 	    } else {
 4123: 		push(@skipped,"$username:$domain");
 4124: 	    }
 4125: 	    next;
 4126: 	}
 4127: 	my $usec=$classlist->{"$username:$domain"}[5];
 4128: 	if (!&canmodify($usec)) {
 4129: 	    push(@notallowed,"$username:$domain");
 4130: 	    next;
 4131: 	}
 4132: 	my %points;
 4133: 	my %grades;
 4134: 	foreach my $dest (keys(%fields)) {
 4135: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 4136: 		$dest eq 'domain') { next; }
 4137: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 4138: 	    if ($dest=~/stores_(.*)_points/) {
 4139: 		my $part=$1;
 4140: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 4141: 					      $symb,$domain,$username);
 4142:                 if ($wgt) {
 4143:                     $entries{$fields{$dest}}=~s/\s//g;
 4144:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 4145:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 4146:                                           : 'correct_by_override';
 4147:                     if ($pcr>1) {
 4148:                        push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
 4149:                     }
 4150:                     $grades{"resource.$part.awarded"}=$pcr;
 4151:                     $grades{"resource.$part.solved"}=$award;
 4152:                     $points{$part}=1;
 4153:                 } else {
 4154:                     $error_msg = "<br />" .
 4155:                         &mt("Some point values were assigned"
 4156:                             ." for problems with a weight "
 4157:                             ."of zero. These values were "
 4158:                             ."ignored.");
 4159:                 }
 4160: 	    } else {
 4161: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 4162: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 4163: 		my $store_key=$dest;
 4164: 		$store_key=~s/^stores/resource/;
 4165: 		$store_key=~s/_/\./g;
 4166: 		$grades{$store_key}=$entries{$fields{$dest}};
 4167: 	    }
 4168: 	}
 4169: 	if (! %grades) { 
 4170:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 4171:         } else {
 4172: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 4173: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 4174: 					   $env{'request.course.id'},
 4175: 					   $domain,$username);
 4176: 	   if ($result eq 'ok') {
 4177: # Successfully stored
 4178: 	      $request->print('.');
 4179: # Remove from grading queue
 4180:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
 4181:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
 4182:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
 4183:                                              $domain,$username);
 4184:               $countdone++;
 4185:            } else {
 4186: 	      $request->print("<p><span class=\"LC_error\">".
 4187:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 4188:                                   "$username:$domain",$result)."</span></p>");
 4189: 	   }
 4190: 	   $request->rflush();
 4191:         }
 4192:     }
 4193:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
 4194:     if (@warnings) {
 4195:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
 4196:         $request->print(join(', ',@warnings));
 4197:     }
 4198:     if (@skipped) {
 4199: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
 4200:         $request->print(join(', ',@skipped));
 4201:     }
 4202:     if (@notallowed) {
 4203: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
 4204: 	$request->print(join(', ',@notallowed));
 4205:     }
 4206:     $request->print("<br />\n");
 4207:     return $error_msg;
 4208: }
 4209: #------------- end of section for handling csv file upload ---------
 4210: #
 4211: #-------------------------------------------------------------------
 4212: #
 4213: #-------------- Next few routines handle grading by page/sequence
 4214: #
 4215: #--- Select a page/sequence and a student to grade
 4216: sub pickStudentPage {
 4217:     my ($request,$symb) = @_;
 4218: 
 4219:     my $alertmsg = &mt('Please select the student you wish to grade.');
 4220:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
 4221: 
 4222: function checkPickOne(formname) {
 4223:     if (radioSelection(formname.student) == null) {
 4224: 	alert("$alertmsg");
 4225: 	return;
 4226:     }
 4227:     ptr = pullDownSelection(formname.selectpage);
 4228:     formname.page.value = formname["page"+ptr].value;
 4229:     formname.title.value = formname["title"+ptr].value;
 4230:     formname.submit();
 4231: }
 4232: 
 4233: LISTJAVASCRIPT
 4234:     &commonJSfunctions($request);
 4235: 
 4236:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4237:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4238:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4239: 
 4240:     my $result='<h3><span class="LC_info">&nbsp;'.
 4241: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 4242: 
 4243:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 4244:     my $map_error;
 4245:     my ($titles,$symbx) = &getSymbMap($map_error);
 4246:     if ($map_error) {
 4247:         $request->print(&navmap_errormsg());
 4248:         return; 
 4249:     }
 4250:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 4251: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 4252: #    my $type=($curpage =~ /\.(page|sequence)/);
 4253:     my $select = '<select name="selectpage">'."\n";
 4254:     my $ctr=0;
 4255:     foreach (@$titles) {
 4256: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4257: 	$select.='<option value="'.$ctr.'" '.
 4258: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4259: 	    '>'.$showtitle.'</option>'."\n";
 4260: 	$ctr++;
 4261:     }
 4262:     $select.= '</select>';
 4263:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
 4264: 
 4265:     $ctr=0;
 4266:     foreach (@$titles) {
 4267: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4268: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 4269: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 4270: 	$ctr++;
 4271:     }
 4272:     $result.='<input type="hidden" name="page" />'."\n".
 4273: 	'<input type="hidden" name="title" />'."\n";
 4274: 
 4275:     my $options =
 4276: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
 4277: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
 4278:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
 4279: 
 4280:     $options =
 4281: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
 4282: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
 4283: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
 4284:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
 4285:     
 4286:     $result.=&build_section_inputs();
 4287:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4288:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 4289: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 4290: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."<br />\n";
 4291: 
 4292:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
 4293: 
 4294:     $result.='&nbsp;<input type="button" '.
 4295:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 4296: 
 4297:     $request->print($result);
 4298: 
 4299:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 4300: 	&Apache::loncommon::start_data_table().
 4301: 	&Apache::loncommon::start_data_table_header_row().
 4302: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4303: 	'<th>'.&nameUserString('header').'</th>'.
 4304: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4305: 	'<th>'.&nameUserString('header').'</th>'.
 4306: 	&Apache::loncommon::end_data_table_header_row();
 4307:  
 4308:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 4309:     my $ptr = 1;
 4310:     foreach my $student (sort 
 4311: 			 {
 4312: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4313: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4314: 			     }
 4315: 			     return $a cmp $b;
 4316: 			 } (keys(%$fullname))) {
 4317: 	my ($uname,$udom) = split(/:/,$student);
 4318: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 4319:                                   : '</td>');
 4320: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 4321: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 4322: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 4323: 	$studentTable.=
 4324: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 4325:                          : '');
 4326: 	$ptr++;
 4327:     }
 4328:     if ($ptr%2 == 0) {
 4329: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 4330: 	    &Apache::loncommon::end_data_table_row();
 4331:     }
 4332:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 4333:     $studentTable.='<input type="button" '.
 4334:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 4335: 
 4336:     $request->print($studentTable);
 4337: 
 4338:     return '';
 4339: }
 4340: 
 4341: sub getSymbMap {
 4342:     my ($map_error) = @_;
 4343:     my $navmap = Apache::lonnavmaps::navmap->new();
 4344:     unless (ref($navmap)) {
 4345:         if (ref($map_error)) {
 4346:             $$map_error = 'navmap';
 4347:         }
 4348:         return;
 4349:     }
 4350:     my %symbx = ();
 4351:     my @titles = ();
 4352:     my $minder = 0;
 4353: 
 4354:     # Gather every sequence that has problems.
 4355:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 4356: 					       1,0,1);
 4357:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 4358: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 4359: 	    my $title = $minder.'.'.
 4360: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 4361: 	    push(@titles, $title); # minder in case two titles are identical
 4362: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 4363: 	    $minder++;
 4364: 	}
 4365:     }
 4366:     return \@titles,\%symbx;
 4367: }
 4368: 
 4369: #
 4370: #--- Displays a page/sequence w/wo problems, w/wo submissions
 4371: sub displayPage {
 4372:     my ($request,$symb) = @_;
 4373:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4374:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4375:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4376:     my $pageTitle = $env{'form.page'};
 4377:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4378:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4379:     my $usec=$classlist->{$env{'form.student'}}[5];
 4380: 
 4381:     #need to make sure we have the correct data for later EXT calls, 
 4382:     #thus invalidate the cache
 4383:     &Apache::lonnet::devalidatecourseresdata(
 4384:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 4385:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 4386:     &Apache::lonnet::clear_EXT_cache_status();
 4387: 
 4388:     if (!&canview($usec)) {
 4389: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
 4390: 	return;
 4391:     }
 4392:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4393:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 4394: 	'</h3>'."\n";
 4395:     $env{'form.CODE'} = uc($env{'form.CODE'});
 4396:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 4397: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 4398:     } else {
 4399: 	delete($env{'form.CODE'});
 4400:     }
 4401:     &sub_page_js($request);
 4402:     $request->print($result);
 4403: 
 4404:     my $navmap = Apache::lonnavmaps::navmap->new();
 4405:     unless (ref($navmap)) {
 4406:         $request->print(&navmap_errormsg());
 4407:         return;
 4408:     }
 4409:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 4410:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4411:     if (!$map) {
 4412: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 4413: 	return; 
 4414:     }
 4415:     my $iterator = $navmap->getIterator($map->map_start(),
 4416: 					$map->map_finish());
 4417: 
 4418:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 4419: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 4420: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 4421: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 4422: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 4423: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 4424: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4425: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
 4426: 
 4427:     if (defined($env{'form.CODE'})) {
 4428: 	$studentTable.=
 4429: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 4430:     }
 4431:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 4432: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 4433: 
 4434:     $studentTable.='&nbsp;<span class="LC_info">'.
 4435:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
 4436:         '</span>'."\n".
 4437: 	&Apache::loncommon::start_data_table().
 4438: 	&Apache::loncommon::start_data_table_header_row().
 4439: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
 4440: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 4441: 	&Apache::loncommon::end_data_table_header_row();
 4442: 
 4443:     &Apache::lonxml::clear_problem_counter();
 4444:     my ($depth,$question,$prob) = (1,1,1);
 4445:     $iterator->next(); # skip the first BEGIN_MAP
 4446:     my $curRes = $iterator->next(); # for "current resource"
 4447:     while ($depth > 0) {
 4448:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4449:         if($curRes == $iterator->END_MAP) { $depth--; }
 4450: 
 4451:         if (ref($curRes) && $curRes->is_problem()) {
 4452: 	    my $parts = $curRes->parts();
 4453:             my $title = $curRes->compTitle();
 4454: 	    my $symbx = $curRes->symb();
 4455: 	    $studentTable.=
 4456: 		&Apache::loncommon::start_data_table_row().
 4457: 		'<td align="center" valign="top" >'.$prob.
 4458: 		(scalar(@{$parts}) == 1 ? '' 
 4459: 		                        : '<br />('.&mt('[_1]parts)',
 4460: 							scalar(@{$parts}).'&nbsp;')
 4461: 		 ).
 4462: 		 '</td>';
 4463: 	    $studentTable.='<td valign="top">';
 4464: 	    my %form = ('CODE' => $env{'form.CODE'},);
 4465: 	    if ($env{'form.vProb'} eq 'yes' ) {
 4466: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 4467: 					     undef,'both',\%form);
 4468: 	    } else {
 4469: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 4470: 		$companswer =~ s|<form(.*?)>||g;
 4471: 		$companswer =~ s|</form>||g;
 4472: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 4473: #		    $companswer =~ s/$1/ /ms;
 4474: #		    $request->print('match='.$1."<br />\n");
 4475: #		}
 4476: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 4477: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 4478: 	    }
 4479: 
 4480: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 4481: 
 4482: 	    if ($env{'form.lastSub'} eq 'datesub') {
 4483: 		if ($record{'version'} eq '') {
 4484: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
 4485: 		} else {
 4486: 		    my %responseType = ();
 4487: 		    foreach my $partid (@{$parts}) {
 4488: 			my @responseIds =$curRes->responseIds($partid);
 4489: 			my @responseType =$curRes->responseType($partid);
 4490: 			my %responseIds;
 4491: 			for (my $i=0;$i<=$#responseIds;$i++) {
 4492: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 4493: 			}
 4494: 			$responseType{$partid} = \%responseIds;
 4495: 		    }
 4496: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 4497: 
 4498: 		}
 4499: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 4500: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 4501: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 4502: 									$env{'request.course.id'},
 4503: 									'','.submission');
 4504:  
 4505: 	    }
 4506: 	    if (&canmodify($usec)) {
 4507:             $studentTable.=&gradeBox_start();
 4508: 		foreach my $partid (@{$parts}) {
 4509: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 4510: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 4511: 		    $question++;
 4512: 		}
 4513:             $studentTable.=&gradeBox_end();
 4514: 		$prob++;
 4515: 	    }
 4516: 	    $studentTable.='</td></tr>';
 4517: 
 4518: 	}
 4519:         $curRes = $iterator->next();
 4520:     }
 4521: 
 4522:     $studentTable.=
 4523:         '</table>'."\n".
 4524:         '<input type="button" value="'.&mt('Save').'" '.
 4525:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 4526:         '</form>'."\n";
 4527:     $request->print($studentTable);
 4528: 
 4529:     return '';
 4530: }
 4531: 
 4532: sub displaySubByDates {
 4533:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 4534:     my $isCODE=0;
 4535:     my $isTask = ($symb =~/\.task$/);
 4536:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 4537:     my $studentTable=&Apache::loncommon::start_data_table().
 4538: 	&Apache::loncommon::start_data_table_header_row().
 4539: 	'<th>'.&mt('Date/Time').'</th>'.
 4540: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 4541: 	'<th>'.&mt('Submission').'</th>'.
 4542: 	'<th>'.&mt('Status').'</th>'.
 4543: 	&Apache::loncommon::end_data_table_header_row();
 4544:     my ($version);
 4545:     my %mark;
 4546:     my %orders;
 4547:     $mark{'correct_by_student'} = $checkIcon;
 4548:     if (!exists($$record{'1:timestamp'})) {
 4549: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 4550:     }
 4551: 
 4552:     my $interaction;
 4553:     my $no_increment = 1;
 4554:     my %lastrndseed;
 4555:     for ($version=1;$version<=$$record{'version'};$version++) {
 4556: 	my $timestamp = 
 4557: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 4558: 	if (exists($$record{$version.':resource.0.version'})) {
 4559: 	    $interaction = $$record{$version.':resource.0.version'};
 4560: 	}
 4561: 
 4562: 	my $where = ($isTask ? "$version:resource.$interaction"
 4563: 		             : "$version:resource");
 4564: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 4565: 	    '<td>'.$timestamp.'</td>';
 4566: 	if ($isCODE) {
 4567: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 4568: 	}
 4569: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 4570: 	my @displaySub = ();
 4571: 	foreach my $partid (@{$parts}) {
 4572:             my ($hidden,$type);
 4573:             $type = $$record{$version.':resource.'.$partid.'.type'};
 4574:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
 4575:                 $hidden = 1;
 4576:             }
 4577: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
 4578: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 4579: 	    
 4580: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 4581: 	    my $display_part=&get_display_part($partid,$symb);
 4582: 	    foreach my $matchKey (@matchKey) {
 4583: 		if (exists($$record{$version.':'.$matchKey}) &&
 4584: 		    $$record{$version.':'.$matchKey} ne '') {
 4585:                     
 4586: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 4587: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 4588:                     $displaySub[0].='<span class="LC_nobreak"';
 4589:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
 4590:                                    .' <span class="LC_internal_info">'
 4591:                                    .'('.&mt('Response ID: [_1]',$responseId).')'
 4592:                                    .'</span>'
 4593:                                    .' <b>';
 4594:                     if ($hidden) {
 4595:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
 4596:                     } else {
 4597:                         my ($trial,$rndseed,$newvariation);
 4598:                         if ($type eq 'randomizetry') {
 4599:                             $trial = $$record{"$where.$partid.tries"};
 4600:                             $rndseed = $$record{"$where.$partid.rndseed"};
 4601:                         }
 4602: 		        if ($$record{"$where.$partid.tries"} eq '') {
 4603: 			    $displaySub[0].=&mt('Trial not counted');
 4604: 		        } else {
 4605: 			    $displaySub[0].=&mt('Trial: [_1]',
 4606: 					    $$record{"$where.$partid.tries"});
 4607:                             if ($rndseed || $lastrndseed{$partid}) {
 4608:                                 if ($rndseed ne $lastrndseed{$partid}) {
 4609:                                     $newvariation = '&nbsp;('.&mt('New variation this try').')';
 4610:                                 }
 4611:                             }
 4612:                             $lastrndseed{$partid} = $rndseed;
 4613: 		        }
 4614: 		        my $responseType=($isTask ? 'Task'
 4615:                                               : $responseType->{$partid}->{$responseId});
 4616: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
 4617: 		        if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
 4618: 			    $orders{$partid}->{$responseId}=
 4619: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
 4620:                                            $no_increment,$type,$trial,$rndseed);
 4621: 		        }
 4622: 		        $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
 4623: 		        $displaySub[0].='&nbsp; '.
 4624: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
 4625:                     }
 4626: 		}
 4627: 	    }
 4628: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 4629: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 4630: 				    $$record{"$where.$partid.checkedin"},
 4631: 				    $$record{"$where.$partid.checkedin.slot"}).
 4632: 					'<br />';
 4633: 	    }
 4634: 	    if (exists $$record{"$where.$partid.award"}) {
 4635: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 4636: 		    lc($$record{"$where.$partid.award"}).' '.
 4637: 		    $mark{$$record{"$where.$partid.solved"}}.
 4638: 		    '<br />';
 4639: 	    }
 4640: 	    if (exists $$record{"$where.$partid.regrader"}) {
 4641: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 4642: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4643: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 4644: 		$displaySub[2].=
 4645: 		    $$record{"$version:resource.$partid.regrader"}.
 4646: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4647: 	    }
 4648: 	}
 4649: 	# needed because old essay regrader has not parts info
 4650: 	if (exists $$record{"$version:resource.regrader"}) {
 4651: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 4652: 	}
 4653: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 4654: 	if ($displaySub[2]) {
 4655: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 4656: 	}
 4657: 	$studentTable.='&nbsp;</td>'.
 4658: 	    &Apache::loncommon::end_data_table_row();
 4659:     }
 4660:     $studentTable.=&Apache::loncommon::end_data_table();
 4661:     return $studentTable;
 4662: }
 4663: 
 4664: sub updateGradeByPage {
 4665:     my ($request,$symb) = @_;
 4666: 
 4667:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4668:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4669:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4670:     my $pageTitle = $env{'form.page'};
 4671:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4672:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4673:     my $usec=$classlist->{$env{'form.student'}}[5];
 4674:     if (!&canmodify($usec)) {
 4675: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 4676: 	return;
 4677:     }
 4678:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4679:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 4680: 	'</h3>'."\n";
 4681: 
 4682:     $request->print($result);
 4683: 
 4684: 
 4685:     my $navmap = Apache::lonnavmaps::navmap->new();
 4686:     unless (ref($navmap)) {
 4687:         $request->print(&navmap_errormsg());
 4688:         return;
 4689:     }
 4690:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 4691:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4692:     if (!$map) {
 4693: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 4694: 	return; 
 4695:     }
 4696:     my $iterator = $navmap->getIterator($map->map_start(),
 4697: 					$map->map_finish());
 4698: 
 4699:     my $studentTable=
 4700: 	&Apache::loncommon::start_data_table().
 4701: 	&Apache::loncommon::start_data_table_header_row().
 4702: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 4703: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 4704: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 4705: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 4706: 	&Apache::loncommon::end_data_table_header_row();
 4707: 
 4708:     $iterator->next(); # skip the first BEGIN_MAP
 4709:     my $curRes = $iterator->next(); # for "current resource"
 4710:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
 4711:     while ($depth > 0) {
 4712:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4713:         if($curRes == $iterator->END_MAP) { $depth--; }
 4714: 
 4715:         if (ref($curRes) && $curRes->is_problem()) {
 4716: 	    my $parts = $curRes->parts();
 4717:             my $title = $curRes->compTitle();
 4718: 	    my $symbx = $curRes->symb();
 4719: 	    $studentTable.=
 4720: 		&Apache::loncommon::start_data_table_row().
 4721: 		'<td align="center" valign="top" >'.$prob.
 4722: 		(scalar(@{$parts}) == 1 ? '' 
 4723:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
 4724: 		.')').'</td>';
 4725: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 4726: 
 4727: 	    my %newrecord=();
 4728: 	    my @displayPts=();
 4729:             my %aggregate = ();
 4730:             my $aggregateflag = 0;
 4731: 	    foreach my $partid (@{$parts}) {
 4732: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 4733: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 4734: 
 4735: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 4736: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 4737: 		my $partial = $newpts/$wgt;
 4738: 		my $score;
 4739: 		if ($partial > 0) {
 4740: 		    $score = 'correct_by_override';
 4741: 		} elsif ($newpts ne '') { #empty is taken as 0
 4742: 		    $score = 'incorrect_by_override';
 4743: 		}
 4744: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 4745: 		if ($dropMenu eq 'excused') {
 4746: 		    $partial = '';
 4747: 		    $score = 'excused';
 4748: 		} elsif ($dropMenu eq 'reset status'
 4749: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 4750: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 4751: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 4752: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 4753: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 4754: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 4755: 		    $changeflag++;
 4756: 		    $newpts = '';
 4757:                     
 4758:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 4759:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 4760:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 4761:                     if ($aggtries > 0) {
 4762:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4763:                         $aggregateflag = 1;
 4764:                     }
 4765: 		}
 4766: 		my $display_part=&get_display_part($partid,$curRes->symb());
 4767: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 4768: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4769: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 4770: 		    '&nbsp;<br />';
 4771: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4772: 		     (($score eq 'excused') ? 'excused' : $newpts).
 4773: 		    '&nbsp;<br />';
 4774: 		$question++;
 4775: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 4776: 
 4777: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 4778: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 4779: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 4780: 		    if (scalar(keys(%newrecord)) > 0);
 4781: 
 4782: 		$changeflag++;
 4783: 	    }
 4784: 	    if (scalar(keys(%newrecord)) > 0) {
 4785: 		my %record = 
 4786: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 4787: 					     $udom,$uname);
 4788: 
 4789: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 4790: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 4791: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 4792: 		    $newrecord{'resource.CODE'} = '';
 4793: 		}
 4794: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 4795: 					$udom,$uname);
 4796: 		%record = &Apache::lonnet::restore($symbx,
 4797: 						   $env{'request.course.id'},
 4798: 						   $udom,$uname);
 4799: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 4800: 					     $cdom,$cnum,$udom,$uname);
 4801: 	    }
 4802: 	    
 4803:             if ($aggregateflag) {
 4804:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4805:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 4806:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 4807:             }
 4808: 
 4809: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 4810: 		'<td valign="top">'.$displayPts[1].'</td>'.
 4811: 		&Apache::loncommon::end_data_table_row();
 4812: 
 4813: 	    $prob++;
 4814: 	}
 4815:         $curRes = $iterator->next();
 4816:     }
 4817: 
 4818:     $studentTable.=&Apache::loncommon::end_data_table();
 4819:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 4820: 		  &mt('The scores were changed for [quant,_1,problem].',
 4821: 		  $changeflag));
 4822:     $request->print($grademsg.$studentTable);
 4823: 
 4824:     return '';
 4825: }
 4826: 
 4827: #-------- end of section for handling grading by page/sequence ---------
 4828: #
 4829: #-------------------------------------------------------------------
 4830: 
 4831: #-------------------- Bubblesheet (Scantron) Grading -------------------
 4832: #
 4833: #------ start of section for handling grading by page/sequence ---------
 4834: 
 4835: =pod
 4836: 
 4837: =head1 Bubble sheet grading routines
 4838: 
 4839:   For this documentation:
 4840: 
 4841:    'scanline' refers to the full line of characters
 4842:    from the file that we are parsing that represents one entire sheet
 4843: 
 4844:    'bubble line' refers to the data
 4845:    representing the line of bubbles that are on the physical bubblesheet
 4846: 
 4847: 
 4848: The overall process is that a scanned in bubblesheet data is uploaded
 4849: into a course. When a user wants to grade, they select a
 4850: sequence/folder of resources, a file of bubblesheet info, and pick
 4851: one of the predefined configurations for what each scanline looks
 4852: like.
 4853: 
 4854: Next each scanline is checked for any errors of either 'missing
 4855: bubbles' (it's an error because it may have been mis-scanned
 4856: because too light bubbling), 'double bubble' (each bubble line should
 4857: have no more that one letter picked), invalid or duplicated CODE,
 4858: invalid student/employee ID
 4859: 
 4860: If the CODE option is used that determines the randomization of the
 4861: homework problems, either way the student/employee ID is looked up into a
 4862: username:domain.
 4863: 
 4864: During the validation phase the instructor can choose to skip scanlines. 
 4865: 
 4866: After the validation phase, there are now 3 bubblesheet files
 4867: 
 4868:   scantron_original_filename (unmodified original file)
 4869:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 4870:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 4871: 
 4872: Also there is a separate hash nohist_scantrondata that contains extra
 4873: correction information that isn't representable in the bubblesheet
 4874: file (see &scantron_getfile() for more information)
 4875: 
 4876: After all scanlines are either valid, marked as valid or skipped, then
 4877: foreach line foreach problem in the picked sequence, an ssi request is
 4878: made that simulates a user submitting their selected letter(s) against
 4879: the homework problem.
 4880: 
 4881: =over 4
 4882: 
 4883: 
 4884: 
 4885: =item defaultFormData
 4886: 
 4887:   Returns html hidden inputs used to hold context/default values.
 4888: 
 4889:  Arguments:
 4890:   $symb - $symb of the current resource 
 4891: 
 4892: =cut
 4893: 
 4894: sub defaultFormData {
 4895:     my ($symb)=@_;
 4896:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />';
 4897: }
 4898: 
 4899: 
 4900: =pod 
 4901: 
 4902: =item getSequenceDropDown
 4903: 
 4904:    Return html dropdown of possible sequences to grade
 4905:  
 4906:  Arguments:
 4907:    $symb - $symb of the current resource
 4908:    $map_error - ref to scalar which will container error if
 4909:                 $navmap object is unavailable in &getSymbMap().
 4910: 
 4911: =cut
 4912: 
 4913: sub getSequenceDropDown {
 4914:     my ($symb,$map_error)=@_;
 4915:     my $result='<select name="selectpage">'."\n";
 4916:     my ($titles,$symbx) = &getSymbMap($map_error);
 4917:     if (ref($map_error)) {
 4918:         return if ($$map_error);
 4919:     }
 4920:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 4921:     my $ctr=0;
 4922:     foreach (@$titles) {
 4923: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4924: 	$result.='<option value="'.$$symbx{$_}.'" '.
 4925: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4926: 	    '>'.$showtitle.'</option>'."\n";
 4927: 	$ctr++;
 4928:     }
 4929:     $result.= '</select>';
 4930:     return $result;
 4931: }
 4932: 
 4933: my %bubble_lines_per_response;     # no. bubble lines for each response.
 4934:                                    # key is zero-based index - 0, 1, 2 ...
 4935: 
 4936: my %first_bubble_line;             # First bubble line no. for each bubble.
 4937: 
 4938: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 4939:                                    # matchresponse or rankresponse, where 
 4940:                                    # an individual response can have multiple 
 4941:                                    # lines
 4942: 
 4943: my %responsetype_per_response;     # responsetype for each response
 4944: 
 4945: # Save and restore the bubble lines array to the form env.
 4946: 
 4947: 
 4948: sub save_bubble_lines {
 4949:     foreach my $line (keys(%bubble_lines_per_response)) {
 4950: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 4951: 	$env{"form.scantron.first_bubble_line.$line"} =
 4952: 	    $first_bubble_line{$line};
 4953:         $env{"form.scantron.sub_bubblelines.$line"} = 
 4954:             $subdivided_bubble_lines{$line};
 4955:         $env{"form.scantron.responsetype.$line"} =
 4956:             $responsetype_per_response{$line};
 4957:     }
 4958: }
 4959: 
 4960: 
 4961: sub restore_bubble_lines {
 4962:     my $line = 0;
 4963:     %bubble_lines_per_response = ();
 4964:     while ($env{"form.scantron.bubblelines.$line"}) {
 4965: 	my $value = $env{"form.scantron.bubblelines.$line"};
 4966: 	$bubble_lines_per_response{$line} = $value;
 4967: 	$first_bubble_line{$line}  =
 4968: 	    $env{"form.scantron.first_bubble_line.$line"};
 4969:         $subdivided_bubble_lines{$line} =
 4970:             $env{"form.scantron.sub_bubblelines.$line"};
 4971:         $responsetype_per_response{$line} =
 4972:             $env{"form.scantron.responsetype.$line"};
 4973: 	$line++;
 4974:     }
 4975: }
 4976: 
 4977: #  Given the parsed scanline, get the response for 
 4978: #  'answer' number n:
 4979: 
 4980: sub get_response_bubbles {
 4981:     my ($parsed_line, $response)  = @_;
 4982: 
 4983:     my $bubble_line = $first_bubble_line{$response-1} +1;
 4984:     my $bubble_lines= $bubble_lines_per_response{$response-1};
 4985:     
 4986:     my $selected = "";
 4987: 
 4988:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
 4989: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
 4990: 	$bubble_line++;
 4991:     }
 4992:     return $selected;
 4993: }
 4994: 
 4995: =pod 
 4996: 
 4997: =item scantron_filenames
 4998: 
 4999:    Returns a list of the scantron files in the current course 
 5000: 
 5001: =cut
 5002: 
 5003: sub scantron_filenames {
 5004:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5005:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5006:     my $getpropath = 1;
 5007:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
 5008:                                                         $cname,$getpropath);
 5009:     my @possiblenames;
 5010:     if (ref($dirlist) eq 'ARRAY') {
 5011:         foreach my $filename (sort(@{$dirlist})) {
 5012: 	    ($filename)=split(/&/,$filename);
 5013: 	    if ($filename!~/^scantron_orig_/) { next ; }
 5014: 	    $filename=~s/^scantron_orig_//;
 5015: 	    push(@possiblenames,$filename);
 5016:         }
 5017:     }
 5018:     return @possiblenames;
 5019: }
 5020: 
 5021: =pod 
 5022: 
 5023: =item scantron_uploads
 5024: 
 5025:    Returns  html drop-down list of scantron files in current course.
 5026: 
 5027:  Arguments:
 5028:    $file2grade - filename to set as selected in the dropdown
 5029: 
 5030: =cut
 5031: 
 5032: sub scantron_uploads {
 5033:     my ($file2grade) = @_;
 5034:     my $result=	'<select name="scantron_selectfile">';
 5035:     $result.="<option></option>";
 5036:     foreach my $filename (sort(&scantron_filenames())) {
 5037: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 5038:     }
 5039:     $result.="</select>";
 5040:     return $result;
 5041: }
 5042: 
 5043: =pod 
 5044: 
 5045: =item scantron_scantab
 5046: 
 5047:   Returns html drop down of the scantron formats in the scantronformat.tab
 5048:   file.
 5049: 
 5050: =cut
 5051: 
 5052: sub scantron_scantab {
 5053:     my $result='<select name="scantron_format">'."\n";
 5054:     $result.='<option></option>'."\n";
 5055:     my @lines = &get_scantronformat_file();
 5056:     if (@lines > 0) {
 5057:         foreach my $line (@lines) {
 5058:             next if (($line =~ /^\#/) || ($line eq ''));
 5059: 	    my ($name,$descrip)=split(/:/,$line);
 5060: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 5061:         }
 5062:     }
 5063:     $result.='</select>'."\n";
 5064:     return $result;
 5065: }
 5066: 
 5067: =pod
 5068: 
 5069: =item get_scantronformat_file
 5070: 
 5071:   Returns an array containing lines from the scantron format file for
 5072:   the domain of the course.
 5073: 
 5074:   If a url for a custom.tab file is listed in domain's configuration.db, 
 5075:   lines are from this file.
 5076: 
 5077:   Otherwise, if a default.tab has been published in RES space by the 
 5078:   domainconfig user, lines are from this file.
 5079: 
 5080:   Otherwise, fall back to getting lines from the legacy file on the
 5081:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
 5082: 
 5083: =cut
 5084: 
 5085: sub get_scantronformat_file {
 5086:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5087:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
 5088:     my $gottab = 0;
 5089:     my @lines;
 5090:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 5091:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 5092:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 5093:             if ($formatfile ne '-1') {
 5094:                 @lines = split("\n",$formatfile,-1);
 5095:                 $gottab = 1;
 5096:             }
 5097:         }
 5098:     }
 5099:     if (!$gottab) {
 5100:         my $confname = $cdom.'-domainconfig';
 5101:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 5102:         my $formatfile =  &Apache::lonnet::getfile($default);
 5103:         if ($formatfile ne '-1') {
 5104:             @lines = split("\n",$formatfile,-1);
 5105:             $gottab = 1;
 5106:         }
 5107:     }
 5108:     if (!$gottab) {
 5109:         my @domains = &Apache::lonnet::current_machine_domains();
 5110:         if (grep(/^\Q$cdom\E$/,@domains)) {
 5111:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 5112:             @lines = <$fh>;
 5113:             close($fh);
 5114:         } else {
 5115:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
 5116:             @lines = <$fh>;
 5117:             close($fh);
 5118:         }
 5119:     }
 5120:     return @lines;
 5121: }
 5122: 
 5123: =pod 
 5124: 
 5125: =item scantron_CODElist
 5126: 
 5127:   Returns html drop down of the saved CODE lists from current course,
 5128:   generated from earlier printings.
 5129: 
 5130: =cut
 5131: 
 5132: sub scantron_CODElist {
 5133:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5134:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5135:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 5136:     my $namechoice='<option></option>';
 5137:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 5138: 	if ($name =~ /^error: 2 /) { next; }
 5139: 	if ($name =~ /^type\0/) { next; }
 5140: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 5141:     }
 5142:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 5143:     return $namechoice;
 5144: }
 5145: 
 5146: =pod 
 5147: 
 5148: =item scantron_CODEunique
 5149: 
 5150:   Returns the html for "Each CODE to be used once" radio.
 5151: 
 5152: =cut
 5153: 
 5154: sub scantron_CODEunique {
 5155:     my $result='<span class="LC_nobreak">
 5156:                  <label><input type="radio" name="scantron_CODEunique"
 5157:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 5158:                 </span>
 5159:                 <span class="LC_nobreak">
 5160:                  <label><input type="radio" name="scantron_CODEunique"
 5161:                         value="no" />'.&mt('No').' </label>
 5162:                 </span>';
 5163:     return $result;
 5164: }
 5165: 
 5166: =pod 
 5167: 
 5168: =item scantron_selectphase
 5169: 
 5170:   Generates the initial screen to start the bubblesheet process.
 5171:   Allows for - starting a grading run.
 5172:              - downloading existing scan data (original, corrected
 5173:                                                 or skipped info)
 5174: 
 5175:              - uploading new scan data
 5176: 
 5177:  Arguments:
 5178:   $r          - The Apache request object
 5179:   $file2grade - name of the file that contain the scanned data to score
 5180: 
 5181: =cut
 5182: 
 5183: sub scantron_selectphase {
 5184:     my ($r,$file2grade,$symb) = @_;
 5185:     if (!$symb) {return '';}
 5186:     my $map_error;
 5187:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
 5188:     if ($map_error) {
 5189:         $r->print('<br />'.&navmap_errormsg().'<br />');
 5190:         return;
 5191:     }
 5192:     my $default_form_data=&defaultFormData($symb);
 5193:     my $file_selector=&scantron_uploads($file2grade);
 5194:     my $format_selector=&scantron_scantab();
 5195:     my $CODE_selector=&scantron_CODElist();
 5196:     my $CODE_unique=&scantron_CODEunique();
 5197:     my $result;
 5198: 
 5199:     $ssi_error = 0;
 5200: 
 5201:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 5202:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 5203: 
 5204: 	# Chunk of form to prompt for a scantron file upload.
 5205: 
 5206:         $r->print('
 5207:     <br />
 5208:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5209:        '.&Apache::loncommon::start_data_table_header_row().'
 5210:             <th>
 5211:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
 5212:             </th>
 5213:        '.&Apache::loncommon::end_data_table_header_row().'
 5214:        '.&Apache::loncommon::start_data_table_row().'
 5215:             <td>
 5216: ');
 5217:     my $default_form_data=&defaultFormData($symb);
 5218:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5219:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 5220:     $r->print(&Apache::lonhtmlcommon::scripttag('
 5221:     function checkUpload(formname) {
 5222: 	if (formname.upfile.value == "") {
 5223: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
 5224: 	    return false;
 5225: 	}
 5226: 	formname.submit();
 5227:     }'));
 5228:     $r->print('
 5229:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 5230:                 '.$default_form_data.'
 5231:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 5232:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 5233:                 <input name="command" value="scantronupload_save" type="hidden" />
 5234:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
 5235:                 <br />
 5236:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 5237:               </form>
 5238: ');
 5239: 
 5240:         $r->print('
 5241:             </td>
 5242:        '.&Apache::loncommon::end_data_table_row().'
 5243:        '.&Apache::loncommon::end_data_table().'
 5244: ');
 5245:     }
 5246: 
 5247:     # Chunk of form to prompt for a file to grade and how:
 5248: 
 5249:     $result.= '
 5250:     <br />
 5251:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 5252:     <input type="hidden" name="command" value="scantron_warning" />
 5253:     '.$default_form_data.'
 5254:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5255:        '.&Apache::loncommon::start_data_table_header_row().'
 5256:             <th colspan="2">
 5257:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 5258:             </th>
 5259:        '.&Apache::loncommon::end_data_table_header_row().'
 5260:        '.&Apache::loncommon::start_data_table_row().'
 5261:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 5262:        '.&Apache::loncommon::end_data_table_row().'
 5263:        '.&Apache::loncommon::start_data_table_row().'
 5264:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
 5265:        '.&Apache::loncommon::end_data_table_row().'
 5266:        '.&Apache::loncommon::start_data_table_row().'
 5267:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
 5268:        '.&Apache::loncommon::end_data_table_row().'
 5269:        '.&Apache::loncommon::start_data_table_row().'
 5270:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 5271:        '.&Apache::loncommon::end_data_table_row().'
 5272:        '.&Apache::loncommon::start_data_table_row().'
 5273:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 5274:        '.&Apache::loncommon::end_data_table_row().'
 5275:        '.&Apache::loncommon::start_data_table_row().'
 5276: 	    <td> '.&mt('Options:').' </td>
 5277:             <td>
 5278: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 5279:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 5280:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 5281: 	    </td>
 5282:        '.&Apache::loncommon::end_data_table_row().'
 5283:        '.&Apache::loncommon::start_data_table_row().'
 5284:             <td colspan="2">
 5285:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
 5286:             </td>
 5287:        '.&Apache::loncommon::end_data_table_row().'
 5288:     '.&Apache::loncommon::end_data_table().'
 5289:     </form>
 5290: ';
 5291:    
 5292:     $r->print($result);
 5293: 
 5294: 
 5295: 
 5296:     # Chunk of the form that prompts to view a scoring office file,
 5297:     # corrected file, skipped records in a file.
 5298: 
 5299:     $r->print('
 5300:    <br />
 5301:    <form action="/adm/grades" name="scantron_download">
 5302:      '.$default_form_data.'
 5303:      <input type="hidden" name="command" value="scantron_download" />
 5304:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5305:        '.&Apache::loncommon::start_data_table_header_row().'
 5306:               <th>
 5307:                 &nbsp;'.&mt('Download a scoring office file').'
 5308:               </th>
 5309:        '.&Apache::loncommon::end_data_table_header_row().'
 5310:        '.&Apache::loncommon::start_data_table_row().'
 5311:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 5312:                 <br />
 5313:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 5314:        '.&Apache::loncommon::end_data_table_row().'
 5315:      '.&Apache::loncommon::end_data_table().'
 5316:    </form>
 5317:    <br />
 5318: ');
 5319: 
 5320:     &Apache::lonpickcode::code_list($r,2);
 5321: 
 5322:     $r->print('<br /><form method="post" name="checkscantron">'.
 5323:              $default_form_data."\n".
 5324:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 5325:              &Apache::loncommon::start_data_table_header_row()."\n".
 5326:              '<th colspan="2">
 5327:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
 5328:              '</th>'."\n".
 5329:               &Apache::loncommon::end_data_table_header_row()."\n".
 5330:               &Apache::loncommon::start_data_table_row()."\n".
 5331:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 5332:               '<td> '.$sequence_selector.' </td>'.
 5333:               &Apache::loncommon::end_data_table_row()."\n".
 5334:               &Apache::loncommon::start_data_table_row()."\n".
 5335:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 5336:               '<td> '.$file_selector.' </td>'."\n".
 5337:               &Apache::loncommon::end_data_table_row()."\n".
 5338:               &Apache::loncommon::start_data_table_row()."\n".
 5339:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 5340:               '<td> '.$format_selector.' </td>'."\n".
 5341:               &Apache::loncommon::end_data_table_row()."\n".
 5342:               &Apache::loncommon::start_data_table_row()."\n".
 5343:               '<td> '.&mt('Options').' </td>'."\n".
 5344:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
 5345:               &Apache::loncommon::end_data_table_row()."\n".
 5346:               &Apache::loncommon::start_data_table_row()."\n".
 5347:               '<td colspan="2">'."\n".
 5348:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 5349:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
 5350:               '</td>'."\n".
 5351:               &Apache::loncommon::end_data_table_row()."\n".
 5352:               &Apache::loncommon::end_data_table()."\n".
 5353:               '</form><br />');
 5354:     return;
 5355: }
 5356: 
 5357: =pod
 5358: 
 5359: =item get_scantron_config
 5360: 
 5361:    Parse and return the scantron configuration line selected as a
 5362:    hash of configuration file fields.
 5363: 
 5364:  Arguments:
 5365:     which - the name of the configuration to parse from the file.
 5366: 
 5367: 
 5368:  Returns:
 5369:             If the named configuration is not in the file, an empty
 5370:             hash is returned.
 5371:     a hash with the fields
 5372:       name         - internal name for the this configuration setup
 5373:       description  - text to display to operator that describes this config
 5374:       CODElocation - if 0 or the string 'none'
 5375:                           - no CODE exists for this config
 5376:                      if -1 || the string 'letter'
 5377:                           - a CODE exists for this config and is
 5378:                             a string of letters
 5379:                      Unsupported value (but planned for future support)
 5380:                           if a positive integer
 5381:                                - The CODE exists as the first n items from
 5382:                                  the question section of the form
 5383:                           if the string 'number'
 5384:                                - The CODE exists for this config and is
 5385:                                  a string of numbers
 5386:       CODEstart   - (only matter if a CODE exists) column in the line where
 5387:                      the CODE starts
 5388:       CODElength  - length of the CODE
 5389:       IDstart     - column where the student/employee ID starts
 5390:       IDlength    - length of the student/employee ID info
 5391:       Qstart      - column where the information from the bubbled
 5392:                     'questions' start
 5393:       Qlength     - number of columns comprising a single bubble line from
 5394:                     the sheet. (usually either 1 or 10)
 5395:       Qon         - either a single character representing the character used
 5396:                     to signal a bubble was chosen in the positional setup, or
 5397:                     the string 'letter' if the letter of the chosen bubble is
 5398:                     in the final, or 'number' if a number representing the
 5399:                     chosen bubble is in the file (1->A 0->J)
 5400:       Qoff        - the character used to represent that a bubble was
 5401:                     left blank
 5402:       PaperID     - if the scanning process generates a unique number for each
 5403:                     sheet scanned the column that this ID number starts in
 5404:       PaperIDlength - number of columns that comprise the unique ID number
 5405:                       for the sheet of paper
 5406:       FirstName   - column that the first name starts in
 5407:       FirstNameLength - number of columns that the first name spans
 5408:  
 5409:       LastName    - column that the last name starts in
 5410:       LastNameLength - number of columns that the last name spans
 5411:       BubblesPerRow - number of bubbles available in each row used to 
 5412:                       bubble an answer. (If not specified, 10 assumed).
 5413: =cut
 5414: 
 5415: sub get_scantron_config {
 5416:     my ($which) = @_;
 5417:     my @lines = &get_scantronformat_file();
 5418:     my %config;
 5419:     #FIXME probably should move to XML it has already gotten a bit much now
 5420:     foreach my $line (@lines) {
 5421: 	my ($name,$descrip)=split(/:/,$line);
 5422: 	if ($name ne $which ) { next; }
 5423: 	chomp($line);
 5424: 	my @config=split(/:/,$line);
 5425: 	$config{'name'}=$config[0];
 5426: 	$config{'description'}=$config[1];
 5427: 	$config{'CODElocation'}=$config[2];
 5428: 	$config{'CODEstart'}=$config[3];
 5429: 	$config{'CODElength'}=$config[4];
 5430: 	$config{'IDstart'}=$config[5];
 5431: 	$config{'IDlength'}=$config[6];
 5432: 	$config{'Qstart'}=$config[7];
 5433:  	$config{'Qlength'}=$config[8];
 5434: 	$config{'Qoff'}=$config[9];
 5435: 	$config{'Qon'}=$config[10];
 5436: 	$config{'PaperID'}=$config[11];
 5437: 	$config{'PaperIDlength'}=$config[12];
 5438: 	$config{'FirstName'}=$config[13];
 5439: 	$config{'FirstNamelength'}=$config[14];
 5440: 	$config{'LastName'}=$config[15];
 5441: 	$config{'LastNamelength'}=$config[16];
 5442:         $config{'BubblesPerRow'}=$config[17];
 5443: 	last;
 5444:     }
 5445:     return %config;
 5446: }
 5447: 
 5448: =pod 
 5449: 
 5450: =item username_to_idmap
 5451: 
 5452:     creates a hash keyed by student/employee ID with values of the corresponding
 5453:     student username:domain.
 5454: 
 5455:   Arguments:
 5456: 
 5457:     $classlist - reference to the class list hash. This is a hash
 5458:                  keyed by student name:domain  whose elements are references
 5459:                  to arrays containing various chunks of information
 5460:                  about the student. (See loncoursedata for more info).
 5461: 
 5462:   Returns
 5463:     %idmap - the constructed hash
 5464: 
 5465: =cut
 5466: 
 5467: sub username_to_idmap {
 5468:     my ($classlist)= @_;
 5469:     my %idmap;
 5470:     foreach my $student (keys(%$classlist)) {
 5471: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
 5472: 	    $student;
 5473:     }
 5474:     return %idmap;
 5475: }
 5476: 
 5477: =pod
 5478: 
 5479: =item scantron_fixup_scanline
 5480: 
 5481:    Process a requested correction to a scanline.
 5482: 
 5483:   Arguments:
 5484:     $scantron_config   - hash from &get_scantron_config()
 5485:     $scan_data         - hash of correction information 
 5486:                           (see &scantron_getfile())
 5487:     $line              - existing scanline
 5488:     $whichline         - line number of the passed in scanline
 5489:     $field             - type of change to process 
 5490:                          (either 
 5491:                           'ID'     -> correct the student/employee ID
 5492:                           'CODE'   -> correct the CODE
 5493:                           'answer' -> fixup the submitted answers)
 5494:     
 5495:    $args               - hash of additional info,
 5496:                           - 'ID' 
 5497:                                'newid' -> studentID to use in replacement
 5498:                                           of existing one
 5499:                           - 'CODE' 
 5500:                                'CODE_ignore_dup' - set to true if duplicates
 5501:                                                    should be ignored.
 5502: 	                       'CODE' - is new code or 'use_unfound'
 5503:                                         if the existing unfound code should
 5504:                                         be used as is
 5505:                           - 'answer'
 5506:                                'response' - new answer or 'none' if blank
 5507:                                'question' - the bubble line to change
 5508:                                'questionnum' - the question identifier,
 5509:                                                may include subquestion. 
 5510: 
 5511:   Returns:
 5512:     $line - the modified scanline
 5513: 
 5514:   Side effects: 
 5515:     $scan_data - may be updated
 5516: 
 5517: =cut
 5518: 
 5519: 
 5520: sub scantron_fixup_scanline {
 5521:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 5522:     if ($field eq 'ID') {
 5523: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 5524: 	    return ($line,1,'New value too large');
 5525: 	}
 5526: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 5527: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 5528: 				     $args->{'newid'});
 5529: 	}
 5530: 	substr($line,$$scantron_config{'IDstart'}-1,
 5531: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 5532: 	if ($args->{'newid'}=~/^\s*$/) {
 5533: 	    &scan_data($scan_data,"$whichline.user",
 5534: 		       $args->{'username'}.':'.$args->{'domain'});
 5535: 	}
 5536:     } elsif ($field eq 'CODE') {
 5537: 	if ($args->{'CODE_ignore_dup'}) {
 5538: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 5539: 	}
 5540: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 5541: 	if ($args->{'CODE'} ne 'use_unfound') {
 5542: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 5543: 		return ($line,1,'New CODE value too large');
 5544: 	    }
 5545: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 5546: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 5547: 	    }
 5548: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 5549: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 5550: 	}
 5551:     } elsif ($field eq 'answer') {
 5552: 	my $length=$scantron_config->{'Qlength'};
 5553: 	my $off=$scantron_config->{'Qoff'};
 5554: 	my $on=$scantron_config->{'Qon'};
 5555: 	my $answer=${off}x$length;
 5556: 	if ($args->{'response'} eq 'none') {
 5557: 	    &scan_data($scan_data,
 5558: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 5559: 	} else {
 5560: 	    if ($on eq 'letter') {
 5561: 		my @alphabet=('A'..'Z');
 5562: 		$answer=$alphabet[$args->{'response'}];
 5563: 	    } elsif ($on eq 'number') {
 5564: 		$answer=$args->{'response'}+1;
 5565: 		if ($answer == 10) { $answer = '0'; }
 5566: 	    } else {
 5567: 		substr($answer,$args->{'response'},1)=$on;
 5568: 	    }
 5569: 	    &scan_data($scan_data,
 5570: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 5571: 	}
 5572: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 5573: 	substr($line,$where-1,$length)=$answer;
 5574:     }
 5575:     return $line;
 5576: }
 5577: 
 5578: =pod
 5579: 
 5580: =item scan_data
 5581: 
 5582:     Edit or look up  an item in the scan_data hash.
 5583: 
 5584:   Arguments:
 5585:     $scan_data  - The hash (see scantron_getfile)
 5586:     $key        - shorthand of the key to edit (actual key is
 5587:                   scantronfilename_key).
 5588:     $data        - New value of the hash entry.
 5589:     $delete      - If true, the entry is removed from the hash.
 5590: 
 5591:   Returns:
 5592:     The new value of the hash table field (undefined if deleted).
 5593: 
 5594: =cut
 5595: 
 5596: 
 5597: sub scan_data {
 5598:     my ($scan_data,$key,$value,$delete)=@_;
 5599:     my $filename=$env{'form.scantron_selectfile'};
 5600:     if (defined($value)) {
 5601: 	$scan_data->{$filename.'_'.$key} = $value;
 5602:     }
 5603:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 5604:     return $scan_data->{$filename.'_'.$key};
 5605: }
 5606: 
 5607: # ----- These first few routines are general use routines.----
 5608: 
 5609: # Return the number of occurences of a pattern in a string.
 5610: 
 5611: sub occurence_count {
 5612:     my ($string, $pattern) = @_;
 5613: 
 5614:     my @matches = ($string =~ /$pattern/g);
 5615: 
 5616:     return scalar(@matches);
 5617: }
 5618: 
 5619: 
 5620: # Take a string known to have digits and convert all the
 5621: # digits into letters in the range J,A..I.
 5622: 
 5623: sub digits_to_letters {
 5624:     my ($input) = @_;
 5625: 
 5626:     my @alphabet = ('J', 'A'..'I');
 5627: 
 5628:     my @input    = split(//, $input);
 5629:     my $output ='';
 5630:     for (my $i = 0; $i < scalar(@input); $i++) {
 5631: 	if ($input[$i] =~ /\d/) {
 5632: 	    $output .= $alphabet[$input[$i]];
 5633: 	} else {
 5634: 	    $output .= $input[$i];
 5635: 	}
 5636:     }
 5637:     return $output;
 5638: }
 5639: 
 5640: =pod 
 5641: 
 5642: =item scantron_parse_scanline
 5643: 
 5644:   Decodes a scanline from the selected scantron file
 5645: 
 5646:  Arguments:
 5647:     line             - The text of the scantron file line to process
 5648:     whichline        - Line number
 5649:     scantron_config  - Hash describing the format of the scantron lines.
 5650:     scan_data        - Hash of extra information about the scanline
 5651:                        (see scantron_getfile for more information)
 5652:     just_header      - True if should not process question answers but only
 5653:                        the stuff to the left of the answers.
 5654:  Returns:
 5655:    Hash containing the result of parsing the scanline
 5656: 
 5657:    Keys are all proceeded by the string 'scantron.'
 5658: 
 5659:        CODE    - the CODE in use for this scanline
 5660:        useCODE - 1 if the CODE is invalid but it usage has been forced
 5661:                  by the operator
 5662:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 5663:                             CODEs were selected, but the usage has been
 5664:                             forced by the operator
 5665:        ID  - student/employee ID
 5666:        PaperID - if used, the ID number printed on the sheet when the 
 5667:                  paper was scanned
 5668:        FirstName - first name from the sheet
 5669:        LastName  - last name from the sheet
 5670: 
 5671:      if just_header was not true these key may also exist
 5672: 
 5673:        missingerror - a list of bubble ranges that are considered to be answers
 5674:                       to a single question that don't have any bubbles filled in.
 5675:                       Of the form questionnumber:firstbubblenumber:count.
 5676:        doubleerror  - a list of bubble ranges that are considered to be answers
 5677:                       to a single question that have more than one bubble filled in.
 5678:                       Of the form questionnumber::firstbubblenumber:count
 5679:    
 5680:                 In the above, count is the number of bubble responses in the
 5681:                 input line needed to represent the possible answers to the question.
 5682:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 5683:                 per line would have count = 2.
 5684: 
 5685:        maxquest     - the number of the last bubble line that was parsed
 5686: 
 5687:        (<number> starts at 1)
 5688:        <number>.answer - zero or more letters representing the selected
 5689:                          letters from the scanline for the bubble line 
 5690:                          <number>.
 5691:                          if blank there was either no bubble or there where
 5692:                          multiple bubbles, (consult the keys missingerror and
 5693:                          doubleerror if this is an error condition)
 5694: 
 5695: =cut
 5696: 
 5697: sub scantron_parse_scanline {
 5698:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
 5699: 
 5700:     my %record;
 5701:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 5702:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 5703:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
 5704:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 5705: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 5706: 	if ($$scantron_config{'CODElocation'} < 0 ||
 5707: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 5708: 	    $$scantron_config{'CODElocation'} eq 'number') {
 5709: 	    $record{'scantron.CODE'}=substr($data,
 5710: 					    $$scantron_config{'CODEstart'}-1,
 5711: 					    $$scantron_config{'CODElength'});
 5712: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 5713: 		$record{'scantron.useCODE'}=1;
 5714: 	    }
 5715: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 5716: 		$record{'scantron.CODE_ignore_dup'}=1;
 5717: 	    }
 5718: 	} else {
 5719: 	    #FIXME interpret first N questions
 5720: 	}
 5721:     }
 5722:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 5723: 				  $$scantron_config{'IDlength'});
 5724:     $record{'scantron.PaperID'}=
 5725: 	substr($data,$$scantron_config{'PaperID'}-1,
 5726: 	       $$scantron_config{'PaperIDlength'});
 5727:     $record{'scantron.FirstName'}=
 5728: 	substr($data,$$scantron_config{'FirstName'}-1,
 5729: 	       $$scantron_config{'FirstNamelength'});
 5730:     $record{'scantron.LastName'}=
 5731: 	substr($data,$$scantron_config{'LastName'}-1,
 5732: 	       $$scantron_config{'LastNamelength'});
 5733:     if ($just_header) { return \%record; }
 5734: 
 5735:     my @alphabet=('A'..'Z');
 5736:     my $questnum=0;
 5737:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 5738: 
 5739:     chomp($questions);		# Get rid of any trailing \n.
 5740:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 5741:     while (length($questions)) {
 5742: 	my $answers_needed = $bubble_lines_per_response{$questnum};
 5743:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 5744:                              || 1;
 5745:         $questnum++;
 5746:         my $quest_id = $questnum;
 5747:         my $currentquest = substr($questions,0,$answer_length);
 5748:         $questions       = substr($questions,$answer_length);
 5749:         if (length($currentquest) < $answer_length) { next; }
 5750: 
 5751:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
 5752:             my $subquestnum = 1;
 5753:             my $subquestions = $currentquest;
 5754:             my @subanswers_needed = 
 5755:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
 5756:             foreach my $subans (@subanswers_needed) {
 5757:                 my $subans_length =
 5758:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 5759:                 my $currsubquest = substr($subquestions,0,$subans_length);
 5760:                 $subquestions   = substr($subquestions,$subans_length);
 5761:                 $quest_id = "$questnum.$subquestnum";
 5762:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 5763:                     ($$scantron_config{'Qon'} eq 'number')) {
 5764:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 5765:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 5766:                         \@alphabet,\%record,$scantron_config,$scan_data);
 5767:                 } else {
 5768:                     $ansnum = &scantron_validator_positional($ansnum,
 5769:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
 5770:                 }
 5771:                 $subquestnum ++;
 5772:             }
 5773:         } else {
 5774:             if (($$scantron_config{'Qon'} eq 'letter') ||
 5775:                 ($$scantron_config{'Qon'} eq 'number')) {
 5776:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 5777:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5778:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5779:             } else {
 5780:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 5781:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5782:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5783:             }
 5784:         }
 5785:     }
 5786:     $record{'scantron.maxquest'}=$questnum;
 5787:     return \%record;
 5788: }
 5789: 
 5790: sub scantron_validator_lettnum {
 5791:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 5792:         $alphabet,$record,$scantron_config,$scan_data) = @_;
 5793: 
 5794:     # Qon 'letter' implies for each slot in currquest we have:
 5795:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 5796:     #    about anything else (esp. a value of Qoff) for missing
 5797:     #    bubbles.
 5798:     #
 5799:     # Qon 'number' implies each slot gives a digit that indexes the
 5800:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 5801:     #    and * or ? for double bubbles on a single line.
 5802:     #
 5803: 
 5804:     my $matchon;
 5805:     if ($$scantron_config{'Qon'} eq 'letter') {
 5806:         $matchon = '[A-Z]';
 5807:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 5808:         $matchon = '\d';
 5809:     }
 5810:     my $occurrences = 0;
 5811:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5812:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5813:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5814:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5815:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5816:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5817:         my @singlelines = split('',$currquest);
 5818:         foreach my $entry (@singlelines) {
 5819:             $occurrences = &occurence_count($entry,$matchon);
 5820:             if ($occurrences > 1) {
 5821:                 last;
 5822:             }
 5823:         } 
 5824:     } else {
 5825:         $occurrences = &occurence_count($currquest,$matchon); 
 5826:     }
 5827:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 5828:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5829:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5830:             my $bubble = substr($currquest,$ans,1);
 5831:             if ($bubble =~ /$matchon/ ) {
 5832:                 if ($$scantron_config{'Qon'} eq 'number') {
 5833:                     if ($bubble == 0) {
 5834:                         $bubble = 10; 
 5835:                     }
 5836:                     $record->{"scantron.$ansnum.answer"} = 
 5837:                         $alphabet->[$bubble-1];
 5838:                 } else {
 5839:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 5840:                 }
 5841:             } else {
 5842:                 $record->{"scantron.$ansnum.answer"}='';
 5843:             }
 5844:             $ansnum++;
 5845:         }
 5846:     } elsif (!defined($currquest)
 5847:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 5848:             || (&occurence_count($currquest,$matchon) == 0)) {
 5849:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5850:             $record->{"scantron.$ansnum.answer"}='';
 5851:             $ansnum++;
 5852:         }
 5853:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5854:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 5855:         }
 5856:     } else {
 5857:         if ($$scantron_config{'Qon'} eq 'number') {
 5858:             $currquest = &digits_to_letters($currquest);            
 5859:         }
 5860:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5861:             my $bubble = substr($currquest,$ans,1);
 5862:             $record->{"scantron.$ansnum.answer"} = $bubble;
 5863:             $ansnum++;
 5864:         }
 5865:     }
 5866:     return $ansnum;
 5867: }
 5868: 
 5869: sub scantron_validator_positional {
 5870:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 5871:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
 5872: 
 5873:     # Otherwise there's a positional notation;
 5874:     # each bubble line requires Qlength items, and there are filled in
 5875:     # bubbles for each case where there 'Qon' characters.
 5876:     #
 5877: 
 5878:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 5879: 
 5880:     # If the split only gives us one element.. the full length of the
 5881:     # answer string, no bubbles are filled in:
 5882: 
 5883:     if ($answers_needed eq '') {
 5884:         return;
 5885:     }
 5886: 
 5887:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 5888:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5889:             $record->{"scantron.$ansnum.answer"}='';
 5890:             $ansnum++;
 5891:         }
 5892:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5893:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 5894:         }
 5895:     } elsif (scalar(@array) == 2) {
 5896:         my $location = length($array[0]);
 5897:         my $line_num = int($location / $$scantron_config{'Qlength'});
 5898:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 5899:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5900:             if ($ans eq $line_num) {
 5901:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 5902:             } else {
 5903:                 $record->{"scantron.$ansnum.answer"} = ' ';
 5904:             }
 5905:             $ansnum++;
 5906:          }
 5907:     } else {
 5908:         #  If there's more than one instance of a bubble character
 5909:         #  That's a double bubble; with positional notation we can
 5910:         #  record all the bubbles filled in as well as the
 5911:         #  fact this response consists of multiple bubbles.
 5912:         #
 5913:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5914:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5915:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5916:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5917:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5918:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5919:             my $doubleerror = 0;
 5920:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 5921:                    (!$doubleerror)) {
 5922:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 5923:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 5924:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 5925:                if (length(@currarray) > 2) {
 5926:                    $doubleerror = 1;
 5927:                } 
 5928:             }
 5929:             if ($doubleerror) {
 5930:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5931:             }
 5932:         } else {
 5933:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5934:         }
 5935:         my $item = $ansnum;
 5936:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5937:             $record->{"scantron.$item.answer"} = '';
 5938:             $item ++;
 5939:         }
 5940: 
 5941:         my @ans=@array;
 5942:         my $i=0;
 5943:         my $increment = 0;
 5944:         while ($#ans) {
 5945:             $i+=length($ans[0]) + $increment;
 5946:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 5947:             my $bubble = $i%$$scantron_config{'Qlength'};
 5948:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 5949:             shift(@ans);
 5950:             $increment = 1;
 5951:         }
 5952:         $ansnum += $answers_needed;
 5953:     }
 5954:     return $ansnum;
 5955: }
 5956: 
 5957: =pod
 5958: 
 5959: =item scantron_add_delay
 5960: 
 5961:    Adds an error message that occurred during the grading phase to a
 5962:    queue of messages to be shown after grading pass is complete
 5963: 
 5964:  Arguments:
 5965:    $delayqueue  - arrary ref of hash ref of error messages
 5966:    $scanline    - the scanline that caused the error
 5967:    $errormesage - the error message
 5968:    $errorcode   - a numeric code for the error
 5969: 
 5970:  Side Effects:
 5971:    updates the $delayqueue to have a new hash ref of the error
 5972: 
 5973: =cut
 5974: 
 5975: sub scantron_add_delay {
 5976:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 5977:     push(@$delayqueue,
 5978: 	 {'line' => $scanline, 'emsg' => $errormessage,
 5979: 	  'ecode' => $errorcode }
 5980: 	 );
 5981: }
 5982: 
 5983: =pod
 5984: 
 5985: =item scantron_find_student
 5986: 
 5987:    Finds the username for the current scanline
 5988: 
 5989:   Arguments:
 5990:    $scantron_record - hash result from scantron_parse_scanline
 5991:    $scan_data       - hash of correction information 
 5992:                       (see &scantron_getfile() form more information)
 5993:    $idmap           - hash from &username_to_idmap()
 5994:    $line            - number of current scanline
 5995:  
 5996:   Returns:
 5997:    Either 'username:domain' or undef if unknown
 5998: 
 5999: =cut
 6000: 
 6001: sub scantron_find_student {
 6002:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 6003:     my $scanID=$$scantron_record{'scantron.ID'};
 6004:     if ($scanID =~ /^\s*$/) {
 6005:  	return &scan_data($scan_data,"$line.user");
 6006:     }
 6007:     foreach my $id (keys(%$idmap)) {
 6008:  	if (lc($id) eq lc($scanID)) {
 6009:  	    return $$idmap{$id};
 6010:  	}
 6011:     }
 6012:     return undef;
 6013: }
 6014: 
 6015: =pod
 6016: 
 6017: =item scantron_filter
 6018: 
 6019:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 6020:    hidden resources was selected
 6021: 
 6022: =cut
 6023: 
 6024: sub scantron_filter {
 6025:     my ($curres)=@_;
 6026: 
 6027:     if (ref($curres) && $curres->is_problem()) {
 6028: 	# if the user has asked to not have either hidden
 6029: 	# or 'randomout' controlled resources to be graded
 6030: 	# don't include them
 6031: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6032: 	    && $curres->randomout) {
 6033: 	    return 0;
 6034: 	}
 6035: 	return 1;
 6036:     }
 6037:     return 0;
 6038: }
 6039: 
 6040: =pod
 6041: 
 6042: =item scantron_process_corrections
 6043: 
 6044:    Gets correction information out of submitted form data and corrects
 6045:    the scanline
 6046: 
 6047: =cut
 6048: 
 6049: sub scantron_process_corrections {
 6050:     my ($r) = @_;
 6051:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6052:     my ($scanlines,$scan_data)=&scantron_getfile();
 6053:     my $classlist=&Apache::loncoursedata::get_classlist();
 6054:     my $which=$env{'form.scantron_line'};
 6055:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 6056:     my ($skip,$err,$errmsg);
 6057:     if ($env{'form.scantron_skip_record'}) {
 6058: 	$skip=1;
 6059:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 6060: 	my $newstudent=$env{'form.scantron_username'}.':'.
 6061: 	    $env{'form.scantron_domain'};
 6062: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 6063: 	($line,$err,$errmsg)=
 6064: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6065: 				     'ID',{'newid'=>$newid,
 6066: 				    'username'=>$env{'form.scantron_username'},
 6067: 				    'domain'=>$env{'form.scantron_domain'}});
 6068:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 6069: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 6070: 	my $newCODE;
 6071: 	my %args;
 6072: 	if      ($resolution eq 'use_unfound') {
 6073: 	    $newCODE='use_unfound';
 6074: 	} elsif ($resolution eq 'use_found') {
 6075: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 6076: 	} elsif ($resolution eq 'use_typed') {
 6077: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 6078: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 6079: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 6080: 	}
 6081: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 6082: 	    $args{'CODE_ignore_dup'}=1;
 6083: 	}
 6084: 	$args{'CODE'}=$newCODE;
 6085: 	($line,$err,$errmsg)=
 6086: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6087: 				     'CODE',\%args);
 6088:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 6089: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 6090: 	    ($line,$err,$errmsg)=
 6091: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 6092: 					 $which,'answer',
 6093: 					 { 'question'=>$question,
 6094: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 6095:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 6096: 	    if ($err) { last; }
 6097: 	}
 6098:     }
 6099:     if ($err) {
 6100: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
 6101:     } else {
 6102: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 6103: 	&scantron_putfile($scanlines,$scan_data);
 6104:     }
 6105: }
 6106: 
 6107: =pod
 6108: 
 6109: =item reset_skipping_status
 6110: 
 6111:    Forgets the current set of remember skipped scanlines (and thus
 6112:    reverts back to considering all lines in the
 6113:    scantron_skipped_<filename> file)
 6114: 
 6115: =cut
 6116: 
 6117: sub reset_skipping_status {
 6118:     my ($scanlines,$scan_data)=&scantron_getfile();
 6119:     &scan_data($scan_data,'remember_skipping',undef,1);
 6120:     &scantron_putfile(undef,$scan_data);
 6121: }
 6122: 
 6123: =pod
 6124: 
 6125: =item start_skipping
 6126: 
 6127:    Marks a scanline to be skipped. 
 6128: 
 6129: =cut
 6130: 
 6131: sub start_skipping {
 6132:     my ($scan_data,$i)=@_;
 6133:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6134:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 6135: 	$remembered{$i}=2;
 6136:     } else {
 6137: 	$remembered{$i}=1;
 6138:     }
 6139:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 6140: }
 6141: 
 6142: =pod
 6143: 
 6144: =item should_be_skipped
 6145: 
 6146:    Checks whether a scanline should be skipped.
 6147: 
 6148: =cut
 6149: 
 6150: sub should_be_skipped {
 6151:     my ($scanlines,$scan_data,$i)=@_;
 6152:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 6153: 	# not redoing old skips
 6154: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 6155: 	return 0;
 6156:     }
 6157:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6158: 
 6159:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 6160: 	return 0;
 6161:     }
 6162:     return 1;
 6163: }
 6164: 
 6165: =pod
 6166: 
 6167: =item remember_current_skipped
 6168: 
 6169:    Discovers what scanlines are in the scantron_skipped_<filename>
 6170:    file and remembers them into scan_data for later use.
 6171: 
 6172: =cut
 6173: 
 6174: sub remember_current_skipped {
 6175:     my ($scanlines,$scan_data)=&scantron_getfile();
 6176:     my %to_remember;
 6177:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6178: 	if ($scanlines->{'skipped'}[$i]) {
 6179: 	    $to_remember{$i}=1;
 6180: 	}
 6181:     }
 6182: 
 6183:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 6184:     &scantron_putfile(undef,$scan_data);
 6185: }
 6186: 
 6187: =pod
 6188: 
 6189: =item check_for_error
 6190: 
 6191:     Checks if there was an error when attempting to remove a specific
 6192:     scantron_.. bubblesheet data file. Prints out an error if
 6193:     something went wrong.
 6194: 
 6195: =cut
 6196: 
 6197: sub check_for_error {
 6198:     my ($r,$result)=@_;
 6199:     if ($result ne 'ok' && $result ne 'not_found' ) {
 6200: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 6201:     }
 6202: }
 6203: 
 6204: =pod
 6205: 
 6206: =item scantron_warning_screen
 6207: 
 6208:    Interstitial screen to make sure the operator has selected the
 6209:    correct options before we start the validation phase.
 6210: 
 6211: =cut
 6212: 
 6213: sub scantron_warning_screen {
 6214:     my ($button_text,$symb)=@_;
 6215:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 6216:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6217:     my $CODElist;
 6218:     if ($scantron_config{'CODElocation'} &&
 6219: 	$scantron_config{'CODEstart'} &&
 6220: 	$scantron_config{'CODElength'}) {
 6221: 	$CODElist=$env{'form.scantron_CODElist'};
 6222: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
 6223: 	$CODElist=
 6224: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 6225: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 6226:     }
 6227:     my $lastbubblepoints;
 6228:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 6229:         $lastbubblepoints =
 6230:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
 6231:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
 6232:     }
 6233:     return ('
 6234: <p>
 6235: <span class="LC_warning">
 6236: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
 6237: </p>
 6238: <table>
 6239: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 6240: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 6241: '.$CODElist.$lastbubblepoints.'
 6242: </table>
 6243: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'<br />
 6244: '.&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>
 6245: 
 6246: <br />
 6247: ');
 6248: }
 6249: 
 6250: =pod
 6251: 
 6252: =item scantron_do_warning
 6253: 
 6254:    Check if the operator has picked something for all required
 6255:    fields. Error out if something is missing.
 6256: 
 6257: =cut
 6258: 
 6259: sub scantron_do_warning {
 6260:     my ($r,$symb)=@_;
 6261:     if (!$symb) {return '';}
 6262:     my $default_form_data=&defaultFormData($symb);
 6263:     $r->print(&scantron_form_start().$default_form_data);
 6264:     if ( $env{'form.selectpage'} eq '' ||
 6265: 	 $env{'form.scantron_selectfile'} eq '' ||
 6266: 	 $env{'form.scantron_format'} eq '' ) {
 6267: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
 6268: 	if ( $env{'form.selectpage'} eq '') {
 6269: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 6270: 	} 
 6271: 	if ( $env{'form.scantron_selectfile'} eq '') {
 6272: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected a file that contains the student's response data.").'</span></p>');
 6273: 	} 
 6274: 	if ( $env{'form.scantron_format'} eq '') {
 6275: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected the format of the student's response data.").'</span></p>');
 6276: 	} 
 6277:     } else {
 6278: 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
 6279:         my $bubbledbyhand=&hand_bubble_option();
 6280: 	$r->print('
 6281: '.$warning.$bubbledbyhand.'
 6282: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 6283: <input type="hidden" name="command" value="scantron_validate" />
 6284: ');
 6285:     }
 6286:     $r->print("</form><br />");
 6287:     return '';
 6288: }
 6289: 
 6290: =pod
 6291: 
 6292: =item scantron_form_start
 6293: 
 6294:     html hidden input for remembering all selected grading options
 6295: 
 6296: =cut
 6297: 
 6298: sub scantron_form_start {
 6299:     my ($max_bubble)=@_;
 6300:     my $result= <<SCANTRONFORM;
 6301: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 6302:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 6303:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 6304:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 6305:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 6306:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 6307:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 6308:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 6309:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 6310:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 6311: SCANTRONFORM
 6312: 
 6313:   my $line = 0;
 6314:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 6315:        my $chunk =
 6316: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 6317:        $chunk .=
 6318: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 6319:        $chunk .= 
 6320:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 6321:        $chunk .=
 6322:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 6323:        $result .= $chunk;
 6324:        $line++;
 6325:    }
 6326:     return $result;
 6327: }
 6328: 
 6329: =pod
 6330: 
 6331: =item scantron_validate_file
 6332: 
 6333:     Dispatch routine for doing validation of a bubblesheet data file.
 6334: 
 6335:     Also processes any necessary information resets that need to
 6336:     occur before validation begins (ignore previous corrections,
 6337:     restarting the skipped records processing)
 6338: 
 6339: =cut
 6340: 
 6341: sub scantron_validate_file {
 6342:     my ($r,$symb) = @_;
 6343:     if (!$symb) {return '';}
 6344:     my $default_form_data=&defaultFormData($symb);
 6345:     
 6346:     # do the detection of only doing skipped records first befroe we delete
 6347:     # them when doing the corrections reset
 6348:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 6349: 	&reset_skipping_status();
 6350:     }
 6351:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 6352: 	&remember_current_skipped();
 6353: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 6354:     }
 6355: 
 6356:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 6357: 	&check_for_error($r,&scantron_remove_file('corrected'));
 6358: 	&check_for_error($r,&scantron_remove_file('skipped'));
 6359: 	&check_for_error($r,&scantron_remove_scan_data());
 6360: 	$env{'form.scantron_options_ignore'}='done';
 6361:     }
 6362: 
 6363:     if ($env{'form.scantron_corrections'}) {
 6364: 	&scantron_process_corrections($r);
 6365:     }
 6366:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 6367:     #get the student pick code ready
 6368:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 6369:     my $nav_error;
 6370:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6371:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 6372:     if ($nav_error) {
 6373:         $r->print(&navmap_errormsg());
 6374:         return '';
 6375:     }
 6376:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 6377:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 6378:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
 6379:     }
 6380:     $r->print($result);
 6381:     
 6382:     my @validate_phases=( 'sequence',
 6383: 			  'ID',
 6384: 			  'CODE',
 6385: 			  'doublebubble',
 6386: 			  'missingbubbles');
 6387:     if (!$env{'form.validatepass'}) {
 6388: 	$env{'form.validatepass'} = 0;
 6389:     }
 6390:     my $currentphase=$env{'form.validatepass'};
 6391: 
 6392: 
 6393:     my $stop=0;
 6394:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 6395: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 6396: 	$r->rflush();
 6397: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 6398: 	{
 6399: 	    no strict 'refs';
 6400: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 6401: 	}
 6402:     }
 6403:     if (!$stop) {
 6404: 	my $warning=&scantron_warning_screen('Start Grading',$symb);
 6405: 	$r->print(&mt('Validation process complete.').'<br />'.
 6406:                   $warning.
 6407:                   &mt('Perform verification for each student after storage of submissions?').
 6408:                   '&nbsp;<span class="LC_nobreak"><label>'.
 6409:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 6410:                   ('&nbsp;'x3).'<label>'.
 6411:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 6412:                   '</label></span><br />'.
 6413:                   &mt('Grading will take longer if you use verification.').'<br />'.
 6414:                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
 6415:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 6416:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 6417:     } else {
 6418: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 6419: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 6420:     }
 6421:     if ($stop) {
 6422: 	if ($validate_phases[$currentphase] eq 'sequence') {
 6423: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 6424: 	    $r->print(' '.&mt('this error').' <br />');
 6425: 
 6426: 	    $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>');
 6427: 	} else {
 6428:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 6429: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 6430:             } else {
 6431:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 6432:             }
 6433: 	    $r->print(' '.&mt('using corrected info').' <br />');
 6434: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 6435: 	    $r->print(" ".&mt("this scanline saving it for later."));
 6436: 	}
 6437:     }
 6438:     $r->print(" </form><br />");
 6439:     return '';
 6440: }
 6441: 
 6442: 
 6443: =pod
 6444: 
 6445: =item scantron_remove_file
 6446: 
 6447:    Removes the requested bubblesheet data file, makes sure that
 6448:    scantron_original_<filename> is never removed
 6449: 
 6450: 
 6451: =cut
 6452: 
 6453: sub scantron_remove_file {
 6454:     my ($which)=@_;
 6455:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6456:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6457:     my $file='scantron_';
 6458:     if ($which eq 'corrected' || $which eq 'skipped') {
 6459: 	$file.=$which.'_';
 6460:     } else {
 6461: 	return 'refused';
 6462:     }
 6463:     $file.=$env{'form.scantron_selectfile'};
 6464:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 6465: }
 6466: 
 6467: 
 6468: =pod
 6469: 
 6470: =item scantron_remove_scan_data
 6471: 
 6472:    Removes all scan_data correction for the requested bubblesheet
 6473:    data file.  (In the case that both the are doing skipped records we need
 6474:    to remember the old skipped lines for the time being so that element
 6475:    persists for a while.)
 6476: 
 6477: =cut
 6478: 
 6479: sub scantron_remove_scan_data {
 6480:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6481:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6482:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 6483:     my @todelete;
 6484:     my $filename=$env{'form.scantron_selectfile'};
 6485:     foreach my $key (@keys) {
 6486: 	if ($key=~/^\Q$filename\E_/) {
 6487: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 6488: 		$key=~/remember_skipping/) {
 6489: 		next;
 6490: 	    }
 6491: 	    push(@todelete,$key);
 6492: 	}
 6493:     }
 6494:     my $result;
 6495:     if (@todelete) {
 6496: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 6497: 				       \@todelete,$cdom,$cname);
 6498:     } else {
 6499: 	$result = 'ok';
 6500:     }
 6501:     return $result;
 6502: }
 6503: 
 6504: 
 6505: =pod
 6506: 
 6507: =item scantron_getfile
 6508: 
 6509:     Fetches the requested bubblesheet data file (all 3 versions), and
 6510:     the scan_data hash
 6511:   
 6512:   Arguments:
 6513:     None
 6514: 
 6515:   Returns:
 6516:     2 hash references
 6517: 
 6518:      - first one has 
 6519:          orig      -
 6520:          corrected -
 6521:          skipped   -  each of which points to an array ref of the specified
 6522:                       file broken up into individual lines
 6523:          count     - number of scanlines
 6524:  
 6525:      - second is the scan_data hash possible keys are
 6526:        ($number refers to scanline numbered $number and thus the key affects
 6527:         only that scanline
 6528:         $bubline refers to the specific bubble line element and the aspects
 6529:         refers to that specific bubble line element)
 6530: 
 6531:        $number.user - username:domain to use
 6532:        $number.CODE_ignore_dup 
 6533:                     - ignore the duplicate CODE error 
 6534:        $number.useCODE
 6535:                     - use the CODE in the scanline as is
 6536:        $number.no_bubble.$bubline
 6537:                     - it is valid that there is no bubbled in bubble
 6538:                       at $number $bubline
 6539:        remember_skipping
 6540:                     - a frozen hash containing keys of $number and values
 6541:                       of either 
 6542:                         1 - we are on a 'do skipped records pass' and plan
 6543:                             on processing this line
 6544:                         2 - we are on a 'do skipped records pass' and this
 6545:                             scanline has been marked to skip yet again
 6546: 
 6547: =cut
 6548: 
 6549: sub scantron_getfile {
 6550:     #FIXME really would prefer a scantron directory
 6551:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6552:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6553:     my $lines;
 6554:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6555: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 6556:     my %scanlines;
 6557:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 6558:     my $temp=$scanlines{'orig'};
 6559:     $scanlines{'count'}=$#$temp;
 6560: 
 6561:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6562: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 6563:     if ($lines eq '-1') {
 6564: 	$scanlines{'corrected'}=[];
 6565:     } else {
 6566: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 6567:     }
 6568:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6569: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 6570:     if ($lines eq '-1') {
 6571: 	$scanlines{'skipped'}=[];
 6572:     } else {
 6573: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 6574:     }
 6575:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 6576:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 6577:     my %scan_data = @tmp;
 6578:     return (\%scanlines,\%scan_data);
 6579: }
 6580: 
 6581: =pod
 6582: 
 6583: =item lonnet_putfile
 6584: 
 6585:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 6586: 
 6587:  Arguments:
 6588:    $contents - data to store
 6589:    $filename - filename to store $contents into
 6590: 
 6591:  Returns:
 6592:    result value from &Apache::lonnet::finishuserfileupload
 6593: 
 6594: =cut
 6595: 
 6596: sub lonnet_putfile {
 6597:     my ($contents,$filename)=@_;
 6598:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6599:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6600:     $env{'form.sillywaytopassafilearound'}=$contents;
 6601:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 6602: 
 6603: }
 6604: 
 6605: =pod
 6606: 
 6607: =item scantron_putfile
 6608: 
 6609:     Stores the current version of the bubblesheet data files, and the
 6610:     scan_data hash. (Does not modify the original version only the
 6611:     corrected and skipped versions.
 6612: 
 6613:  Arguments:
 6614:     $scanlines - hash ref that looks like the first return value from
 6615:                  &scantron_getfile()
 6616:     $scan_data - hash ref that looks like the second return value from
 6617:                  &scantron_getfile()
 6618: 
 6619: =cut
 6620: 
 6621: sub scantron_putfile {
 6622:     my ($scanlines,$scan_data) = @_;
 6623:     #FIXME really would prefer a scantron directory
 6624:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6625:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6626:     if ($scanlines) {
 6627: 	my $prefix='scantron_';
 6628: # no need to update orig, shouldn't change
 6629: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 6630: #		    $env{'form.scantron_selectfile'});
 6631: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 6632: 			$prefix.'corrected_'.
 6633: 			$env{'form.scantron_selectfile'});
 6634: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 6635: 			$prefix.'skipped_'.
 6636: 			$env{'form.scantron_selectfile'});
 6637:     }
 6638:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 6639: }
 6640: 
 6641: =pod
 6642: 
 6643: =item scantron_get_line
 6644: 
 6645:    Returns the correct version of the scanline
 6646: 
 6647:  Arguments:
 6648:     $scanlines - hash ref that looks like the first return value from
 6649:                  &scantron_getfile()
 6650:     $scan_data - hash ref that looks like the second return value from
 6651:                  &scantron_getfile()
 6652:     $i         - number of the requested line (starts at 0)
 6653: 
 6654:  Returns:
 6655:    A scanline, (either the original or the corrected one if it
 6656:    exists), or undef if the requested scanline should be
 6657:    skipped. (Either because it's an skipped scanline, or it's an
 6658:    unskipped scanline and we are not doing a 'do skipped scanlines'
 6659:    pass.
 6660: 
 6661: =cut
 6662: 
 6663: sub scantron_get_line {
 6664:     my ($scanlines,$scan_data,$i)=@_;
 6665:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 6666:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 6667:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 6668:     return $scanlines->{'orig'}[$i]; 
 6669: }
 6670: 
 6671: =pod
 6672: 
 6673: =item scantron_todo_count
 6674: 
 6675:     Counts the number of scanlines that need processing.
 6676: 
 6677:  Arguments:
 6678:     $scanlines - hash ref that looks like the first return value from
 6679:                  &scantron_getfile()
 6680:     $scan_data - hash ref that looks like the second return value from
 6681:                  &scantron_getfile()
 6682: 
 6683:  Returns:
 6684:     $count - number of scanlines to process
 6685: 
 6686: =cut
 6687: 
 6688: sub get_todo_count {
 6689:     my ($scanlines,$scan_data)=@_;
 6690:     my $count=0;
 6691:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6692: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6693: 	if ($line=~/^[\s\cz]*$/) { next; }
 6694: 	$count++;
 6695:     }
 6696:     return $count;
 6697: }
 6698: 
 6699: =pod
 6700: 
 6701: =item scantron_put_line
 6702: 
 6703:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
 6704:     data file.
 6705: 
 6706:  Arguments:
 6707:     $scanlines - hash ref that looks like the first return value from
 6708:                  &scantron_getfile()
 6709:     $scan_data - hash ref that looks like the second return value from
 6710:                  &scantron_getfile()
 6711:     $i         - line number to update
 6712:     $newline   - contents of the updated scanline
 6713:     $skip      - if true make the line for skipping and update the
 6714:                  'skipped' file
 6715: 
 6716: =cut
 6717: 
 6718: sub scantron_put_line {
 6719:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 6720:     if ($skip) {
 6721: 	$scanlines->{'skipped'}[$i]=$newline;
 6722: 	&start_skipping($scan_data,$i);
 6723: 	return;
 6724:     }
 6725:     $scanlines->{'corrected'}[$i]=$newline;
 6726: }
 6727: 
 6728: =pod
 6729: 
 6730: =item scantron_clear_skip
 6731: 
 6732:    Remove a line from the 'skipped' file
 6733: 
 6734:  Arguments:
 6735:     $scanlines - hash ref that looks like the first return value from
 6736:                  &scantron_getfile()
 6737:     $scan_data - hash ref that looks like the second return value from
 6738:                  &scantron_getfile()
 6739:     $i         - line number to update
 6740: 
 6741: =cut
 6742: 
 6743: sub scantron_clear_skip {
 6744:     my ($scanlines,$scan_data,$i)=@_;
 6745:     if (exists($scanlines->{'skipped'}[$i])) {
 6746: 	undef($scanlines->{'skipped'}[$i]);
 6747: 	return 1;
 6748:     }
 6749:     return 0;
 6750: }
 6751: 
 6752: =pod
 6753: 
 6754: =item scantron_filter_not_exam
 6755: 
 6756:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 6757:    filter out resources that are not marked as 'exam' mode
 6758: 
 6759: =cut
 6760: 
 6761: sub scantron_filter_not_exam {
 6762:     my ($curres)=@_;
 6763:     
 6764:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 6765: 	# if the user has asked to not have either hidden
 6766: 	# or 'randomout' controlled resources to be graded
 6767: 	# don't include them
 6768: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6769: 	    && $curres->randomout) {
 6770: 	    return 0;
 6771: 	}
 6772: 	return 1;
 6773:     }
 6774:     return 0;
 6775: }
 6776: 
 6777: =pod
 6778: 
 6779: =item scantron_validate_sequence
 6780: 
 6781:     Validates the selected sequence, checking for resource that are
 6782:     not set to exam mode.
 6783: 
 6784: =cut
 6785: 
 6786: sub scantron_validate_sequence {
 6787:     my ($r,$currentphase) = @_;
 6788: 
 6789:     my $navmap=Apache::lonnavmaps::navmap->new();
 6790:     unless (ref($navmap)) {
 6791:         $r->print(&navmap_errormsg());
 6792:         return (1,$currentphase);
 6793:     }
 6794:     my (undef,undef,$sequence)=
 6795: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 6796: 
 6797:     my $map=$navmap->getResourceByUrl($sequence);
 6798: 
 6799:     $r->print('<input type="hidden" name="validate_sequence_exam"
 6800:                                     value="ignore" />');
 6801:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 6802: 	my @resources=
 6803: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 6804: 	if (@resources) {
 6805: 	    $r->print("<p>".&mt('Some resources in the sequence currently are not set to exam mode. Grading these resources currently may not work correctly.')."</p>");
 6806: 	    return (1,$currentphase);
 6807: 	}
 6808:     }
 6809: 
 6810:     return (0,$currentphase+1);
 6811: }
 6812: 
 6813: 
 6814: 
 6815: sub scantron_validate_ID {
 6816:     my ($r,$currentphase) = @_;
 6817:     
 6818:     #get student info
 6819:     my $classlist=&Apache::loncoursedata::get_classlist();
 6820:     my %idmap=&username_to_idmap($classlist);
 6821: 
 6822:     #get scantron line setup
 6823:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6824:     my ($scanlines,$scan_data)=&scantron_getfile();
 6825: 
 6826:     my $nav_error;
 6827:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
 6828:     if ($nav_error) {
 6829:         $r->print(&navmap_errormsg());
 6830:         return(1,$currentphase);
 6831:     }
 6832: 
 6833:     my %found=('ids'=>{},'usernames'=>{});
 6834:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6835: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6836: 	if ($line=~/^[\s\cz]*$/) { next; }
 6837: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 6838: 						 $scan_data);
 6839: 	my $id=$$scan_record{'scantron.ID'};
 6840: 	my $found;
 6841: 	foreach my $checkid (keys(%idmap)) {
 6842: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 6843: 	}
 6844: 	if ($found) {
 6845: 	    my $username=$idmap{$found};
 6846: 	    if ($found{'ids'}{$found}) {
 6847: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6848: 					 $line,'duplicateID',$found);
 6849: 		return(1,$currentphase);
 6850: 	    } elsif ($found{'usernames'}{$username}) {
 6851: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6852: 					 $line,'duplicateID',$username);
 6853: 		return(1,$currentphase);
 6854: 	    }
 6855: 	    #FIXME store away line we previously saw the ID on to use above
 6856: 	    $found{'ids'}{$found}++;
 6857: 	    $found{'usernames'}{$username}++;
 6858: 	} else {
 6859: 	    if ($id =~ /^\s*$/) {
 6860: 		my $username=&scan_data($scan_data,"$i.user");
 6861: 		if (defined($username) && $found{'usernames'}{$username}) {
 6862: 		    &scantron_get_correction($r,$i,$scan_record,
 6863: 					     \%scantron_config,
 6864: 					     $line,'duplicateID',$username);
 6865: 		    return(1,$currentphase);
 6866: 		} elsif (!defined($username)) {
 6867: 		    &scantron_get_correction($r,$i,$scan_record,
 6868: 					     \%scantron_config,
 6869: 					     $line,'incorrectID');
 6870: 		    return(1,$currentphase);
 6871: 		}
 6872: 		$found{'usernames'}{$username}++;
 6873: 	    } else {
 6874: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6875: 					 $line,'incorrectID');
 6876: 		return(1,$currentphase);
 6877: 	    }
 6878: 	}
 6879:     }
 6880: 
 6881:     return (0,$currentphase+1);
 6882: }
 6883: 
 6884: 
 6885: sub scantron_get_correction {
 6886:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
 6887: #FIXME in the case of a duplicated ID the previous line, probably need
 6888: #to show both the current line and the previous one and allow skipping
 6889: #the previous one or the current one
 6890: 
 6891:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 6892:         $r->print(
 6893:             '<p class="LC_warning">'
 6894:            .&mt('An error was detected ([_1]) for PaperID [_2]',
 6895:                 "<b>$error</b>",
 6896:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
 6897:            ."</p> \n");
 6898:     } else {
 6899:         $r->print(
 6900:             '<p class="LC_warning">'
 6901:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
 6902:                 "<b>$error</b>", $i, "<pre>$line</pre>")
 6903:            ."</p> \n");
 6904:     }
 6905:     my $message =
 6906:         '<p>'
 6907:        .&mt('The ID on the form is [_1]',
 6908:             "<tt>$$scan_record{'scantron.ID'}</tt>")
 6909:        .'<br />'
 6910:        .&mt('The name on the paper is [_1], [_2]',
 6911:             $$scan_record{'scantron.LastName'},
 6912:             $$scan_record{'scantron.FirstName'})
 6913:        .'</p>';
 6914: 
 6915:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 6916:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 6917:                            # Array populated for doublebubble or
 6918:     my @lines_to_correct;  # missingbubble errors to build javascript
 6919:                            # to validate radio button checking   
 6920: 
 6921:     if ($error =~ /ID$/) {
 6922: 	if ($error eq 'incorrectID') {
 6923:             $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
 6924: 		      "</p>\n");
 6925: 	} elsif ($error eq 'duplicateID') {
 6926:             $r->print('<p class="LC_warning">'.&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 6927: 	}
 6928: 	$r->print($message);
 6929: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6930: 	$r->print("\n<ul><li> ");
 6931: 	#FIXME it would be nice if this sent back the user ID and
 6932: 	#could do partial userID matches
 6933: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 6934: 				       'scantron_username','scantron_domain'));
 6935: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 6936: 	$r->print("\n@".
 6937: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 6938: 
 6939: 	$r->print('</li>');
 6940:     } elsif ($error =~ /CODE$/) {
 6941: 	if ($error eq 'incorrectCODE') {
 6942: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 6943: 	} elsif ($error eq 'duplicateCODE') {
 6944: 	    $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");
 6945: 	}
 6946: 	$r->print("<p>".&mt('The CODE on the form is [_1]',
 6947: 			    "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
 6948:                  ."</p>\n");
 6949: 	$r->print($message);
 6950: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
 6951: 	$r->print("\n<br /> ");
 6952: 	my $i=0;
 6953: 	if ($error eq 'incorrectCODE' 
 6954: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 6955: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 6956: 	    if ($closest > 0) {
 6957: 		foreach my $testcode (@{$closest}) {
 6958: 		    my $checked='';
 6959: 		    if (!$i) { $checked=' checked="checked"'; }
 6960: 		    $r->print("
 6961:    <label>
 6962:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
 6963:        ".&mt("Use the similar CODE [_1] instead.",
 6964: 	    "<b><tt>".$testcode."</tt></b>")."
 6965:     </label>
 6966:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 6967: 		    $r->print("\n<br />");
 6968: 		    $i++;
 6969: 		}
 6970: 	    }
 6971: 	}
 6972: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 6973: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
 6974: 	    $r->print("
 6975:     <label>
 6976:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
 6977:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
 6978: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 6979:     </label>");
 6980: 	    $r->print("\n<br />");
 6981: 	}
 6982: 
 6983: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
 6984: function change_radio(field) {
 6985:     var slct=document.scantronupload.scantron_CODE_resolution;
 6986:     var i;
 6987:     for (i=0;i<slct.length;i++) {
 6988:         if (slct[i].value==field) { slct[i].checked=true; }
 6989:     }
 6990: }
 6991: ENDSCRIPT
 6992: 	my $href="/adm/pickcode?".
 6993: 	   "form=".&escape("scantronupload").
 6994: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 6995: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 6996: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 6997: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 6998: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 6999: 	    $r->print("
 7000:     <label>
 7001:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 7002:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 7003: 	     "<a target='_blank' href='$href'>","</a>")."
 7004:     </label> 
 7005:     ".&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\')" />'));
 7006: 	    $r->print("\n<br />");
 7007: 	}
 7008: 	$r->print("
 7009:     <label>
 7010:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 7011:        ".&mt("Use [_1] as the CODE.",
 7012: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 7013: 	$r->print("\n<br /><br />");
 7014:     } elsif ($error eq 'doublebubble') {
 7015: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 7016: 
 7017: 	# The form field scantron_questions is acutally a list of line numbers.
 7018: 	# represented by this form so:
 7019: 
 7020: 	my $line_list = &questions_to_line_list($arg);
 7021: 
 7022: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7023: 		  $line_list.'" />');
 7024: 	$r->print($message);
 7025: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 7026: 	foreach my $question (@{$arg}) {
 7027: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7028:                                                    $scan_record, $error);
 7029:             push(@lines_to_correct,@linenums);
 7030: 	}
 7031:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7032:     } elsif ($error eq 'missingbubble') {
 7033: 	$r->print('<p class="LC_warning">'.&mt("There have been [_1]no[_2] bubbles scanned for some question(s)",'<b>','</b>')."</p>\n");
 7034: 	$r->print($message);
 7035: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 7036: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 7037: 
 7038: 	# The form field scantron_questions is actually a list of line numbers not
 7039: 	# a list of question numbers. Therefore:
 7040: 	#
 7041: 	
 7042: 	my $line_list = &questions_to_line_list($arg);
 7043: 
 7044: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7045: 		  $line_list.'" />');
 7046: 	foreach my $question (@{$arg}) {
 7047: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7048:                                                    $scan_record, $error);
 7049:             push(@lines_to_correct,@linenums);
 7050: 	}
 7051:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7052:     } else {
 7053: 	$r->print("\n<ul>");
 7054:     }
 7055:     $r->print("\n</li></ul>");
 7056: }
 7057: 
 7058: sub verify_bubbles_checked {
 7059:     my (@ansnums) = @_;
 7060:     my $ansnumstr = join('","',@ansnums);
 7061:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 7062:     my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
 7063: function verify_bubble_radio(form) {
 7064:     var ansnumArray = new Array ("$ansnumstr");
 7065:     var need_bubble_count = 0;
 7066:     for (var i=0; i<ansnumArray.length; i++) {
 7067:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 7068:             var bubble_picked = 0; 
 7069:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 7070:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 7071:                     bubble_picked = 1;
 7072:                 }
 7073:             }
 7074:             if (bubble_picked == 0) {
 7075:                 need_bubble_count ++;
 7076:             }
 7077:         }
 7078:     }
 7079:     if (need_bubble_count) {
 7080:         alert("$warning");
 7081:         return;
 7082:     }
 7083:     form.submit(); 
 7084: }
 7085: ENDSCRIPT
 7086:     return $output;
 7087: }
 7088: 
 7089: =pod
 7090: 
 7091: =item  questions_to_line_list
 7092: 
 7093: Converts a list of questions into a string of comma separated
 7094: line numbers in the answer sheet used by the questions.  This is
 7095: used to fill in the scantron_questions form field.
 7096: 
 7097:   Arguments:
 7098:      questions    - Reference to an array of questions.
 7099: 
 7100: =cut
 7101: 
 7102: 
 7103: sub questions_to_line_list {
 7104:     my ($questions) = @_;
 7105:     my @lines;
 7106: 
 7107:     foreach my $item (@{$questions}) {
 7108:         my $question = $item;
 7109:         my ($first,$count,$last);
 7110:         if ($item =~ /^(\d+)\.(\d+)$/) {
 7111:             $question = $1;
 7112:             my $subquestion = $2;
 7113:             $first = $first_bubble_line{$question-1} + 1;
 7114:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7115:             my $subcount = 1;
 7116:             while ($subcount<$subquestion) {
 7117:                 $first += $subans[$subcount-1];
 7118:                 $subcount ++;
 7119:             }
 7120:             $count = $subans[$subquestion-1];
 7121:         } else {
 7122: 	    $first   = $first_bubble_line{$question-1} + 1;
 7123: 	    $count   = $bubble_lines_per_response{$question-1};
 7124:         }
 7125:         $last = $first+$count-1;
 7126:         push(@lines, ($first..$last));
 7127:     }
 7128:     return join(',', @lines);
 7129: }
 7130: 
 7131: =pod 
 7132: 
 7133: =item prompt_for_corrections
 7134: 
 7135: Prompts for a potentially multiline correction to the
 7136: user's bubbling (factors out common code from scantron_get_correction
 7137: for multi and missing bubble cases).
 7138: 
 7139:  Arguments:
 7140:    $r           - Apache request object.
 7141:    $question    - The question number to prompt for.
 7142:    $scan_config - The scantron file configuration hash.
 7143:    $scan_record - Reference to the hash that has the the parsed scanlines.
 7144:    $error       - Type of error
 7145: 
 7146:  Implicit inputs:
 7147:    %bubble_lines_per_response   - Starting line numbers for each question.
 7148:                                   Numbered from 0 (but question numbers are from
 7149:                                   1.
 7150:    %first_bubble_line           - Starting bubble line for each question.
 7151:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 7152:                                   type problems render as separate sub-questions, 
 7153:                                   in exam mode. This hash contains a 
 7154:                                   comma-separated list of the lines per 
 7155:                                   sub-question.
 7156:    %responsetype_per_response   - essayresponse, formularesponse,
 7157:                                   stringresponse, imageresponse, reactionresponse,
 7158:                                   and organicresponse type problem parts can have
 7159:                                   multiple lines per response if the weight
 7160:                                   assigned exceeds 10.  In this case, only
 7161:                                   one bubble per line is permitted, but more 
 7162:                                   than one line might contain bubbles, e.g.
 7163:                                   bubbling of: line 1 - J, line 2 - J, 
 7164:                                   line 3 - B would assign 22 points.  
 7165: 
 7166: =cut
 7167: 
 7168: sub prompt_for_corrections {
 7169:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
 7170:     my ($current_line,$lines);
 7171:     my @linenums;
 7172:     my $questionnum = $question;
 7173:     if ($question =~ /^(\d+)\.(\d+)$/) {
 7174:         $question = $1;
 7175:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7176:         my $subquestion = $2;
 7177:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7178:         my $subcount = 1;
 7179:         while ($subcount<$subquestion) {
 7180:             $current_line += $subans[$subcount-1];
 7181:             $subcount ++;
 7182:         }
 7183:         $lines = $subans[$subquestion-1];
 7184:     } else {
 7185:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7186:         $lines        = $bubble_lines_per_response{$question-1};
 7187:     }
 7188:     if ($lines > 1) {
 7189:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 7190:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
 7191:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
 7192:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
 7193:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
 7194:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
 7195:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
 7196:             $r->print(&mt("Although this particular question type requires handgrading, the instructions for this question in the exam directed students to leave [quant,_1,line] blank on their bubblesheets.",$lines).'<br /><br />'.&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.').'<br />'.&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.').'<br />'.&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.").'<br /><br />');
 7197:         } else {
 7198:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 7199:         }
 7200:     }
 7201:     for (my $i =0; $i < $lines; $i++) {
 7202:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 7203: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
 7204: 	        		  $questionnum,$error,split('', $selected));
 7205:         push(@linenums,$current_line);
 7206: 	$current_line++;
 7207:     }
 7208:     if ($lines > 1) {
 7209: 	$r->print("<hr /><br />");
 7210:     }
 7211:     return @linenums;
 7212: }
 7213: 
 7214: =pod
 7215: 
 7216: =item scantron_bubble_selector
 7217:   
 7218:    Generates the html radiobuttons to correct a single bubble line
 7219:    possibly showing the existing the selected bubbles if known
 7220: 
 7221:  Arguments:
 7222:     $r           - Apache request object
 7223:     $scan_config - hash from &get_scantron_config()
 7224:     $line        - Number of the line being displayed.
 7225:     $questionnum - Question number (may include subquestion)
 7226:     $error       - Type of error.
 7227:     @selected    - Array of bubbles picked on this line.
 7228: 
 7229: =cut
 7230: 
 7231: sub scantron_bubble_selector {
 7232:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 7233:     my $max=$$scan_config{'Qlength'};
 7234: 
 7235:     my $scmode=$$scan_config{'Qon'};
 7236:     if ($scmode eq 'number' || $scmode eq 'letter') { 
 7237:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
 7238:             ($$scan_config{'BubblesPerRow'} > 0)) {
 7239:             $max=$$scan_config{'BubblesPerRow'};
 7240:             if (($scmode eq 'number') && ($max > 10)) {
 7241:                 $max = 10;
 7242:             } elsif (($scmode eq 'letter') && $max > 26) {
 7243:                 $max = 26;
 7244:             }
 7245:         } else {
 7246:             $max = 10;
 7247:         }
 7248:     }
 7249: 
 7250:     my @alphabet=('A'..'Z');
 7251:     $r->print(&Apache::loncommon::start_data_table().
 7252:               &Apache::loncommon::start_data_table_row());
 7253:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 7254:     for (my $i=0;$i<$max+1;$i++) {
 7255: 	$r->print("\n".'<td align="center">');
 7256: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 7257: 	else { $r->print('&nbsp;'); }
 7258: 	$r->print('</td>');
 7259:     }
 7260:     $r->print(&Apache::loncommon::end_data_table_row().
 7261:               &Apache::loncommon::start_data_table_row());
 7262:     for (my $i=0;$i<$max;$i++) {
 7263: 	$r->print("\n".
 7264: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 7265: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 7266:     }
 7267:     my $nobub_checked = ' ';
 7268:     if ($error eq 'missingbubble') {
 7269:         $nobub_checked = ' checked = "checked" ';
 7270:     }
 7271:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 7272: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 7273:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 7274:               $line.'" value="'.$questionnum.'" /></td>');
 7275:     $r->print(&Apache::loncommon::end_data_table_row().
 7276:               &Apache::loncommon::end_data_table());
 7277: }
 7278: 
 7279: =pod
 7280: 
 7281: =item num_matches
 7282: 
 7283:    Counts the number of characters that are the same between the two arguments.
 7284: 
 7285:  Arguments:
 7286:    $orig - CODE from the scanline
 7287:    $code - CODE to match against
 7288: 
 7289:  Returns:
 7290:    $count - integer count of the number of same characters between the
 7291:             two arguments
 7292: 
 7293: =cut
 7294: 
 7295: sub num_matches {
 7296:     my ($orig,$code) = @_;
 7297:     my @code=split(//,$code);
 7298:     my @orig=split(//,$orig);
 7299:     my $same=0;
 7300:     for (my $i=0;$i<scalar(@code);$i++) {
 7301: 	if ($code[$i] eq $orig[$i]) { $same++; }
 7302:     }
 7303:     return $same;
 7304: }
 7305: 
 7306: =pod
 7307: 
 7308: =item scantron_get_closely_matching_CODEs
 7309: 
 7310:    Cycles through all CODEs and finds the set that has the greatest
 7311:    number of same characters as the provided CODE
 7312: 
 7313:  Arguments:
 7314:    $allcodes - hash ref returned by &get_codes()
 7315:    $CODE     - CODE from the current scanline
 7316: 
 7317:  Returns:
 7318:    2 element list
 7319:     - first elements is number of how closely matching the best fit is 
 7320:       (5 means best set has 5 matching characters)
 7321:     - second element is an arrary ref containing the set of valid CODEs
 7322:       that best fit the passed in CODE
 7323: 
 7324: =cut
 7325: 
 7326: sub scantron_get_closely_matching_CODEs {
 7327:     my ($allcodes,$CODE)=@_;
 7328:     my @CODEs;
 7329:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 7330: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 7331:     }
 7332: 
 7333:     return ($#CODEs,$CODEs[-1]);
 7334: }
 7335: 
 7336: =pod
 7337: 
 7338: =item get_codes
 7339: 
 7340:    Builds a hash which has keys of all of the valid CODEs from the selected
 7341:    set of remembered CODEs.
 7342: 
 7343:  Arguments:
 7344:   $old_name - name of the set of remembered CODEs
 7345:   $cdom     - domain of the course
 7346:   $cnum     - internal course name
 7347: 
 7348:  Returns:
 7349:   %allcodes - keys are the valid CODEs, values are all 1
 7350: 
 7351: =cut
 7352: 
 7353: sub get_codes {
 7354:     my ($old_name, $cdom, $cnum) = @_;
 7355:     if (!$old_name) {
 7356: 	$old_name=$env{'form.scantron_CODElist'};
 7357:     }
 7358:     if (!$cdom) {
 7359: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 7360:     }
 7361:     if (!$cnum) {
 7362: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 7363:     }
 7364:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 7365: 				    $cdom,$cnum);
 7366:     my %allcodes;
 7367:     if ($result{"type\0$old_name"} eq 'number') {
 7368: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 7369:     } else {
 7370: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 7371:     }
 7372:     return %allcodes;
 7373: }
 7374: 
 7375: =pod
 7376: 
 7377: =item scantron_validate_CODE
 7378: 
 7379:    Validates all scanlines in the selected file to not have any
 7380:    invalid or underspecified CODEs and that none of the codes are
 7381:    duplicated if this was requested.
 7382: 
 7383: =cut
 7384: 
 7385: sub scantron_validate_CODE {
 7386:     my ($r,$currentphase) = @_;
 7387:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7388:     if ($scantron_config{'CODElocation'} &&
 7389: 	$scantron_config{'CODEstart'} &&
 7390: 	$scantron_config{'CODElength'}) {
 7391: 	if (!defined($env{'form.scantron_CODElist'})) {
 7392: 	    &FIXME_blow_up()
 7393: 	}
 7394:     } else {
 7395: 	return (0,$currentphase+1);
 7396:     }
 7397:     
 7398:     my %usedCODEs;
 7399: 
 7400:     my %allcodes=&get_codes();
 7401: 
 7402:     my $nav_error;
 7403:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
 7404:     if ($nav_error) {
 7405:         $r->print(&navmap_errormsg());
 7406:         return(1,$currentphase);
 7407:     }
 7408: 
 7409:     my ($scanlines,$scan_data)=&scantron_getfile();
 7410:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7411: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7412: 	if ($line=~/^[\s\cz]*$/) { next; }
 7413: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7414: 						 $scan_data);
 7415: 	my $CODE=$$scan_record{'scantron.CODE'};
 7416: 	my $error=0;
 7417: 	if (!&Apache::lonnet::validCODE($CODE)) {
 7418: 	    &scantron_get_correction($r,$i,$scan_record,
 7419: 				     \%scantron_config,
 7420: 				     $line,'incorrectCODE',\%allcodes);
 7421: 	    return(1,$currentphase);
 7422: 	}
 7423: 	if (%allcodes && !exists($allcodes{$CODE}) 
 7424: 	    && !$$scan_record{'scantron.useCODE'}) {
 7425: 	    &scantron_get_correction($r,$i,$scan_record,
 7426: 				     \%scantron_config,
 7427: 				     $line,'incorrectCODE',\%allcodes);
 7428: 	    return(1,$currentphase);
 7429: 	}
 7430: 	if (exists($usedCODEs{$CODE}) 
 7431: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 7432: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 7433: 	    &scantron_get_correction($r,$i,$scan_record,
 7434: 				     \%scantron_config,
 7435: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 7436: 	    return(1,$currentphase);
 7437: 	}
 7438: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 7439:     }
 7440:     return (0,$currentphase+1);
 7441: }
 7442: 
 7443: =pod
 7444: 
 7445: =item scantron_validate_doublebubble
 7446: 
 7447:    Validates all scanlines in the selected file to not have any
 7448:    bubble lines with multiple bubbles marked.
 7449: 
 7450: =cut
 7451: 
 7452: sub scantron_validate_doublebubble {
 7453:     my ($r,$currentphase) = @_;
 7454:     #get student info
 7455:     my $classlist=&Apache::loncoursedata::get_classlist();
 7456:     my %idmap=&username_to_idmap($classlist);
 7457: 
 7458:     #get scantron line setup
 7459:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7460:     my ($scanlines,$scan_data)=&scantron_getfile();
 7461:     my $nav_error;
 7462:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
 7463:     if ($nav_error) {
 7464:         $r->print(&navmap_errormsg());
 7465:         return(1,$currentphase);
 7466:     }
 7467: 
 7468:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7469: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7470: 	if ($line=~/^[\s\cz]*$/) { next; }
 7471: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7472: 						 $scan_data);
 7473: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 7474: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 7475: 				 'doublebubble',
 7476: 				 $$scan_record{'scantron.doubleerror'});
 7477:     	return (1,$currentphase);
 7478:     }
 7479:     return (0,$currentphase+1);
 7480: }
 7481: 
 7482: 
 7483: sub scantron_get_maxbubble {
 7484:     my ($nav_error,$scantron_config) = @_;
 7485:     if (defined($env{'form.scantron_maxbubble'}) &&
 7486: 	$env{'form.scantron_maxbubble'}) {
 7487: 	&restore_bubble_lines();
 7488: 	return $env{'form.scantron_maxbubble'};
 7489:     }
 7490: 
 7491:     my (undef, undef, $sequence) =
 7492: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7493: 
 7494:     my $navmap=Apache::lonnavmaps::navmap->new();
 7495:     unless (ref($navmap)) {
 7496:         if (ref($nav_error)) {
 7497:             $$nav_error = 1;
 7498:         }
 7499:         return;
 7500:     }
 7501:     my $map=$navmap->getResourceByUrl($sequence);
 7502:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7503:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
 7504: 
 7505:     &Apache::lonxml::clear_problem_counter();
 7506: 
 7507:     my $uname       = $env{'user.name'};
 7508:     my $udom        = $env{'user.domain'};
 7509:     my $cid         = $env{'request.course.id'};
 7510:     my $total_lines = 0;
 7511:     %bubble_lines_per_response = ();
 7512:     %first_bubble_line         = ();
 7513:     %subdivided_bubble_lines   = ();
 7514:     %responsetype_per_response = ();
 7515: 
 7516:     my $response_number = 0;
 7517:     my $bubble_line     = 0;
 7518:     foreach my $resource (@resources) {
 7519:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom,undef,$bubbles_per_row);
 7520:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 7521: 	    foreach my $part_id (@{$parts}) {
 7522:                 my $lines;
 7523: 
 7524: 	        # TODO - make this a persistent hash not an array.
 7525: 
 7526:                 # optionresponse, matchresponse and rankresponse type items 
 7527:                 # render as separate sub-questions in exam mode.
 7528:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 7529:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 7530:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 7531:                     my ($numbub,$numshown);
 7532:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 7533:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 7534:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 7535:                         }
 7536:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 7537:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 7538:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 7539:                         }
 7540:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 7541:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 7542:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 7543:                         }
 7544:                     }
 7545:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 7546:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 7547:                     }
 7548:                     my $bubbles_per_row =
 7549:                         &bubblesheet_bubbles_per_row($scantron_config);
 7550:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
 7551:                     if (($numbub % $bubbles_per_row) != 0) {
 7552:                         $inner_bubble_lines++;
 7553:                     }
 7554:                     for (my $i=0; $i<$numshown; $i++) {
 7555:                         $subdivided_bubble_lines{$response_number} .= 
 7556:                             $inner_bubble_lines.',';
 7557:                     }
 7558:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 7559:                     $lines = $numshown * $inner_bubble_lines;
 7560:                 } else {
 7561:                     $lines = $analysis->{"$part_id.bubble_lines"};
 7562:                 }
 7563: 
 7564:                 $first_bubble_line{$response_number} = $bubble_line;
 7565: 	        $bubble_lines_per_response{$response_number} = $lines;
 7566:                 $responsetype_per_response{$response_number} = 
 7567:                     $analysis->{$part_id.'.type'};
 7568: 	        $response_number++;
 7569: 
 7570: 	        $bubble_line +=  $lines;
 7571: 	        $total_lines +=  $lines;
 7572: 	    }
 7573:         }
 7574:     }
 7575:     &Apache::lonnet::delenv('scantron.');
 7576: 
 7577:     &save_bubble_lines();
 7578:     $env{'form.scantron_maxbubble'} =
 7579: 	$total_lines;
 7580:     return $env{'form.scantron_maxbubble'};
 7581: }
 7582: 
 7583: sub bubblesheet_bubbles_per_row {
 7584:     my ($scantron_config) = @_;
 7585:     my $bubbles_per_row;
 7586:     if (ref($scantron_config) eq 'HASH') {
 7587:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
 7588:     }
 7589:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
 7590:         $bubbles_per_row = 10;
 7591:     }
 7592:     return $bubbles_per_row;
 7593: }
 7594: 
 7595: sub scantron_validate_missingbubbles {
 7596:     my ($r,$currentphase) = @_;
 7597:     #get student info
 7598:     my $classlist=&Apache::loncoursedata::get_classlist();
 7599:     my %idmap=&username_to_idmap($classlist);
 7600: 
 7601:     #get scantron line setup
 7602:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7603:     my ($scanlines,$scan_data)=&scantron_getfile();
 7604:     my $nav_error;
 7605:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 7606:     if ($nav_error) {
 7607:         return(1,$currentphase);
 7608:     }
 7609:     if (!$max_bubble) { $max_bubble=2**31; }
 7610:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7611: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7612: 	if ($line=~/^[\s\cz]*$/) { next; }
 7613: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7614: 						 $scan_data);
 7615: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 7616: 	my @to_correct;
 7617: 	
 7618: 	# Probably here's where the error is...
 7619: 
 7620: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 7621:             my $lastbubble;
 7622:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 7623:                my $question = $1;
 7624:                my $subquestion = $2;
 7625:                if (!defined($first_bubble_line{$question -1})) { next; }
 7626:                my $first = $first_bubble_line{$question-1};
 7627:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7628:                my $subcount = 1;
 7629:                while ($subcount<$subquestion) {
 7630:                    $first += $subans[$subcount-1];
 7631:                    $subcount ++;
 7632:                }
 7633:                my $count = $subans[$subquestion-1];
 7634:                $lastbubble = $first + $count;
 7635:             } else {
 7636:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
 7637:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
 7638:             }
 7639:             if ($lastbubble > $max_bubble) { next; }
 7640: 	    push(@to_correct,$missing);
 7641: 	}
 7642: 	if (@to_correct) {
 7643: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7644: 				     $line,'missingbubble',\@to_correct);
 7645: 	    return (1,$currentphase);
 7646: 	}
 7647: 
 7648:     }
 7649:     return (0,$currentphase+1);
 7650: }
 7651: 
 7652: sub hand_bubble_option {
 7653:     my (undef, undef, $sequence) =
 7654:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 7655:     return if ($sequence eq '');
 7656:     my $navmap = Apache::lonnavmaps::navmap->new();
 7657:     unless (ref($navmap)) {
 7658:         return;
 7659:     }
 7660:     my $needs_hand_bubbles;
 7661:     my $map=$navmap->getResourceByUrl($sequence);
 7662:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7663:     foreach my $res (@resources) {
 7664:         if (ref($res)) {
 7665:             if ($res->is_problem()) {
 7666:                 my $partlist = $res->parts();
 7667:                 foreach my $part (@{ $partlist }) {
 7668:                     my @types = $res->responseType($part);
 7669:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
 7670:                         $needs_hand_bubbles = 1;
 7671:                         last;
 7672:                     }
 7673:                 }
 7674:             }
 7675:         }
 7676:     }
 7677:     if ($needs_hand_bubbles) {
 7678:         my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7679:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 7680:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
 7681:                &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 />').
 7682:                '<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;'.
 7683:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0"/>0 points</label></p>';
 7684:     }
 7685:     return;
 7686: }
 7687: 
 7688: sub scantron_process_students {
 7689:     my ($r,$symb) = @_;
 7690: 
 7691:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7692:     if (!$symb) {
 7693: 	return '';
 7694:     }
 7695:     my $default_form_data=&defaultFormData($symb);
 7696: 
 7697:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7698:     my $bubbles_per_row =
 7699:         &bubblesheet_bubbles_per_row(\%scantron_config);
 7700:     my ($scanlines,$scan_data)=&scantron_getfile();
 7701:     my $classlist=&Apache::loncoursedata::get_classlist();
 7702:     my %idmap=&username_to_idmap($classlist);
 7703:     my $navmap=Apache::lonnavmaps::navmap->new();
 7704:     unless (ref($navmap)) {
 7705:         $r->print(&navmap_errormsg());
 7706:         return '';
 7707:     }  
 7708:     my $map=$navmap->getResourceByUrl($sequence);
 7709:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7710:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
 7711:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 7712:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 7713:     my $resource_error;
 7714:     foreach my $resource (@resources) {
 7715:         my $ressymb;
 7716:         if (ref($resource)) {
 7717:             $ressymb = $resource->symb();
 7718:         } else {
 7719:             $resource_error = 1;
 7720:             last;
 7721:         }
 7722:         my ($analysis,$parts) =
 7723:             &scantron_partids_tograde($resource,$env{'request.course.id'},
 7724:                                       $env{'user.name'},$env{'user.domain'},1,$bubbles_per_row);
 7725:         $grader_partids_by_symb{$ressymb} = $parts;
 7726:         if (ref($analysis) eq 'HASH') {
 7727:             if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 7728:                 $grader_randomlists_by_symb{$ressymb} = 
 7729:                     $analysis->{'parts_withrandomlist'};
 7730:             }
 7731:         }
 7732:     }
 7733:     if ($resource_error) {
 7734:         $r->print(&navmap_errormsg());
 7735:         return '';
 7736:     }
 7737: 
 7738:     my ($uname,$udom);
 7739:     my $result= <<SCANTRONFORM;
 7740: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 7741:   <input type="hidden" name="command" value="scantron_configphase" />
 7742:   $default_form_data
 7743: SCANTRONFORM
 7744:     $r->print($result);
 7745: 
 7746:     my @delayqueue;
 7747:     my (%completedstudents,%scandata);
 7748:     
 7749:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 7750:     my $count=&get_todo_count($scanlines,$scan_data);
 7751:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 7752:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
 7753:     $r->print('<br />');
 7754:     my $start=&Time::HiRes::time();
 7755:     my $i=-1;
 7756:     my $started;
 7757: 
 7758:     my $nav_error;
 7759:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 7760:     if ($nav_error) {
 7761:         $r->print(&navmap_errormsg());
 7762:         return '';
 7763:     }
 7764: 
 7765:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 7766:     # the user and return.
 7767: 
 7768:     if ($ssi_error) {
 7769: 	$r->print("</form>");
 7770: 	&ssi_print_error($r);
 7771:         &Apache::lonnet::remove_lock($lock);
 7772: 	return '';		# Dunno why the other returns return '' rather than just returning.
 7773:     }
 7774: 
 7775:     my %lettdig = &letter_to_digits();
 7776:     my $numletts = scalar(keys(%lettdig));
 7777: 
 7778:     while ($i<$scanlines->{'count'}) {
 7779:  	($uname,$udom)=('','');
 7780:  	$i++;
 7781:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7782:  	if ($line=~/^[\s\cz]*$/) { next; }
 7783: 	if ($started) {
 7784: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
 7785: 	}
 7786: 	$started=1;
 7787:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7788:  						 $scan_data);
 7789:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 7790:  					      \%idmap,$i)) {
 7791:   	    &scantron_add_delay(\@delayqueue,$line,
 7792:  				'Unable to find a student that matches',1);
 7793:  	    next;
 7794:   	}
 7795:  	if (exists $completedstudents{$uname}) {
 7796:  	    &scantron_add_delay(\@delayqueue,$line,
 7797:  				'Student '.$uname.' has multiple sheets',2);
 7798:  	    next;
 7799:  	}
 7800:   	($uname,$udom)=split(/:/,$uname);
 7801: 
 7802:         my (%partids_by_symb,$res_error);
 7803:         foreach my $resource (@resources) {
 7804:             my $ressymb;
 7805:             if (ref($resource)) {
 7806:                 $ressymb = $resource->symb();
 7807:             } else {
 7808:                 $res_error = 1;
 7809:                 last;
 7810:             }
 7811:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 7812:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 7813:                 my ($analysis,$parts) =
 7814:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom,undef,$bubbles_per_row);
 7815:                 $partids_by_symb{$ressymb} = $parts;
 7816:             } else {
 7817:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
 7818:             }
 7819:         }
 7820: 
 7821:         if ($res_error) {
 7822:             &scantron_add_delay(\@delayqueue,$line,
 7823:                                 'An error occurred while grading student '.$uname,2);
 7824:             next;
 7825:         }
 7826: 
 7827: 	&Apache::lonxml::clear_problem_counter();
 7828:   	&Apache::lonnet::appenv($scan_record);
 7829: 
 7830: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 7831: 	    &scantron_putfile($scanlines,$scan_data);
 7832: 	}
 7833: 	
 7834:         my $scancode;
 7835:         if ((exists($scan_record->{'scantron.CODE'})) &&
 7836:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 7837:             $scancode = $scan_record->{'scantron.CODE'};
 7838:         } else {
 7839:             $scancode = '';
 7840:         }
 7841: 
 7842:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 7843:                                    \@resources,\%partids_by_symb,
 7844:                                    $bubbles_per_row) eq 'ssi_error') {
 7845:             $ssi_error = 0; # So end of handler error message does not trigger.
 7846:             $r->print("</form>");
 7847:             &ssi_print_error($r);
 7848:             &Apache::lonnet::remove_lock($lock);
 7849:             return '';      # Why return ''?  Beats me.
 7850:         }
 7851: 
 7852: 	$completedstudents{$uname}={'line'=>$line};
 7853:         if ($env{'form.verifyrecord'}) {
 7854:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 7855:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 7856:             chomp($studentdata);
 7857:             $studentdata =~ s/\r$//;
 7858:             my $studentrecord = '';
 7859:             my $counter = -1;
 7860:             foreach my $resource (@resources) {
 7861:                 my $ressymb = $resource->symb();
 7862:                 ($counter,my $recording) =
 7863:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 7864:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
 7865:                                              \%scantron_config,\%lettdig,$numletts);
 7866:                 $studentrecord .= $recording;
 7867:             }
 7868:             if ($studentrecord ne $studentdata) {
 7869:                 &Apache::lonxml::clear_problem_counter();
 7870:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 7871:                                            \@resources,\%partids_by_symb,
 7872:                                            $bubbles_per_row) eq 'ssi_error') {
 7873:                     $ssi_error = 0; # So end of handler error message does not trigger.
 7874:                     $r->print("</form>");
 7875:                     &ssi_print_error($r);
 7876:                     &Apache::lonnet::remove_lock($lock);
 7877:                     delete($completedstudents{$uname});
 7878:                     return '';
 7879:                 }
 7880:                 $counter = -1;
 7881:                 $studentrecord = '';
 7882:                 foreach my $resource (@resources) {
 7883:                     my $ressymb = $resource->symb();
 7884:                     ($counter,my $recording) =
 7885:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 7886:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 7887:                                                  \%scantron_config,\%lettdig,$numletts);
 7888:                     $studentrecord .= $recording;
 7889:                 }
 7890:                 if ($studentrecord ne $studentdata) {
 7891:                     $r->print('<p><span class="LC_warning">');
 7892:                     if ($scancode eq '') {
 7893:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
 7894:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 7895:                     } else {
 7896:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
 7897:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 7898:                     }
 7899:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 7900:                               &Apache::loncommon::start_data_table_header_row()."\n".
 7901:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 7902:                               &Apache::loncommon::end_data_table_header_row()."\n".
 7903:                               &Apache::loncommon::start_data_table_row().
 7904:                               '<td>'.&mt('Bubblesheet').'</td>'.
 7905:                               '<td><span class="LC_nobreak"><tt>'.$studentdata.'</tt></span></td>'.
 7906:                               &Apache::loncommon::end_data_table_row().
 7907:                               &Apache::loncommon::start_data_table_row().
 7908:                               '<td>'.&mt('Stored submissions').'</td>'.
 7909:                               '<td><span class="LC_nobreak"><tt>'.$studentrecord.'</tt></span></td>'."\n".
 7910:                               &Apache::loncommon::end_data_table_row().
 7911:                               &Apache::loncommon::end_data_table().'</p>');
 7912:                 } else {
 7913:                     $r->print('<br /><span class="LC_warning">'.
 7914:                              &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 />'.
 7915:                              &mt("As a consequence, this user's submission history records two tries.").
 7916:                                  '</span><br />');
 7917:                 }
 7918:             }
 7919:         }
 7920:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 7921:     } continue {
 7922: 	&Apache::lonxml::clear_problem_counter();
 7923: 	&Apache::lonnet::delenv('scantron.');
 7924:     }
 7925:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 7926:     &Apache::lonnet::remove_lock($lock);
 7927: #    my $lasttime = &Time::HiRes::time()-$start;
 7928: #    $r->print("<p>took $lasttime</p>");
 7929: 
 7930:     $r->print("</form>");
 7931:     return '';
 7932: }
 7933: 
 7934: sub graders_resources_pass {
 7935:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
 7936:         $bubbles_per_row) = @_;
 7937:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
 7938:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
 7939:         foreach my $resource (@{$resources}) {
 7940:             my $ressymb = $resource->symb();
 7941:             my ($analysis,$parts) =
 7942:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
 7943:                                           $env{'user.name'},$env{'user.domain'},1,$bubbles_per_row);
 7944:             $grader_partids_by_symb->{$ressymb} = $parts;
 7945:             if (ref($analysis) eq 'HASH') {
 7946:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 7947:                     $grader_randomlists_by_symb->{$ressymb} =
 7948:                         $analysis->{'parts_withrandomlist'};
 7949:                 }
 7950:             }
 7951:         }
 7952:     }
 7953:     return;
 7954: }
 7955: 
 7956: sub grade_student_bubbles {
 7957:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row) = @_;
 7958: # Walk folder as student here to get resources in order student sees.
 7959:     if (ref($resources) eq 'ARRAY') {
 7960:         my $count = 0;
 7961:         foreach my $resource (@{$resources}) {
 7962:             my $ressymb = $resource->symb();
 7963:             my %form = ('submitted'      => 'scantron',
 7964:                         'grade_target'   => 'grade',
 7965:                         'grade_username' => $uname,
 7966:                         'grade_domain'   => $udom,
 7967:                         'grade_courseid' => $env{'request.course.id'},
 7968:                         'grade_symb'     => $ressymb,
 7969:                         'CODE'           => $scancode
 7970:                        );
 7971:             if ($bubbles_per_row ne '') {
 7972:                 $form{'bubbles_per_row'} = $bubbles_per_row;
 7973:             }
 7974:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
 7975:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
 7976:             }
 7977:             if (ref($parts) eq 'HASH') {
 7978:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 7979:                     foreach my $part (@{$parts->{$ressymb}}) {
 7980:                         $form{'scantron_questnum_start.'.$part} =
 7981:                             1+$env{'form.scantron.first_bubble_line.'.$count};
 7982:                         $count++;
 7983:                     }
 7984:                 }
 7985:             }
 7986:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 7987:             return 'ssi_error' if ($ssi_error);
 7988:             last if (&Apache::loncommon::connection_aborted($r));
 7989:         }
 7990:     }
 7991:     return;
 7992: }
 7993: 
 7994: sub scantron_upload_scantron_data {
 7995:     my ($r,$symb)=@_;
 7996:     my $dom = $env{'request.role.domain'};
 7997:     my $domdesc = &Apache::lonnet::domain($dom,'description');
 7998:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
 7999:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 8000: 							  'domainid',
 8001: 							  'coursename',$dom);
 8002:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
 8003:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
 8004:     my $default_form_data=&defaultFormData($symb);
 8005:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
 8006:     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.");
 8007:     $r->print(&Apache::lonhtmlcommon::scripttag('
 8008:     function checkUpload(formname) {
 8009: 	if (formname.upfile.value == "") {
 8010: 	    alert("'.$nofile_alert.'");
 8011: 	    return false;
 8012: 	}
 8013:         if (formname.courseid.value == "") {
 8014:             alert("'.$nocourseid_alert.'");
 8015:             return false;
 8016:         }
 8017: 	formname.submit();
 8018:     }
 8019: 
 8020:     function ToSyllabus() {
 8021:         var cdom = '."'$dom'".';
 8022:         var cnum = document.rules.courseid.value;
 8023:         if (cdom == "" || cdom == null) {
 8024:             return;
 8025:         }
 8026:         if (cnum == "" || cnum == null) {
 8027:            return;
 8028:         }
 8029:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
 8030:                             "height=350,width=350,scrollbars=yes,menubar=no");
 8031:         return;
 8032:     }
 8033: 
 8034: '));
 8035:     $r->print('
 8036: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
 8037: 
 8038: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 8039: '.$default_form_data.
 8040:   &Apache::lonhtmlcommon::start_pick_box().
 8041:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
 8042:   '<input name="courseid" type="text" size="30" />'.$select_link.
 8043:   &Apache::lonhtmlcommon::row_closure().
 8044:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
 8045:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
 8046:   &Apache::lonhtmlcommon::row_closure().
 8047:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
 8048:   '<input name="domainid" type="hidden" />'.$domdesc.
 8049:   &Apache::lonhtmlcommon::row_closure().
 8050:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
 8051:   '<input type="file" name="upfile" size="50" />'.
 8052:   &Apache::lonhtmlcommon::row_closure(1).
 8053:   &Apache::lonhtmlcommon::end_pick_box().'<br />
 8054: 
 8055: <input name="command" value="scantronupload_save" type="hidden" />
 8056: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 8057: </form>
 8058: ');
 8059:     return '';
 8060: }
 8061: 
 8062: 
 8063: sub scantron_upload_scantron_data_save {
 8064:     my($r,$symb)=@_;
 8065:     my $doanotherupload=
 8066: 	'<br /><form action="/adm/grades" method="post">'."\n".
 8067: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 8068: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 8069: 	'</form>'."\n";
 8070:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 8071: 	!&Apache::lonnet::allowed('usc',
 8072: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 8073: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
 8074: 	unless ($symb) {
 8075: 	    $r->print($doanotherupload);
 8076: 	}
 8077: 	return '';
 8078:     }
 8079:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 8080:     my $uploadedfile;
 8081:     $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
 8082:     if (length($env{'form.upfile'}) < 2) {
 8083:         $r->print(&mt('[_1]Error:[_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.','<span class="LC_error">','</span>','<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 8084:     } else {
 8085:         my $result = 
 8086:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
 8087:                                             $env{'form.courseid'},$env{'form.domainid'});
 8088: 	if ($result =~ m{^/uploaded/}) {
 8089: 	    $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
 8090:                           '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
 8091: 			  '<span class="LC_filename">'.$result.'</span>'));
 8092:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
 8093:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
 8094:                                                        $env{'form.courseid'},$uploadedfile));
 8095: 	} else {
 8096: 	    $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
 8097:                           '<span class="LC_error">','</span>',$result,
 8098: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 8099: 	}
 8100:     }
 8101:     if ($symb) {
 8102: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
 8103:     } else {
 8104: 	$r->print($doanotherupload);
 8105:     }
 8106:     return '';
 8107: }
 8108: 
 8109: sub validate_uploaded_scantron_file {
 8110:     my ($cdom,$cname,$fname) = @_;
 8111:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
 8112:     my @lines;
 8113:     if ($scanlines ne '-1') {
 8114:         @lines=split("\n",$scanlines,-1);
 8115:     }
 8116:     my $output;
 8117:     if (@lines) {
 8118:         my (%counts,$max_match_format);
 8119:         my ($max_match_count,$max_match_pct) = (0,0);
 8120:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
 8121:         my %idmap = &username_to_idmap($classlist);
 8122:         foreach my $key (keys(%idmap)) {
 8123:             my $lckey = lc($key);
 8124:             $idmap{$lckey} = $idmap{$key};
 8125:         }
 8126:         my %unique_formats;
 8127:         my @formatlines = &get_scantronformat_file();
 8128:         foreach my $line (@formatlines) {
 8129:             chomp($line);
 8130:             my @config = split(/:/,$line);
 8131:             my $idstart = $config[5];
 8132:             my $idlength = $config[6];
 8133:             if (($idstart ne '') && ($idlength > 0)) {
 8134:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
 8135:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
 8136:                 } else {
 8137:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
 8138:                 }
 8139:             }
 8140:         }
 8141:         foreach my $key (keys(%unique_formats)) {
 8142:             my ($idstart,$idlength) = split(':',$key);
 8143:             %{$counts{$key}} = (
 8144:                                'found'   => 0,
 8145:                                'total'   => 0,
 8146:                               );
 8147:             foreach my $line (@lines) {
 8148:                 next if ($line =~ /^#/);
 8149:                 next if ($line =~ /^[\s\cz]*$/);
 8150:                 my $id = substr($line,$idstart-1,$idlength);
 8151:                 $id = lc($id);
 8152:                 if (exists($idmap{$id})) {
 8153:                     $counts{$key}{'found'} ++;
 8154:                 }
 8155:                 $counts{$key}{'total'} ++;
 8156:             }
 8157:             if ($counts{$key}{'total'}) {
 8158:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
 8159:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
 8160:                     $max_match_pct = $percent_match;
 8161:                     $max_match_format = $key;
 8162:                     $max_match_count = $counts{$key}{'total'};
 8163:                 }
 8164:             }
 8165:         }
 8166:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
 8167:             my $format_descs;
 8168:             my $numwithformat = @{$unique_formats{$max_match_format}};
 8169:             for (my $i=0; $i<$numwithformat; $i++) {
 8170:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
 8171:                 if ($i<$numwithformat-2) {
 8172:                     $format_descs .= '"<i>'.$desc.'</i>", ';
 8173:                 } elsif ($i==$numwithformat-2) {
 8174:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
 8175:                 } elsif ($i==$numwithformat-1) {
 8176:                     $format_descs .= '"<i>'.$desc.'</i>"';
 8177:                 }
 8178:             }
 8179:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
 8180:             $output .= '<br />'.&mt('Comparison of student IDs in the uploaded file with the course roster found matches for [_1] of the [_2] entries in the file (for the format defined for [_3]).','<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
 8181:                        '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
 8182:                        '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
 8183:                        '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
 8184:                                   '<i>'.$cdom.'</i>').'</li>'.
 8185:                        '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
 8186:                        '<li>'.&mt('The course roster is not up to date').'</li>'.
 8187:                        '</ul>';
 8188:         }
 8189:     } else {
 8190:         $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
 8191:     }
 8192:     return $output;
 8193: }
 8194: 
 8195: sub valid_file {
 8196:     my ($requested_file)=@_;
 8197:     foreach my $filename (sort(&scantron_filenames())) {
 8198: 	if ($requested_file eq $filename) { return 1; }
 8199:     }
 8200:     return 0;
 8201: }
 8202: 
 8203: sub scantron_download_scantron_data {
 8204:     my ($r,$symb)=@_;
 8205:     my $default_form_data=&defaultFormData($symb);
 8206:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 8207:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8208:     my $file=$env{'form.scantron_selectfile'};
 8209:     if (! &valid_file($file)) {
 8210: 	$r->print('
 8211: 	<p>
 8212: 	    '.&mt('The requested file name was invalid.').'
 8213:         </p>
 8214: ');
 8215: 	return;
 8216:     }
 8217:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 8218:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 8219:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 8220:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 8221:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 8222:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 8223:     $r->print('
 8224:     <p>
 8225: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
 8226: 	      '<a href="'.$orig.'">','</a>').'
 8227:     </p>
 8228:     <p>
 8229: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 8230: 	      '<a href="'.$corrected.'">','</a>').'
 8231:     </p>
 8232:     <p>
 8233: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 8234: 	      '<a href="'.$skipped.'">','</a>').'
 8235:     </p>
 8236: ');
 8237:     return '';
 8238: }
 8239: 
 8240: sub checkscantron_results {
 8241:     my ($r,$symb) = @_;
 8242:     if (!$symb) {return '';}
 8243:     my $cid = $env{'request.course.id'};
 8244:     my %lettdig = &letter_to_digits();
 8245:     my $numletts = scalar(keys(%lettdig));
 8246:     my $cnum = $env{'course.'.$cid.'.num'};
 8247:     my $cdom = $env{'course.'.$cid.'.domain'};
 8248:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8249:     my %record;
 8250:     my %scantron_config =
 8251:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
 8252:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8253:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
 8254:     my $classlist=&Apache::loncoursedata::get_classlist();
 8255:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 8256:     my $navmap=Apache::lonnavmaps::navmap->new();
 8257:     unless (ref($navmap)) {
 8258:         $r->print(&navmap_errormsg());
 8259:         return '';
 8260:     }
 8261:     my $map=$navmap->getResourceByUrl($sequence);
 8262:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8263:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
 8264:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,                             \%grader_randomlists_by_symb);
 8265: 
 8266:     my ($uname,$udom);
 8267:     my (%scandata,%lastname,%bylast);
 8268:     $r->print('
 8269: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 8270: 
 8271:     my @delayqueue;
 8272:     my %completedstudents;
 8273: 
 8274:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
 8275:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 8276:     my ($username,$domain,$started);
 8277:     my $nav_error;
 8278:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 8279:     if ($nav_error) {
 8280:         $r->print(&navmap_errormsg());
 8281:         return '';
 8282:     }
 8283: 
 8284:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
 8285:     my $start=&Time::HiRes::time();
 8286:     my $i=-1;
 8287: 
 8288:     while ($i<$scanlines->{'count'}) {
 8289:         ($username,$domain,$uname)=('','','');
 8290:         $i++;
 8291:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 8292:         if ($line=~/^[\s\cz]*$/) { next; }
 8293:         if ($started) {
 8294:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
 8295:         }
 8296:         $started=1;
 8297:         my $scan_record=
 8298:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 8299:                                                      $scan_data);
 8300:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
 8301:                                                               \%idmap,$i)) {
 8302:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 8303:                                 'Unable to find a student that matches',1);
 8304:             next;
 8305:         }
 8306:         if (exists $completedstudents{$uname}) {
 8307:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 8308:                                 'Student '.$uname.' has multiple sheets',2);
 8309:             next;
 8310:         }
 8311:         my $pid = $scan_record->{'scantron.ID'};
 8312:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 8313:         push(@{$bylast{$lastname{$pid}}},$pid);
 8314:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 8315:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 8316:         chomp($scandata{$pid});
 8317:         $scandata{$pid} =~ s/\r$//;
 8318:         ($username,$domain)=split(/:/,$uname);
 8319:         my $counter = -1;
 8320:         foreach my $resource (@resources) {
 8321:             my $parts;
 8322:             my $ressymb = $resource->symb();
 8323:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 8324:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 8325:                 (my $analysis,$parts) =
 8326:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$username,$domain,undef,$bubbles_per_row);
 8327:             } else {
 8328:                 $parts = $grader_partids_by_symb{$ressymb};
 8329:             }
 8330:             ($counter,my $recording) =
 8331:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
 8332:                                          $scandata{$pid},$parts,
 8333:                                          \%scantron_config,\%lettdig,$numletts);
 8334:             $record{$pid} .= $recording;
 8335:         }
 8336:     }
 8337:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 8338:     $r->print('<br />');
 8339:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 8340:     $passed = 0;
 8341:     $failed = 0;
 8342:     $numstudents = 0;
 8343:     foreach my $last (sort(keys(%bylast))) {
 8344:         if (ref($bylast{$last}) eq 'ARRAY') {
 8345:             foreach my $pid (sort(@{$bylast{$last}})) {
 8346:                 my $showscandata = $scandata{$pid};
 8347:                 my $showrecord = $record{$pid};
 8348:                 $showscandata =~ s/\s/&nbsp;/g;
 8349:                 $showrecord =~ s/\s/&nbsp;/g;
 8350:                 if ($scandata{$pid} eq $record{$pid}) {
 8351:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 8352:                     $okstudents .= '<tr class="'.$css_class.'">'.
 8353: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 8354: '</tr>'."\n".
 8355: '<tr class="'.$css_class.'">'."\n".
 8356: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
 8357:                     $passed ++;
 8358:                 } else {
 8359:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
 8360:                     $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".
 8361: '</tr>'."\n".
 8362: '<tr class="'.$css_class.'">'."\n".
 8363: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
 8364: '</tr>'."\n";
 8365:                     $failed ++;
 8366:                 }
 8367:                 $numstudents ++;
 8368:             }
 8369:         }
 8370:     }
 8371:     $r->print(
 8372:         '<p>'
 8373:        .&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).',
 8374:             '<b>',
 8375:             $numstudents,
 8376:             '</b>',
 8377:             $env{'form.scantron_maxbubble'})
 8378:        .'</p>'
 8379:     );
 8380:     $r->print('<p>'.&mt('Exact matches for <b>[quant,_1,student]</b>.',$passed).'<br />'.&mt('Discrepancies detected for <b>[quant,_1,student]</b>.',$failed).'</p>');
 8381:     if ($passed) {
 8382:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
 8383:         $r->print(&Apache::loncommon::start_data_table()."\n".
 8384:                  &Apache::loncommon::start_data_table_header_row()."\n".
 8385:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 8386:                  &Apache::loncommon::end_data_table_header_row()."\n".
 8387:                  $okstudents."\n".
 8388:                  &Apache::loncommon::end_data_table().'<br />');
 8389:     }
 8390:     if ($failed) {
 8391:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
 8392:         $r->print(&Apache::loncommon::start_data_table()."\n".
 8393:                  &Apache::loncommon::start_data_table_header_row()."\n".
 8394:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 8395:                  &Apache::loncommon::end_data_table_header_row()."\n".
 8396:                  $badstudents."\n".
 8397:                  &Apache::loncommon::end_data_table()).'<br />'.
 8398:                  &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.');  
 8399:     }
 8400:     $r->print('</form><br />');
 8401:     return;
 8402: }
 8403: 
 8404: sub verify_scantron_grading {
 8405:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
 8406:         $scantron_config,$lettdig,$numletts) = @_;
 8407:     my ($record,%expected,%startpos);
 8408:     return ($counter,$record) if (!ref($resource));
 8409:     return ($counter,$record) if (!$resource->is_problem());
 8410:     my $symb = $resource->symb();
 8411:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
 8412:     foreach my $part_id (@{$partids}) {
 8413:         $counter ++;
 8414:         $expected{$part_id} = 0;
 8415:         if ($env{"form.scantron.sub_bubblelines.$counter"}) {
 8416:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
 8417:             foreach my $item (@sub_lines) {
 8418:                 $expected{$part_id} += $item;
 8419:             }
 8420:         } else {
 8421:             $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
 8422:         }
 8423:         $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
 8424:     }
 8425:     if ($symb) {
 8426:         my %recorded;
 8427:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
 8428:         if ($returnhash{'version'}) {
 8429:             my %lasthash=();
 8430:             my $version;
 8431:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 8432:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 8433:                     $lasthash{$key}=$returnhash{$version.':'.$key};
 8434:                 }
 8435:             }
 8436:             foreach my $key (keys(%lasthash)) {
 8437:                 if ($key =~ /\.scantron$/) {
 8438:                     my $value = &unescape($lasthash{$key});
 8439:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
 8440:                     if ($value eq '') {
 8441:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
 8442:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
 8443:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8444:                             }
 8445:                         }
 8446:                     } else {
 8447:                         my @tocheck;
 8448:                         my @items = split(//,$value);
 8449:                         if (($scantron_config->{'Qon'} eq 'letter') ||
 8450:                             ($scantron_config->{'Qon'} eq 'number')) {
 8451:                             if (@items < $expected{$part_id}) {
 8452:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
 8453:                                 my @singles = split(//,$fragment);
 8454:                                 foreach my $pos (@singles) {
 8455:                                     if ($pos eq ' ') {
 8456:                                         push(@tocheck,$pos);
 8457:                                     } else {
 8458:                                         my $next = shift(@items);
 8459:                                         push(@tocheck,$next);
 8460:                                     }
 8461:                                 }
 8462:                             } else {
 8463:                                 @tocheck = @items;
 8464:                             }
 8465:                             foreach my $letter (@tocheck) {
 8466:                                 if ($scantron_config->{'Qon'} eq 'letter') {
 8467:                                     if ($letter !~ /^[A-J]$/) {
 8468:                                         $letter = $scantron_config->{'Qoff'};
 8469:                                     }
 8470:                                     $recorded{$part_id} .= $letter;
 8471:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
 8472:                                     my $digit;
 8473:                                     if ($letter !~ /^[A-J]$/) {
 8474:                                         $digit = $scantron_config->{'Qoff'};
 8475:                                     } else {
 8476:                                         $digit = $lettdig->{$letter};
 8477:                                     }
 8478:                                     $recorded{$part_id} .= $digit;
 8479:                                 }
 8480:                             }
 8481:                         } else {
 8482:                             @tocheck = @items;
 8483:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
 8484:                                 my $curr_sub = shift(@tocheck);
 8485:                                 my $digit;
 8486:                                 if ($curr_sub =~ /^[A-J]$/) {
 8487:                                     $digit = $lettdig->{$curr_sub}-1;
 8488:                                 }
 8489:                                 if ($curr_sub eq 'J') {
 8490:                                     $digit += scalar($numletts);
 8491:                                 }
 8492:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 8493:                                     if ($j == $digit) {
 8494:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
 8495:                                     } else {
 8496:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8497:                                     }
 8498:                                 }
 8499:                             }
 8500:                         }
 8501:                     }
 8502:                 }
 8503:             }
 8504:         }
 8505:         foreach my $part_id (@{$partids}) {
 8506:             if ($recorded{$part_id} eq '') {
 8507:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
 8508:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 8509:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8510:                     }
 8511:                 }
 8512:             }
 8513:             $record .= $recorded{$part_id};
 8514:         }
 8515:     }
 8516:     return ($counter,$record);
 8517: }
 8518: 
 8519: sub letter_to_digits { 
 8520:     my %lettdig = (
 8521:                     A => 1,
 8522:                     B => 2,
 8523:                     C => 3,
 8524:                     D => 4,
 8525:                     E => 5,
 8526:                     F => 6,
 8527:                     G => 7,
 8528:                     H => 8,
 8529:                     I => 9,
 8530:                     J => 0,
 8531:                   );
 8532:     return %lettdig;
 8533: }
 8534: 
 8535: 
 8536: #-------- end of section for handling grading scantron forms -------
 8537: #
 8538: #-------------------------------------------------------------------
 8539: 
 8540: #-------------------------- Menu interface -------------------------
 8541: #
 8542: #--- Href with symb and command ---
 8543: 
 8544: sub href_symb_cmd {
 8545:     my ($symb,$cmd)=@_;
 8546:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&command='.$cmd;
 8547: }
 8548: 
 8549: sub grading_menu {
 8550:     my ($request,$symb) = @_;
 8551:     if (!$symb) {return '';}
 8552: 
 8553:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 8554:                   'command'=>'individual');
 8555:     
 8556:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8557: 
 8558:     $fields{'command'}='ungraded';
 8559:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8560: 
 8561:     $fields{'command'}='table';
 8562:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8563: 
 8564:     $fields{'command'}='all_for_one';
 8565:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8566: 
 8567:     $fields{'command'}='downloadfilesselect';
 8568:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8569: 
 8570:     $fields{'command'} = 'csvform';
 8571:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8572:     
 8573:     $fields{'command'} = 'processclicker';
 8574:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8575:     
 8576:     $fields{'command'} = 'scantron_selectphase';
 8577:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8578: 
 8579:     $fields{'command'} = 'initialverifyreceipt';
 8580:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8581:     
 8582:     my @menu = ({	categorytitle=>'Hand Grading',
 8583:             items =>[
 8584:                         {	linktext => 'Select individual students to grade',
 8585:                     		url => $url1a,
 8586:                     		permission => 'F',
 8587:                     		icon => 'grade_students.png',
 8588:                     		linktitle => 'Grade current resource for a selection of students.'
 8589:                         }, 
 8590:                         {       linktext => 'Grade ungraded submissions.',
 8591:                                 url => $url1b,
 8592:                                 permission => 'F',
 8593:                                 icon => 'ungrade_sub.png',
 8594:                                 linktitle => 'Grade all submissions that have not been graded yet.'
 8595:                         },
 8596: 
 8597:                         {       linktext => 'Grading table',
 8598:                                 url => $url1c,
 8599:                                 permission => 'F',
 8600:                                 icon => 'grading_table.png',
 8601:                                 linktitle => 'Grade current resource for all students.'
 8602:                         },
 8603:                         {       linktext => 'Grade page/folder for one student',
 8604:                                 url => $url1d,
 8605:                                 permission => 'F',
 8606:                                 icon => 'grade_PageFolder.png',
 8607:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
 8608:                         },
 8609:                         {       linktext => 'Download submissions',
 8610:                                 url => $url1e,
 8611:                                 permission => 'F',
 8612:                                 icon => 'download_sub.png',
 8613:                                 linktitle => 'Download all students submissions.'
 8614:                         }]},
 8615:                          { categorytitle=>'Automated Grading',
 8616:                items =>[
 8617: 
 8618:                 	    {	linktext => 'Upload Scores',
 8619:                     		url => $url2,
 8620:                     		permission => 'F',
 8621:                     		icon => 'uploadscores.png',
 8622:                     		linktitle => 'Specify a file containing the class scores for current resource.'
 8623:                 	    },
 8624:                 	    {	linktext => 'Process Clicker',
 8625:                     		url => $url3,
 8626:                     		permission => 'F',
 8627:                     		icon => 'addClickerInfoFile.png',
 8628:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
 8629:                 	    },
 8630:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
 8631:                     		url => $url4,
 8632:                     		permission => 'F',
 8633:                     		icon => 'bubblesheet.png',
 8634:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
 8635:                 	    },
 8636:                             {   linktext => 'Verify Receipt Number',
 8637:                                 url => $url5,
 8638:                                 permission => 'F',
 8639:                                 icon => 'receipt_number.png',
 8640:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
 8641:                             }
 8642: 
 8643:                     ]
 8644:             });
 8645: 
 8646:     # Create the menu
 8647:     my $Str;
 8648:     $Str .= '<form method="post" action="" name="gradingMenu">';
 8649:     $Str .= '<input type="hidden" name="command" value="" />'.
 8650:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 8651: 
 8652:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
 8653:     return $Str;    
 8654: }
 8655: 
 8656: 
 8657: sub ungraded {
 8658:     my ($request)=@_;
 8659:     &submit_options($request);
 8660: }
 8661: 
 8662: sub submit_options_sequence {
 8663:     my ($request,$symb) = @_;
 8664:     if (!$symb) {return '';}
 8665:     &commonJSfunctions($request);
 8666:     my $result;
 8667: 
 8668:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8669:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 8670:     $result.=&selectfield(0).
 8671:             '<input type="hidden" name="command" value="pickStudentPage" />
 8672:             <div>
 8673:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 8674:             </div>
 8675:         </div>
 8676:   </form>';
 8677:     return $result;
 8678: }
 8679: 
 8680: sub submit_options_table {
 8681:     my ($request,$symb) = @_;
 8682:     if (!$symb) {return '';}
 8683:     &commonJSfunctions($request);
 8684:     my $result;
 8685: 
 8686:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8687:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 8688: 
 8689:     $result.=&selectfield(0).
 8690:             '<input type="hidden" name="command" value="viewgrades" />
 8691:             <div>
 8692:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 8693:             </div>
 8694:         </div>
 8695:   </form>';
 8696:     return $result;
 8697: }
 8698: 
 8699: sub submit_options_download {
 8700:     my ($request,$symb) = @_;
 8701:     if (!$symb) {return '';}
 8702: 
 8703:     &commonJSfunctions($request);
 8704: 
 8705:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8706:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 8707:     $result.='
 8708: <h2>
 8709:   '.&mt('Select Students for Which to Download Submissions').'
 8710: </h2>'.&selectfield(1).'
 8711:                 <input type="hidden" name="command" value="downloadfileslink" /> 
 8712:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 8713:             </div>
 8714:           </div>
 8715: 
 8716: 
 8717:   </form>';
 8718:     return $result;
 8719: }
 8720: 
 8721: #--- Displays the submissions first page -------
 8722: sub submit_options {
 8723:     my ($request,$symb) = @_;
 8724:     if (!$symb) {return '';}
 8725: 
 8726:     &commonJSfunctions($request);
 8727:     my $result;
 8728: 
 8729:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8730: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 8731:     $result.=&selectfield(1).'
 8732:                 <input type="hidden" name="command" value="submission" /> 
 8733: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
 8734:             </div>
 8735:           </div>
 8736: 
 8737: 
 8738:   </form>';
 8739:     return $result;
 8740: }
 8741: 
 8742: sub selectfield {
 8743:    my ($full)=@_;
 8744:    my %options = 
 8745:           (&Apache::lonlocal::texthash(
 8746:              'yes'       => 'with submissions',
 8747:              'queued'    => 'in grading queue',
 8748:              'graded'    => 'with ungraded submissions',
 8749:              'incorrect' => 'with incorrect submissions',
 8750:              'all'       => 'with any status'),
 8751:              'select_form_order' => ['yes','queued','graded','incorrect','all']);
 8752:    my $result='<div class="LC_columnSection">
 8753:   
 8754:     <fieldset>
 8755:       <legend>
 8756:        '.&mt('Sections').'
 8757:       </legend>
 8758:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
 8759:     </fieldset>
 8760:   
 8761:     <fieldset>
 8762:       <legend>
 8763:         '.&mt('Groups').'
 8764:       </legend>
 8765:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
 8766:     </fieldset>
 8767:   
 8768:     <fieldset>
 8769:       <legend>
 8770:         '.&mt('Access Status').'
 8771:       </legend>
 8772:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
 8773:     </fieldset>';
 8774:     if ($full) {
 8775:        $result.='
 8776:     <fieldset>
 8777:       <legend>
 8778:         '.&mt('Submission Status').'
 8779:       </legend>'.
 8780:        &Apache::loncommon::select_form('all','submitonly',\%options).
 8781:    '</fieldset>';
 8782:     }
 8783:     $result.='</div><br />';
 8784:     return $result;
 8785: }
 8786: 
 8787: sub reset_perm {
 8788:     undef(%perm);
 8789: }
 8790: 
 8791: sub init_perm {
 8792:     &reset_perm();
 8793:     foreach my $test_perm ('vgr','mgr','opa') {
 8794: 
 8795: 	my $scope = $env{'request.course.id'};
 8796: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
 8797: 
 8798: 	    $scope .= '/'.$env{'request.course.sec'};
 8799: 	    if ( $perm{$test_perm}=
 8800: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
 8801: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
 8802: 	    } else {
 8803: 		delete($perm{$test_perm});
 8804: 	    }
 8805: 	}
 8806:     }
 8807: }
 8808: 
 8809: sub gather_clicker_ids {
 8810:     my %clicker_ids;
 8811: 
 8812:     my $classlist = &Apache::loncoursedata::get_classlist();
 8813: 
 8814:     # Set up a couple variables.
 8815:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
 8816:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
 8817:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
 8818: 
 8819:     foreach my $student (keys(%$classlist)) {
 8820:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
 8821:         my $username = $classlist->{$student}->[$username_idx];
 8822:         my $domain   = $classlist->{$student}->[$domain_idx];
 8823:         my $clickers =
 8824: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
 8825:         foreach my $id (split(/\,/,$clickers)) {
 8826:             $id=~s/^[\#0]+//;
 8827:             $id=~s/[\-\:]//g;
 8828:             if (exists($clicker_ids{$id})) {
 8829: 		$clicker_ids{$id}.=','.$username.':'.$domain;
 8830:             } else {
 8831: 		$clicker_ids{$id}=$username.':'.$domain;
 8832:             }
 8833:         }
 8834:     }
 8835:     return %clicker_ids;
 8836: }
 8837: 
 8838: sub gather_adv_clicker_ids {
 8839:     my %clicker_ids;
 8840:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 8841:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8842:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
 8843:     foreach my $element (sort(keys(%coursepersonnel))) {
 8844:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
 8845:             my ($puname,$pudom)=split(/\:/,$person);
 8846:             my $clickers =
 8847: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
 8848:             foreach my $id (split(/\,/,$clickers)) {
 8849: 		$id=~s/^[\#0]+//;
 8850:                 $id=~s/[\-\:]//g;
 8851: 		if (exists($clicker_ids{$id})) {
 8852: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
 8853: 		} else {
 8854: 		    $clicker_ids{$id}=$puname.':'.$pudom;
 8855: 		}
 8856:             }
 8857:         }
 8858:     }
 8859:     return %clicker_ids;
 8860: }
 8861: 
 8862: sub clicker_grading_parameters {
 8863:     return ('gradingmechanism' => 'scalar',
 8864:             'upfiletype' => 'scalar',
 8865:             'specificid' => 'scalar',
 8866:             'pcorrect' => 'scalar',
 8867:             'pincorrect' => 'scalar');
 8868: }
 8869: 
 8870: sub process_clicker {
 8871:     my ($r,$symb)=@_;
 8872:     if (!$symb) {return '';}
 8873:     my $result=&checkforfile_js();
 8874:     $result.=&Apache::loncommon::start_data_table().
 8875:              &Apache::loncommon::start_data_table_header_row().
 8876:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
 8877:              &Apache::loncommon::end_data_table_header_row().
 8878:              &Apache::loncommon::start_data_table_row()."<td>\n";
 8879: # Attempt to restore parameters from last session, set defaults if not present
 8880:     my %Saveable_Parameters=&clicker_grading_parameters();
 8881:     &Apache::loncommon::restore_course_settings('grades_clicker',
 8882:                                                  \%Saveable_Parameters);
 8883:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
 8884:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
 8885:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
 8886:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
 8887: 
 8888:     my %checked;
 8889:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
 8890:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
 8891:           $checked{$gradingmechanism}=' checked="checked"';
 8892:        }
 8893:     }
 8894: 
 8895:     my $upload=&mt("Evaluate File");
 8896:     my $type=&mt("Type");
 8897:     my $attendance=&mt("Award points just for participation");
 8898:     my $personnel=&mt("Correctness determined from response by course personnel");
 8899:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
 8900:     my $given=&mt("Correctness determined from given list of answers").' '.
 8901:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
 8902:     my $pcorrect=&mt("Percentage points for correct solution");
 8903:     my $pincorrect=&mt("Percentage points for incorrect solution");
 8904:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
 8905: 						   {'iclicker' => 'i>clicker',
 8906:                                                     'interwrite' => 'interwrite PRS',
 8907:                                                     'turning' => 'Turning Technologies'});
 8908:     $symb = &Apache::lonenc::check_encrypt($symb);
 8909:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
 8910: function sanitycheck() {
 8911: // Accept only integer percentages
 8912:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
 8913:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
 8914: // Find out grading choice
 8915:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8916:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
 8917:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
 8918:       }
 8919:    }
 8920: // By default, new choice equals user selection
 8921:    newgradingchoice=gradingchoice;
 8922: // Not good to give more points for false answers than correct ones
 8923:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
 8924:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
 8925:    }
 8926: // If new choice is attendance only, and old choice was correctness-based, restore defaults
 8927:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
 8928:       document.forms.gradesupload.pcorrect.value=100;
 8929:       document.forms.gradesupload.pincorrect.value=100;
 8930:    }
 8931: // If the values are different, cannot be attendance only
 8932:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
 8933:        (gradingchoice=='attendance')) {
 8934:        newgradingchoice='personnel';
 8935:    }
 8936: // Change grading choice to new one
 8937:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8938:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
 8939:          document.forms.gradesupload.gradingmechanism[i].checked=true;
 8940:       } else {
 8941:          document.forms.gradesupload.gradingmechanism[i].checked=false;
 8942:       }
 8943:    }
 8944: // Remember the old state
 8945:    document.forms.gradesupload.waschecked.value=newgradingchoice;
 8946: }
 8947: ENDUPFORM
 8948:     $result.= <<ENDUPFORM;
 8949: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 8950: <input type="hidden" name="symb" value="$symb" />
 8951: <input type="hidden" name="command" value="processclickerfile" />
 8952: <input type="file" name="upfile" size="50" />
 8953: <br /><label>$type: $selectform</label>
 8954: ENDUPFORM
 8955:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
 8956:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
 8957:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
 8958: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
 8959: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
 8960: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
 8961: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
 8962: <br />&nbsp;&nbsp;&nbsp;
 8963: <input type="text" name="givenanswer" size="50" />
 8964: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
 8965: ENDGRADINGFORM
 8966:          $result.='</td>'.&Apache::loncommon::end_data_table_row().
 8967:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
 8968:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
 8969: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
 8970: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 8971: </form>'
 8972: ENDPERCFORM
 8973:     $result.='</td>'.
 8974:              &Apache::loncommon::end_data_table_row().
 8975:              &Apache::loncommon::end_data_table();
 8976:     return $result;
 8977: }
 8978: 
 8979: sub process_clicker_file {
 8980:     my ($r,$symb)=@_;
 8981:     if (!$symb) {return '';}
 8982: 
 8983:     my %Saveable_Parameters=&clicker_grading_parameters();
 8984:     &Apache::loncommon::store_course_settings('grades_clicker',
 8985:                                               \%Saveable_Parameters);
 8986:     my $result='';
 8987:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
 8988: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
 8989: 	return $result;
 8990:     }
 8991:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
 8992:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
 8993:         return $result;
 8994:     }
 8995:     my $foundgiven=0;
 8996:     if ($env{'form.gradingmechanism'} eq 'given') {
 8997:         $env{'form.givenanswer'}=~s/^\s*//gs;
 8998:         $env{'form.givenanswer'}=~s/\s*$//gs;
 8999:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
 9000:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
 9001:         my @answers=split(/\,/,$env{'form.givenanswer'});
 9002:         $foundgiven=$#answers+1;
 9003:     }
 9004:     my %clicker_ids=&gather_clicker_ids();
 9005:     my %correct_ids;
 9006:     if ($env{'form.gradingmechanism'} eq 'personnel') {
 9007: 	%correct_ids=&gather_adv_clicker_ids();
 9008:     }
 9009:     if ($env{'form.gradingmechanism'} eq 'specific') {
 9010: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
 9011: 	   $correct_id=~tr/a-z/A-Z/;
 9012: 	   $correct_id=~s/\s//gs;
 9013: 	   $correct_id=~s/^[\#0]+//;
 9014:            $correct_id=~s/[\-\:]//g;
 9015:            if ($correct_id) {
 9016: 	      $correct_ids{$correct_id}='specified';
 9017:            }
 9018:         }
 9019:     }
 9020:     if ($env{'form.gradingmechanism'} eq 'attendance') {
 9021: 	$result.=&mt('Score based on attendance only');
 9022:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
 9023:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
 9024:     } else {
 9025: 	my $number=0;
 9026: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
 9027: 	foreach my $id (sort(keys(%correct_ids))) {
 9028: 	    $result.='<br /><tt>'.$id.'</tt> - ';
 9029: 	    if ($correct_ids{$id} eq 'specified') {
 9030: 		$result.=&mt('specified');
 9031: 	    } else {
 9032: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
 9033: 		$result.=&Apache::loncommon::plainname($uname,$udom);
 9034: 	    }
 9035: 	    $number++;
 9036: 	}
 9037:         $result.="</p>\n";
 9038: 	if ($number==0) {
 9039: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
 9040: 	    return $result;
 9041: 	}
 9042:     }
 9043:     if (length($env{'form.upfile'}) < 2) {
 9044:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
 9045: 		     '<span class="LC_error">',
 9046: 		     '</span>',
 9047: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
 9048:         return $result;
 9049:     }
 9050: 
 9051: # Were able to get all the info needed, now analyze the file
 9052: 
 9053:     $result.=&Apache::loncommon::studentbrowser_javascript();
 9054:     $symb = &Apache::lonenc::check_encrypt($symb);
 9055:     $result.=&Apache::loncommon::start_data_table().
 9056:              &Apache::loncommon::start_data_table_header_row().
 9057:              '<th>'.&mt('Evaluate clicker file').'</th>'.
 9058:              &Apache::loncommon::end_data_table_header_row().
 9059:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
 9060: <td>
 9061: <form method="post" action="/adm/grades" name="clickeranalysis">
 9062: <input type="hidden" name="symb" value="$symb" />
 9063: <input type="hidden" name="command" value="assignclickergrades" />
 9064: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
 9065: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
 9066: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
 9067: ENDHEADER
 9068:     if ($env{'form.gradingmechanism'} eq 'given') {
 9069:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
 9070:     } 
 9071:     my %responses;
 9072:     my @questiontitles;
 9073:     my $errormsg='';
 9074:     my $number=0;
 9075:     if ($env{'form.upfiletype'} eq 'iclicker') {
 9076: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
 9077:     }
 9078:     if ($env{'form.upfiletype'} eq 'interwrite') {
 9079:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
 9080:     }
 9081:     if ($env{'form.upfiletype'} eq 'turning') {
 9082:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
 9083:     }
 9084:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
 9085:              '<input type="hidden" name="number" value="'.$number.'" />'.
 9086:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
 9087:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
 9088:              '<br />';
 9089:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
 9090:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
 9091:        return $result;
 9092:     } 
 9093: # Remember Question Titles
 9094: # FIXME: Possibly need delimiter other than ":"
 9095:     for (my $i=0;$i<$number;$i++) {
 9096:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
 9097:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
 9098:     }
 9099:     my $correct_count=0;
 9100:     my $student_count=0;
 9101:     my $unknown_count=0;
 9102: # Match answers with usernames
 9103: # FIXME: Possibly need delimiter other than ":"
 9104:     foreach my $id (keys(%responses)) {
 9105:        if ($correct_ids{$id}) {
 9106:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
 9107:           $correct_count++;
 9108:        } elsif ($clicker_ids{$id}) {
 9109:           if ($clicker_ids{$id}=~/\,/) {
 9110: # More than one user with the same clicker!
 9111:              $result.="</td>".&Apache::loncommon::end_data_table_row().
 9112:                            &Apache::loncommon::start_data_table_row()."<td>".
 9113:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
 9114:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 9115:                            "<select name='multi".$id."'>";
 9116:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
 9117:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
 9118:              }
 9119:              $result.='</select>';
 9120:              $unknown_count++;
 9121:           } else {
 9122: # Good: found one and only one user with the right clicker
 9123:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
 9124:              $student_count++;
 9125:           }
 9126:        } else {
 9127:           $result.="</td>".&Apache::loncommon::end_data_table_row().
 9128:                            &Apache::loncommon::start_data_table_row()."<td>".
 9129:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
 9130:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 9131:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
 9132:                    "\n".&mt("Domain").": ".
 9133:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
 9134:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,0,$id);
 9135:           $unknown_count++;
 9136:        }
 9137:     }
 9138:     $result.='<hr />'.
 9139:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
 9140:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
 9141:        if ($correct_count==0) {
 9142:           $errormsg.="Found no correct answers answers for grading!";
 9143:        } elsif ($correct_count>1) {
 9144:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
 9145:        }
 9146:     }
 9147:     if ($number<1) {
 9148:        $errormsg.="Found no questions.";
 9149:     }
 9150:     if ($errormsg) {
 9151:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
 9152:     } else {
 9153:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
 9154:     }
 9155:     $result.='</form></td>'.
 9156:              &Apache::loncommon::end_data_table_row().
 9157:              &Apache::loncommon::end_data_table();
 9158:     return $result;
 9159: }
 9160: 
 9161: sub iclicker_eval {
 9162:     my ($questiontitles,$responses)=@_;
 9163:     my $number=0;
 9164:     my $errormsg='';
 9165:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 9166:         my %components=&Apache::loncommon::record_sep($line);
 9167:         my @entries=map {$components{$_}} (sort(keys(%components)));
 9168: 	if ($entries[0] eq 'Question') {
 9169: 	    for (my $i=3;$i<$#entries;$i+=6) {
 9170: 		$$questiontitles[$number]=$entries[$i];
 9171: 		$number++;
 9172: 	    }
 9173: 	}
 9174: 	if ($entries[0]=~/^\#/) {
 9175: 	    my $id=$entries[0];
 9176: 	    my @idresponses;
 9177: 	    $id=~s/^[\#0]+//;
 9178: 	    for (my $i=0;$i<$number;$i++) {
 9179: 		my $idx=3+$i*6;
 9180:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
 9181: 		push(@idresponses,$entries[$idx]);
 9182: 	    }
 9183: 	    $$responses{$id}=join(',',@idresponses);
 9184: 	}
 9185:     }
 9186:     return ($errormsg,$number);
 9187: }
 9188: 
 9189: sub interwrite_eval {
 9190:     my ($questiontitles,$responses)=@_;
 9191:     my $number=0;
 9192:     my $errormsg='';
 9193:     my $skipline=1;
 9194:     my $questionnumber=0;
 9195:     my %idresponses=();
 9196:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 9197:         my %components=&Apache::loncommon::record_sep($line);
 9198:         my @entries=map {$components{$_}} (sort(keys(%components)));
 9199:         if ($entries[1] eq 'Time') { $skipline=0; next; }
 9200:         if ($entries[1] eq 'Response') { $skipline=1; }
 9201:         next if $skipline;
 9202:         if ($entries[0]!=$questionnumber) {
 9203:            $questionnumber=$entries[0];
 9204:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
 9205:            $number++;
 9206:         }
 9207:         my $id=$entries[4];
 9208:         $id=~s/^[\#0]+//;
 9209:         $id=~s/^v\d*\://i;
 9210:         $id=~s/[\-\:]//g;
 9211:         $idresponses{$id}[$number]=$entries[6];
 9212:     }
 9213:     foreach my $id (keys(%idresponses)) {
 9214:        $$responses{$id}=join(',',@{$idresponses{$id}});
 9215:        $$responses{$id}=~s/^\s*\,//;
 9216:     }
 9217:     return ($errormsg,$number);
 9218: }
 9219: 
 9220: sub turning_eval {
 9221:     my ($questiontitles,$responses)=@_;
 9222:     my $number=0;
 9223:     my $errormsg='';
 9224:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 9225:         my %components=&Apache::loncommon::record_sep($line);
 9226:         my @entries=map {$components{$_}} (sort(keys(%components)));
 9227:         if ($#entries>$number) { $number=$#entries; }
 9228:         my $id=$entries[0];
 9229:         my @idresponses;
 9230:         $id=~s/^[\#0]+//;
 9231:         unless ($id) { next; }
 9232:         for (my $idx=1;$idx<=$#entries;$idx++) {
 9233:             $entries[$idx]=~s/\,/\;/g;
 9234:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
 9235:             push(@idresponses,$entries[$idx]);
 9236:         }
 9237:         $$responses{$id}=join(',',@idresponses);
 9238:     }
 9239:     for (my $i=1; $i<=$number; $i++) {
 9240:         $$questiontitles[$i]=&mt('Question [_1]',$i);
 9241:     }
 9242:     return ($errormsg,$number);
 9243: }
 9244: 
 9245: 
 9246: sub assign_clicker_grades {
 9247:     my ($r,$symb)=@_;
 9248:     if (!$symb) {return '';}
 9249: # See which part we are saving to
 9250:     my $res_error;
 9251:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 9252:     if ($res_error) {
 9253:         return &navmap_errormsg();
 9254:     }
 9255: # FIXME: This should probably look for the first handgradeable part
 9256:     my $part=$$partlist[0];
 9257: # Start screen output
 9258:     my $result=&Apache::loncommon::start_data_table().
 9259:              &Apache::loncommon::start_data_table_header_row().
 9260:              '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
 9261:              &Apache::loncommon::end_data_table_header_row().
 9262:              &Apache::loncommon::start_data_table_row().'<td>';
 9263: # Get correct result
 9264: # FIXME: Possibly need delimiter other than ":"
 9265:     my @correct=();
 9266:     my $gradingmechanism=$env{'form.gradingmechanism'};
 9267:     my $number=$env{'form.number'};
 9268:     if ($gradingmechanism ne 'attendance') {
 9269:        foreach my $key (keys(%env)) {
 9270:           if ($key=~/^form\.correct\:/) {
 9271:              my @input=split(/\,/,$env{$key});
 9272:              for (my $i=0;$i<=$#input;$i++) {
 9273:                  if (($correct[$i]) && ($input[$i]) &&
 9274:                      ($correct[$i] ne $input[$i])) {
 9275:                     $result.='<br /><span class="LC_warning">'.
 9276:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
 9277:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
 9278:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
 9279:                     $correct[$i]=$input[$i];
 9280:                  }
 9281:              }
 9282:           }
 9283:        }
 9284:        for (my $i=0;$i<$number;$i++) {
 9285:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
 9286:              $result.='<br /><span class="LC_error">'.
 9287:                       &mt('No correct result given for question "[_1]"!',
 9288:                           $env{'form.question:'.$i}).'</span>';
 9289:           }
 9290:        }
 9291:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
 9292:     }
 9293: # Start grading
 9294:     my $pcorrect=$env{'form.pcorrect'};
 9295:     my $pincorrect=$env{'form.pincorrect'};
 9296:     my $storecount=0;
 9297:     my %users=();
 9298:     foreach my $key (keys(%env)) {
 9299:        my $user='';
 9300:        if ($key=~/^form\.student\:(.*)$/) {
 9301:           $user=$1;
 9302:        }
 9303:        if ($key=~/^form\.unknown\:(.*)$/) {
 9304:           my $id=$1;
 9305:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
 9306:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
 9307:           } elsif ($env{'form.multi'.$id}) {
 9308:              $user=$env{'form.multi'.$id};
 9309:           }
 9310:        }
 9311:        if ($user) {
 9312:           if ($users{$user}) {
 9313:              $result.='<br /><span class="LC_warning">'.
 9314:                       &mt("More than one entry found for <tt>[_1]</tt>!",$user).
 9315:                       '</span><br />';
 9316:           }
 9317:           $users{$user}=1; 
 9318:           my @answer=split(/\,/,$env{$key});
 9319:           my $sum=0;
 9320:           my $realnumber=$number;
 9321:           for (my $i=0;$i<$number;$i++) {
 9322:              if  ($correct[$i] eq '-') {
 9323:                 $realnumber--;
 9324:              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/))  {
 9325:                 if ($gradingmechanism eq 'attendance') {
 9326:                    $sum+=$pcorrect;
 9327:                 } elsif ($correct[$i] eq '*') {
 9328:                    $sum+=$pcorrect;
 9329:                 } else {
 9330: # We actually grade if correct or not
 9331:                    my $increment=$pincorrect;
 9332: # Special case: numerical answer "0"
 9333:                    if ($correct[$i] eq '0') {
 9334:                       if ($answer[$i]=~/^[0\.]+$/) {
 9335:                          $increment=$pcorrect;
 9336:                       }
 9337: # General numerical answer, both evaluate to something non-zero
 9338:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
 9339:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
 9340:                          $increment=$pcorrect;
 9341:                       }
 9342: # Must be just alphanumeric
 9343:                    } elsif ($answer[$i] eq $correct[$i]) {
 9344:                       $increment=$pcorrect;
 9345:                    }
 9346:                    $sum+=$increment;
 9347:                 }
 9348:              }
 9349:           }
 9350:           my $ave=$sum/(100*$realnumber);
 9351: # Store
 9352:           my ($username,$domain)=split(/\:/,$user);
 9353:           my %grades=();
 9354:           $grades{"resource.$part.solved"}='correct_by_override';
 9355:           $grades{"resource.$part.awarded"}=$ave;
 9356:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 9357:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
 9358:                                                  $env{'request.course.id'},
 9359:                                                  $domain,$username);
 9360:           if ($returncode ne 'ok') {
 9361:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
 9362:           } else {
 9363:              $storecount++;
 9364:           }
 9365:        }
 9366:     }
 9367: # We are done
 9368:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
 9369:              '</td>'.
 9370:              &Apache::loncommon::end_data_table_row().
 9371:              &Apache::loncommon::end_data_table();
 9372:     return $result;
 9373: }
 9374: 
 9375: sub navmap_errormsg {
 9376:     return '<div class="LC_error">'.
 9377:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
 9378:            &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>').
 9379:            '</div>';
 9380: }
 9381: 
 9382: sub startpage {
 9383:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag) = @_;
 9384:     unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
 9385:     $r->print(&Apache::loncommon::start_page('Grading',undef,
 9386:                                           {'bread_crumbs' => $crumbs}));
 9387:     &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
 9388:     unless ($nodisplayflag) {
 9389:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag));
 9390:     }
 9391: }
 9392: 
 9393: sub select_problem {
 9394:     my ($r)=@_;
 9395:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
 9396:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1));
 9397:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
 9398:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
 9399: }
 9400: 
 9401: sub handler {
 9402:     my $request=$_[0];
 9403:     &reset_caches();
 9404:     if ($request->header_only) {
 9405:         &Apache::loncommon::content_type($request,'text/html');
 9406:         $request->send_http_header;
 9407:         return OK;
 9408:     }
 9409:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
 9410: 
 9411: # see what command we need to execute
 9412: 
 9413:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
 9414:     my $command=$commands[0];
 9415: 
 9416:     &init_perm();
 9417:     if (!$env{'request.course.id'}) {
 9418:         unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
 9419:                 ($command =~ /^scantronupload/)) {
 9420:             # Not in a course.
 9421:             $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
 9422:             return HTTP_NOT_ACCEPTABLE;
 9423:         }
 9424:     } elsif (!%perm) {
 9425:         $request->internal_redirect('/adm/quickgrades');
 9426:     }
 9427:     &Apache::loncommon::content_type($request,'text/html');
 9428:     $request->send_http_header;
 9429: 
 9430:     if ($#commands > 0) {
 9431: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
 9432:     }
 9433: 
 9434: # see what the symb is
 9435: 
 9436:     my $symb=$env{'form.symb'};
 9437:     unless ($symb) {
 9438:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
 9439:        $symb=&Apache::lonnet::symbread($url);
 9440:     }
 9441:     &Apache::lonenc::check_decrypt(\$symb);
 9442: 
 9443:     $ssi_error = 0;
 9444:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
 9445: #
 9446: # Not called from a resource, but inside a course
 9447: #    
 9448:         &startpage($request,undef,[],1,1);
 9449:         &select_problem($request);
 9450:     } else {
 9451: 	if ($command eq 'submission' && $perm{'vgr'}) {
 9452:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}]);
 9453: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
 9454: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
 9455:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
 9456:                                        {href=>'',text=>'Select student'}],1,1);
 9457: 	    &pickStudentPage($request,$symb);
 9458: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
 9459:             &startpage($request,$symb,
 9460:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
 9461:                                        {href=>'',text=>'Select student'},
 9462:                                        {href=>'',text=>'Grade student'}],1,1);
 9463: 	    &displayPage($request,$symb);
 9464: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
 9465:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
 9466:                                        {href=>'',text=>'Select student'},
 9467:                                        {href=>'',text=>'Grade student'},
 9468:                                        {href=>'',text=>'Store grades'}],1,1);
 9469: 	    &updateGradeByPage($request,$symb);
 9470: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
 9471:             &startpage($request,$symb,[{href=>'',text=>'...'},
 9472:                                        {href=>'',text=>'Modify grades'}]);
 9473: 	    &processGroup($request,$symb);
 9474: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
 9475:             &startpage($request,$symb);
 9476: 	    $request->print(&grading_menu($request,$symb));
 9477: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
 9478:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
 9479: 	    $request->print(&submit_options($request,$symb));
 9480:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
 9481:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}]);
 9482:             $request->print(&listStudents($request,$symb,'graded'));
 9483:         } elsif ($command eq 'table' && $perm{'vgr'}) {
 9484:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
 9485:             $request->print(&submit_options_table($request,$symb));
 9486:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
 9487:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
 9488:             $request->print(&submit_options_sequence($request,$symb));
 9489: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
 9490:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
 9491: 	    $request->print(&viewgrades($request,$symb));
 9492: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
 9493:             &startpage($request,$symb,[{href=>'',text=>'...'},
 9494:                                        {href=>'',text=>'Store grades'}]);
 9495: 	    $request->print(&processHandGrade($request,$symb));
 9496: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
 9497:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
 9498:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
 9499:                                                                              text=>"Modify grades"},
 9500:                                        {href=>'', text=>"Store grades"}]);
 9501: 	    $request->print(&editgrades($request,$symb));
 9502:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
 9503:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
 9504:             $request->print(&initialverifyreceipt($request,$symb));
 9505: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
 9506:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
 9507:                                        {href=>'',text=>'Verification Result'}]);
 9508: 	    $request->print(&verifyreceipt($request,$symb));
 9509:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
 9510:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
 9511:             $request->print(&process_clicker($request,$symb));
 9512:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
 9513:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
 9514:                                        {href=>'', text=>'Process clicker file'}]);
 9515:             $request->print(&process_clicker_file($request,$symb));
 9516:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
 9517:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
 9518:                                        {href=>'', text=>'Process clicker file'},
 9519:                                        {href=>'', text=>'Store grades'}]);
 9520:             $request->print(&assign_clicker_grades($request,$symb));
 9521: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
 9522:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
 9523: 	    $request->print(&upcsvScores_form($request,$symb));
 9524: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
 9525:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
 9526: 	    $request->print(&csvupload($request,$symb));
 9527: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
 9528:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
 9529: 	    $request->print(&csvuploadmap($request,$symb));
 9530: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
 9531: 	    if ($env{'form.associate'} ne 'Reverse Association') {
 9532:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
 9533: 		$request->print(&csvuploadoptions($request,$symb));
 9534: 	    } else {
 9535: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
 9536: 		    $env{'form.upfile_associate'} = 'reverse';
 9537: 		} else {
 9538: 		    $env{'form.upfile_associate'} = 'forward';
 9539: 		}
 9540:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
 9541: 		$request->print(&csvuploadmap($request,$symb));
 9542: 	    }
 9543: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
 9544:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
 9545: 	    $request->print(&csvuploadassign($request,$symb));
 9546: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
 9547:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9548: 	    $request->print(&scantron_selectphase($request,undef,$symb));
 9549:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
 9550:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9551:  	    $request->print(&scantron_do_warning($request,$symb));
 9552: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
 9553:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9554: 	    $request->print(&scantron_validate_file($request,$symb));
 9555: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
 9556:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9557: 	    $request->print(&scantron_process_students($request,$symb));
 9558:  	} elsif ($command eq 'scantronupload' && 
 9559:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9560: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9561:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9562:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
 9563:  	} elsif ($command eq 'scantronupload_save' &&
 9564:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9565: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9566:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9567:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
 9568:  	} elsif ($command eq 'scantron_download' &&
 9569: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 9570:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9571:  	    $request->print(&scantron_download_scantron_data($request,$symb));
 9572:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
 9573:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9574:             $request->print(&checkscantron_results($request,$symb));
 9575:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
 9576:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}]);
 9577:             $request->print(&submit_options_download($request,$symb));
 9578:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
 9579:             &startpage($request,$symb,
 9580:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
 9581:     {href=>'', text=>'Download submissions'}]);
 9582:             &submit_download_link($request,$symb);
 9583: 	} elsif ($command) {
 9584:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
 9585: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
 9586: 	}
 9587:     }
 9588:     if ($ssi_error) {
 9589: 	&ssi_print_error($request);
 9590:     }
 9591:     &Apache::lonquickgrades::endGradeScreen($request);
 9592:     $request->print(&Apache::loncommon::end_page());
 9593:     &reset_caches();
 9594:     return OK;
 9595: }
 9596: 
 9597: 1;
 9598: 
 9599: __END__;
 9600: 
 9601: 
 9602: =head1 NAME
 9603: 
 9604: Apache::grades
 9605: 
 9606: =head1 SYNOPSIS
 9607: 
 9608: Handles the viewing of grades.
 9609: 
 9610: This is part of the LearningOnline Network with CAPA project
 9611: described at http://www.lon-capa.org.
 9612: 
 9613: =head1 OVERVIEW
 9614: 
 9615: Do an ssi with retries:
 9616: While I'd love to factor out this with the vesrion in lonprintout,
 9617: 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
 9618: I'm not quite ready to invent (e.g. an ssi_with_retry object).
 9619: 
 9620: At least the logic that drives this has been pulled out into loncommon.
 9621: 
 9622: 
 9623: 
 9624: ssi_with_retries - Does the server side include of a resource.
 9625:                      if the ssi call returns an error we'll retry it up to
 9626:                      the number of times requested by the caller.
 9627:                      If we still have a proble, no text is appended to the
 9628:                      output and we set some global variables.
 9629:                      to indicate to the caller an SSI error occurred.  
 9630:                      All of this is supposed to deal with the issues described
 9631:                      in LonCAPA BZ 5631 see:
 9632:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
 9633:                      by informing the user that this happened.
 9634: 
 9635: Parameters:
 9636:   resource   - The resource to include.  This is passed directly, without
 9637:                interpretation to lonnet::ssi.
 9638:   form       - The form hash parameters that guide the interpretation of the resource
 9639:                
 9640:   retries    - Number of retries allowed before giving up completely.
 9641: Returns:
 9642:   On success, returns the rendered resource identified by the resource parameter.
 9643: Side Effects:
 9644:   The following global variables can be set:
 9645:    ssi_error                - If an unrecoverable error occurred this becomes true.
 9646:                               It is up to the caller to initialize this to false
 9647:                               if desired.
 9648:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
 9649:                               of the resource that could not be rendered by the ssi
 9650:                               call.
 9651:    ssi_error_message   - The error string fetched from the ssi response
 9652:                               in the event of an error.
 9653: 
 9654: 
 9655: =head1 HANDLER SUBROUTINE
 9656: 
 9657: ssi_with_retries()
 9658: 
 9659: =head1 SUBROUTINES
 9660: 
 9661: =over
 9662: 
 9663: =item scantron_get_correction() : 
 9664: 
 9665:    Builds the interface screen to interact with the operator to fix a
 9666:    specific error condition in a specific scanline
 9667: 
 9668:  Arguments:
 9669:     $r           - Apache request object
 9670:     $i           - number of the current scanline
 9671:     $scan_record - hash ref as returned from &scantron_parse_scanline()
 9672:     $scan_config - hash ref as returned from &get_scantron_config()
 9673:     $line        - full contents of the current scanline
 9674:     $error       - error condition, valid values are
 9675:                    'incorrectCODE', 'duplicateCODE',
 9676:                    'doublebubble', 'missingbubble',
 9677:                    'duplicateID', 'incorrectID'
 9678:     $arg         - extra information needed
 9679:        For errors:
 9680:          - duplicateID   - paper number that this studentID was seen before on
 9681:          - duplicateCODE - array ref of the paper numbers this CODE was
 9682:                            seen on before
 9683:          - incorrectCODE - current incorrect CODE 
 9684:          - doublebubble  - array ref of the bubble lines that have double
 9685:                            bubble errors
 9686:          - missingbubble - array ref of the bubble lines that have missing
 9687:                            bubble errors
 9688: 
 9689: =item  scantron_get_maxbubble() : 
 9690: 
 9691:    Arguments:
 9692:        $nav_error  - Reference to scalar which is a flag to indicate a
 9693:                       failure to retrieve a navmap object.
 9694:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
 9695:        calling routine should trap the error condition and display the warning
 9696:        found in &navmap_errormsg().
 9697: 
 9698:        $scantron_config - Reference to bubblesheet format configuration hash.
 9699: 
 9700:    Returns the maximum number of bubble lines that are expected to
 9701:    occur. Does this by walking the selected sequence rendering the
 9702:    resource and then checking &Apache::lonxml::get_problem_counter()
 9703:    for what the current value of the problem counter is.
 9704: 
 9705:    Caches the results to $env{'form.scantron_maxbubble'},
 9706:    $env{'form.scantron.bubble_lines.n'}, 
 9707:    $env{'form.scantron.first_bubble_line.n'} and
 9708:    $env{"form.scantron.sub_bubblelines.n"}
 9709:    which are the total number of bubble, lines, the number of bubble
 9710:    lines for response n and number of the first bubble line for response n,
 9711:    and a comma separated list of numbers of bubble lines for sub-questions
 9712:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
 9713: 
 9714: 
 9715: =item  scantron_validate_missingbubbles() : 
 9716: 
 9717:    Validates all scanlines in the selected file to not have any
 9718:     answers that don't have bubbles that have not been verified
 9719:     to be bubble free.
 9720: 
 9721: =item  scantron_process_students() : 
 9722: 
 9723:    Routine that does the actual grading of the bubblesheet information.
 9724: 
 9725:    The parsed scanline hash is added to %env 
 9726: 
 9727:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
 9728:    foreach resource , with the form data of
 9729: 
 9730: 	'submitted'     =>'scantron' 
 9731: 	'grade_target'  =>'grade',
 9732: 	'grade_username'=> username of student
 9733: 	'grade_domain'  => domain of student
 9734: 	'grade_courseid'=> of course
 9735: 	'grade_symb'    => symb of resource to grade
 9736: 
 9737:     This triggers a grading pass. The problem grading code takes care
 9738:     of converting the bubbled letter information (now in %env) into a
 9739:     valid submission.
 9740: 
 9741: =item  scantron_upload_scantron_data() :
 9742: 
 9743:     Creates the screen for adding a new bubblesheet data file to a course.
 9744: 
 9745: =item  scantron_upload_scantron_data_save() : 
 9746: 
 9747:    Adds a provided bubble information data file to the course if user
 9748:    has the correct privileges to do so. 
 9749: 
 9750: =item  valid_file() :
 9751: 
 9752:    Validates that the requested bubble data file exists in the course.
 9753: 
 9754: =item  scantron_download_scantron_data() : 
 9755: 
 9756:    Shows a list of the three internal files (original, corrected,
 9757:    skipped) for a specific bubblesheet data file that exists in the
 9758:    course.
 9759: 
 9760: =item  scantron_validate_ID() : 
 9761: 
 9762:    Validates all scanlines in the selected file to not have any
 9763:    invalid or underspecified student/employee IDs
 9764: 
 9765: =item navmap_errormsg() :
 9766: 
 9767:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
 9768:    Should be called whenever the request to instantiate a navmap object fails.  
 9769: 
 9770: =back
 9771: 
 9772: =cut

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