File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.655: download - view: text, annotated - select for diffs
Sun Oct 9 15:31:12 2011 UTC (12 years, 7 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Missing localization.

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.655 2011/10/09 15:31:12 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: 
   30: 
   31: package Apache::grades;
   32: use strict;
   33: use Apache::style;
   34: use Apache::lonxml;
   35: use Apache::lonnet;
   36: use Apache::loncommon;
   37: use Apache::lonhtmlcommon;
   38: use Apache::lonnavmaps;
   39: use Apache::lonhomework;
   40: use Apache::lonpickcode;
   41: use Apache::loncoursedata;
   42: use Apache::lonmsg();
   43: use Apache::Constants qw(:common :http);
   44: use Apache::lonlocal;
   45: use Apache::lonenc;
   46: use Apache::lonstathelpers;
   47: use Apache::lonquickgrades;
   48: use String::Similarity;
   49: use LONCAPA;
   50: 
   51: use POSIX qw(floor);
   52: 
   53: 
   54: 
   55: my %perm=();
   56: 
   57: #  These variables are used to recover from ssi errors
   58: 
   59: my $ssi_retries = 5;
   60: my $ssi_error;
   61: my $ssi_error_resource;
   62: my $ssi_error_message;
   63: 
   64: 
   65: sub ssi_with_retries {
   66:     my ($resource, $retries, %form) = @_;
   67:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
   68:     if ($response->is_error) {
   69: 	$ssi_error          = 1;
   70: 	$ssi_error_resource = $resource;
   71: 	$ssi_error_message  = $response->code . " " . $response->message;
   72:     }
   73: 
   74:     return $content;
   75: 
   76: }
   77: #
   78: #  Prodcuces an ssi retry failure error message to the user:
   79: #
   80: 
   81: sub ssi_print_error {
   82:     my ($r) = @_;
   83:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
   84:     $r->print('
   85: <br />
   86: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
   87: <p>
   88: '.&mt('Unable to retrieve a resource from a server:').'<br />
   89: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
   90: '.&mt('Error:').' '.$ssi_error_message.'
   91: </p>
   92: <p>'.
   93: &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 />'.
   94: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
   95: '</p>');
   96:     return;
   97: }
   98: 
   99: #
  100: # --- Retrieve the parts from the metadata file.---
  101: # Returns an array of everything that the resources stores away
  102: #
  103: 
  104: sub getpartlist {
  105:     my ($symb,$errorref) = @_;
  106: 
  107:     my $navmap   = Apache::lonnavmaps::navmap->new();
  108:     unless (ref($navmap)) {
  109:         if (ref($errorref)) { 
  110:             $$errorref = 'navmap';
  111:             return;
  112:         }
  113:     }
  114:     my $res      = $navmap->getBySymb($symb);
  115:     my $partlist = $res->parts();
  116:     my $url      = $res->src();
  117:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
  118: 
  119:     my @stores;
  120:     foreach my $part (@{ $partlist }) {
  121: 	foreach my $key (@metakeys) {
  122: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
  123: 	}
  124:     }
  125:     return @stores;
  126: }
  127: 
  128: #--- Format fullname, username:domain if different for display
  129: #--- Use anywhere where the student names are listed
  130: sub nameUserString {
  131:     my ($type,$fullname,$uname,$udom) = @_;
  132:     if ($type eq 'header') {
  133: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
  134:     } else {
  135: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
  136: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
  137:     }
  138: }
  139: 
  140: #--- Get the partlist and the response type for a given problem. ---
  141: #--- Indicate if a response type is coded handgraded or not. ---
  142: #--- Sets response_error pointer to "1" if navmaps object broken ---
  143: sub response_type {
  144:     my ($symb,$response_error) = @_;
  145: 
  146:     my $navmap = Apache::lonnavmaps::navmap->new();
  147:     unless (ref($navmap)) {
  148:         if (ref($response_error)) {
  149:             $$response_error = 1;
  150:         }
  151:         return;
  152:     }
  153:     my $res = $navmap->getBySymb($symb);
  154:     unless (ref($res)) {
  155:         $$response_error = 1;
  156:         return;
  157:     }
  158:     my $partlist = $res->parts();
  159:     my %vPart = 
  160: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
  161:     my (%response_types,%handgrade);
  162:     foreach my $part (@{ $partlist }) {
  163: 	next if (%vPart && !exists($vPart{$part}));
  164: 
  165: 	my @types = $res->responseType($part);
  166: 	my @ids = $res->responseIds($part);
  167: 	for (my $i=0; $i < scalar(@ids); $i++) {
  168: 	    $response_types{$part}{$ids[$i]} = $types[$i];
  169: 	    $handgrade{$part.'_'.$ids[$i]} = 
  170: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
  171: 				     '.handgrade',$symb);
  172: 	}
  173:     }
  174:     return ($partlist,\%handgrade,\%response_types);
  175: }
  176: 
  177: sub flatten_responseType {
  178:     my ($responseType) = @_;
  179:     my @part_response_id =
  180: 	map { 
  181: 	    my $part = $_;
  182: 	    map {
  183: 		[$part,$_]
  184: 		} sort(keys(%{ $responseType->{$part} }));
  185: 	} sort(keys(%$responseType));
  186:     return @part_response_id;
  187: }
  188: 
  189: sub get_display_part {
  190:     my ($partID,$symb)=@_;
  191:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
  192:     if (defined($display) and $display ne '') {
  193:         $display.= ' (<span class="LC_internal_info">'
  194:                   .&mt('Part ID: [_1]',$partID).'</span>)';
  195:     } else {
  196: 	$display=$partID;
  197:     }
  198:     return $display;
  199: }
  200: 
  201: sub reset_caches {
  202:     &reset_analyze_cache();
  203:     &reset_perm();
  204: }
  205: 
  206: {
  207:     my %analyze_cache;
  208:     my %analyze_cache_formkeys;
  209: 
  210:     sub reset_analyze_cache {
  211: 	undef(%analyze_cache);
  212:         undef(%analyze_cache_formkeys);
  213:     }
  214: 
  215:     sub get_analyze {
  216: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash,$type,$trial,$rndseed,$bubbles_per_row)=@_;
  217: 	my $key = "$symb\0$uname\0$udom";
  218:         if ($type eq 'randomizetry') {
  219:             if ($trial ne '') {
  220:                 $key .= "\0".$trial;
  221:             }
  222:         }
  223: 	if (exists($analyze_cache{$key})) {
  224:             my $getupdate = 0;
  225:             if (ref($add_to_hash) eq 'HASH') {
  226:                 foreach my $item (keys(%{$add_to_hash})) {
  227:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
  228:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
  229:                             $getupdate = 1;
  230:                             last;
  231:                         }
  232:                     } else {
  233:                         $getupdate = 1;
  234:                     }
  235:                 }
  236:             }
  237:             if (!$getupdate) {
  238:                 return $analyze_cache{$key};
  239:             }
  240:         }
  241: 
  242: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
  243: 	$url=&Apache::lonnet::clutter($url);
  244:         my %form = ('grade_target'      => 'analyze',
  245:                     'grade_domain'      => $udom,
  246:                     'grade_symb'        => $symb,
  247:                     'grade_courseid'    =>  $env{'request.course.id'},
  248:                     'grade_username'    => $uname,
  249:                     'grade_noincrement' => $no_increment);
  250:         if ($bubbles_per_row ne '') {
  251:             $form{'bubbles_per_row'} = $bubbles_per_row;
  252:         }
  253:         if ($type eq 'randomizetry') {
  254:             $form{'grade_questiontype'} = $type;
  255:             if ($rndseed ne '') {
  256:                 $form{'grade_rndseed'} = $rndseed;
  257:             }
  258:         }
  259:         if (ref($add_to_hash)) {
  260:             %form = (%form,%{$add_to_hash});
  261:         }
  262: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
  263: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
  264: 	my %analyze=&Apache::lonnet::str2hash($subresult);
  265:         if (ref($add_to_hash) eq 'HASH') {
  266:             $analyze_cache_formkeys{$key} = $add_to_hash;
  267:         } else {
  268:             $analyze_cache_formkeys{$key} = {};
  269:         }
  270: 	return $analyze_cache{$key} = \%analyze;
  271:     }
  272: 
  273:     sub get_order {
  274: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment,$type,$trial,$rndseed)=@_;
  275: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment,undef,$type,$trial,$rndseed);
  276: 	return $analyze->{"$partid.$respid.shown"};
  277:     }
  278: 
  279:     sub get_radiobutton_correct_foil {
  280: 	my ($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed)=@_;
  281: 	my $analyze = &get_analyze($symb,$uname,$udom,undef,undef,$type,$trial,$rndseed);
  282:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom,undef,$type,$trial,$rndseed);
  283:         if (ref($foils) eq 'ARRAY') {
  284: 	    foreach my $foil (@{$foils}) {
  285: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
  286: 		    return $foil;
  287: 	        }
  288: 	    }
  289: 	}
  290:     }
  291: 
  292:     sub scantron_partids_tograde {
  293:         my ($resource,$cid,$uname,$udom,$check_for_randomlist,$bubbles_per_row) = @_;
  294:         my (%analysis,@parts);
  295:         if (ref($resource)) {
  296:             my $symb = $resource->symb();
  297:             my $add_to_form;
  298:             if ($check_for_randomlist) {
  299:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
  300:             }
  301:             my $analyze = 
  302:                 &get_analyze($symb,$uname,$udom,undef,$add_to_form,
  303:                              undef,undef,undef,$bubbles_per_row);
  304:             if (ref($analyze) eq 'HASH') {
  305:                 %analysis = %{$analyze};
  306:             }
  307:             if (ref($analysis{'parts'}) eq 'ARRAY') {
  308:                 foreach my $part (@{$analysis{'parts'}}) {
  309:                     my ($id,$respid) = split(/\./,$part);
  310:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
  311:                         push(@parts,$part);
  312:                     }
  313:                 }
  314:             }
  315:         }
  316:         return (\%analysis,\@parts);
  317:     }
  318: 
  319: }
  320: 
  321: #--- Clean response type for display
  322: #--- Currently filters option/rank/radiobutton/match/essay/Task
  323: #        response types only.
  324: sub cleanRecord {
  325:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
  326: 	$uname,$udom,$type,$trial,$rndseed) = @_;
  327:     my $grayFont = '<span class="LC_internal_info">';
  328:     if ($response =~ /^(option|rank)$/) {
  329: 	my %answer=&Apache::lonnet::str2hash($answer);
  330: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  331: 	my ($toprow,$bottomrow);
  332: 	foreach my $foil (@$order) {
  333: 	    if ($grading{$foil} == 1) {
  334: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
  335: 	    } else {
  336: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
  337: 	    }
  338: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  339: 	}
  340: 	return '<blockquote><table border="1">'.
  341: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  342: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  343: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
  344:     } elsif ($response eq 'match') {
  345: 	my %answer=&Apache::lonnet::str2hash($answer);
  346: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  347: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
  348: 	my ($toprow,$middlerow,$bottomrow);
  349: 	foreach my $foil (@$order) {
  350: 	    my $item=shift(@items);
  351: 	    if ($grading{$foil} == 1) {
  352: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
  353: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
  354: 	    } else {
  355: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
  356: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
  357: 	    }
  358: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  359: 	}
  360: 	return '<blockquote><table border="1">'.
  361: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  362: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
  363: 	    $middlerow.'</tr>'.
  364: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  365: 	    $bottomrow.'</tr>'.'</table></blockquote>';
  366:     } elsif ($response eq 'radiobutton') {
  367: 	my %answer=&Apache::lonnet::str2hash($answer);
  368: 	my ($toprow,$bottomrow);
  369: 	my $correct = 
  370: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
  371: 	foreach my $foil (@$order) {
  372: 	    if (exists($answer{$foil})) {
  373: 		if ($foil eq $correct) {
  374: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
  375: 		} else {
  376: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
  377: 		}
  378: 	    } else {
  379: 		$toprow.='<td>'.&mt('false').'</td>';
  380: 	    }
  381: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  382: 	}
  383: 	return '<blockquote><table border="1">'.
  384: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  385: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  386: 	    $bottomrow.'</tr>'.'</table></blockquote>';
  387:     } elsif ($response eq 'essay') {
  388: 	if (! exists ($env{'form.'.$symb})) {
  389: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
  390: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
  391: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
  392: 
  393: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
  394: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
  395: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
  396: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
  397: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
  398: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
  399: 	}
  400: 	$answer =~ s-\n-<br />-g;
  401: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
  402:     } elsif ( $response eq 'organic') {
  403: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
  404: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
  405: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
  406: 	return $result;
  407:     } elsif ( $response eq 'Task') {
  408: 	if ( $answer eq 'SUBMITTED') {
  409: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
  410: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
  411: 	    return $result;
  412: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
  413: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
  414: 			       keys(%{$record}));
  415: 	    return join('<br />',($version,@matches));
  416: 			       
  417: 			       
  418: 	} else {
  419: 	    my $result =
  420: 		'<p>'
  421: 		.&mt('Overall result: [_1]',
  422: 		     $record->{$version."resource.$respid.$partid.status"})
  423: 		.'</p>';
  424: 	    
  425: 	    $result .= '<ul>';
  426: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
  427: 			     keys(%{$record}));
  428: 	    foreach my $grade (sort(@grade)) {
  429: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
  430: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
  431: 				     $dim, $record->{$grade}).
  432: 			  '</li>';
  433: 	    }
  434: 	    $result.='</ul>';
  435: 	    return $result;
  436: 	}
  437:     } elsif ( $response =~ m/(?:numerical|formula)/) {
  438: 	$answer = 
  439: 	    &Apache::loncommon::format_previous_attempt_value('submission',
  440: 							      $answer);
  441:     }
  442:     return $answer;
  443: }
  444: 
  445: #-- A couple of common js functions
  446: sub commonJSfunctions {
  447:     my $request = shift;
  448:     $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
  449:     function radioSelection(radioButton) {
  450: 	var selection=null;
  451: 	if (radioButton.length > 1) {
  452: 	    for (var i=0; i<radioButton.length; i++) {
  453: 		if (radioButton[i].checked) {
  454: 		    return radioButton[i].value;
  455: 		}
  456: 	    }
  457: 	} else {
  458: 	    if (radioButton.checked) return radioButton.value;
  459: 	}
  460: 	return selection;
  461:     }
  462: 
  463:     function pullDownSelection(selectOne) {
  464: 	var selection="";
  465: 	if (selectOne.length > 1) {
  466: 	    for (var i=0; i<selectOne.length; i++) {
  467: 		if (selectOne[i].selected) {
  468: 		    return selectOne[i].value;
  469: 		}
  470: 	    }
  471: 	} else {
  472:             // only one value it must be the selected one
  473: 	    return selectOne.value;
  474: 	}
  475:     }
  476: COMMONJSFUNCTIONS
  477: }
  478: 
  479: #--- Dumps the class list with usernames,list of sections,
  480: #--- section, ids and fullnames for each user.
  481: sub getclasslist {
  482:     my ($getsec,$filterlist,$getgroup) = @_;
  483:     my @getsec;
  484:     my @getgroup;
  485:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  486:     if (!ref($getsec)) {
  487: 	if ($getsec ne '' && $getsec ne 'all') {
  488: 	    @getsec=($getsec);
  489: 	}
  490:     } else {
  491: 	@getsec=@{$getsec};
  492:     }
  493:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
  494:     if (!ref($getgroup)) {
  495: 	if ($getgroup ne '' && $getgroup ne 'all') {
  496: 	    @getgroup=($getgroup);
  497: 	}
  498:     } else {
  499: 	@getgroup=@{$getgroup};
  500:     }
  501:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
  502: 
  503:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
  504:     # Bail out if we were unable to get the classlist
  505:     return if (! defined($classlist));
  506:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
  507:     #
  508:     my %sections;
  509:     my %fullnames;
  510:     foreach my $student (keys(%$classlist)) {
  511:         my $end      = 
  512:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
  513:         my $start    = 
  514:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
  515:         my $id       = 
  516:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
  517:         my $section  = 
  518:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
  519:         my $fullname = 
  520:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
  521:         my $status   = 
  522:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
  523:         my $group   = 
  524:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
  525: 	# filter students according to status selected
  526: 	if ($filterlist && (!($stu_status =~ /Any/))) {
  527: 	    if (!($stu_status =~ $status)) {
  528: 		delete($classlist->{$student});
  529: 		next;
  530: 	    }
  531: 	}
  532: 	# filter students according to groups selected
  533: 	my @stu_groups = split(/,/,$group);
  534: 	if (@getgroup) {
  535: 	    my $exclude = 1;
  536: 	    foreach my $grp (@getgroup) {
  537: 	        foreach my $stu_group (@stu_groups) {
  538: 	            if ($stu_group eq $grp) {
  539: 	                $exclude = 0;
  540:     	            } 
  541: 	        }
  542:     	        if (($grp eq 'none') && !$group) {
  543:         	        $exclude = 0;
  544:         	}
  545: 	    }
  546: 	    if ($exclude) {
  547: 	        delete($classlist->{$student});
  548: 	    }
  549: 	}
  550: 	$section = ($section ne '' ? $section : 'none');
  551: 	if (&canview($section)) {
  552: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
  553: 		$sections{$section}++;
  554: 		if ($classlist->{$student}) {
  555: 		    $fullnames{$student}=$fullname;
  556: 		}
  557: 	    } else {
  558: 		delete($classlist->{$student});
  559: 	    }
  560: 	} else {
  561: 	    delete($classlist->{$student});
  562: 	}
  563:     }
  564:     my %seen = ();
  565:     my @sections = sort(keys(%sections));
  566:     return ($classlist,\@sections,\%fullnames);
  567: }
  568: 
  569: sub canmodify {
  570:     my ($sec)=@_;
  571:     if ($perm{'mgr'}) {
  572: 	if (!defined($perm{'mgr_section'})) {
  573: 	    # can modify whole class
  574: 	    return 1;
  575: 	} else {
  576: 	    if ($sec eq $perm{'mgr_section'}) {
  577: 		#can modify the requested section
  578: 		return 1;
  579: 	    } else {
  580: 		# can't modify the request section
  581: 		return 0;
  582: 	    }
  583: 	}
  584:     }
  585:     #can't modify
  586:     return 0;
  587: }
  588: 
  589: sub canview {
  590:     my ($sec)=@_;
  591:     if ($perm{'vgr'}) {
  592: 	if (!defined($perm{'vgr_section'})) {
  593: 	    # can modify whole class
  594: 	    return 1;
  595: 	} else {
  596: 	    if ($sec eq $perm{'vgr_section'}) {
  597: 		#can modify the requested section
  598: 		return 1;
  599: 	    } else {
  600: 		# can't modify the request section
  601: 		return 0;
  602: 	    }
  603: 	}
  604:     }
  605:     #can't modify
  606:     return 0;
  607: }
  608: 
  609: #--- Retrieve the grade status of a student for all the parts
  610: sub student_gradeStatus {
  611:     my ($symb,$udom,$uname,$partlist) = @_;
  612:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
  613:     my %partstatus = ();
  614:     foreach (@$partlist) {
  615: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
  616: 	$status              = 'nothing' if ($status eq '');
  617: 	$partstatus{$_}      = $status;
  618: 	my $subkey           = "resource.$_.submitted_by";
  619: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
  620:     }
  621:     return %partstatus;
  622: }
  623: 
  624: # hidden form and javascript that calls the form
  625: # Use by verifyscript and viewgrades
  626: # Shows a student's view of problem and submission
  627: sub jscriptNform {
  628:     my ($symb) = @_;
  629:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  630:     my $jscript= &Apache::lonhtmlcommon::scripttag(
  631: 	'    function viewOneStudent(user,domain) {'."\n".
  632: 	'	document.onestudent.student.value = user;'."\n".
  633: 	'	document.onestudent.userdom.value = domain;'."\n".
  634: 	'	document.onestudent.submit();'."\n".
  635: 	'    }'."\n".
  636: 	"\n");
  637:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
  638: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  639: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
  640: 	'<input type="hidden" name="command" value="submission" />'."\n".
  641: 	'<input type="hidden" name="student" value="" />'."\n".
  642: 	'<input type="hidden" name="userdom" value="" />'."\n".
  643: 	'</form>'."\n";
  644:     return $jscript;
  645: }
  646: 
  647: 
  648: 
  649: # Given the score (as a number [0-1] and the weight) what is the final
  650: # point value? This function will round to the nearest tenth, third,
  651: # or quarter if one of those is within the tolerance of .00001.
  652: sub compute_points {
  653:     my ($score, $weight) = @_;
  654:     
  655:     my $tolerance = .00001;
  656:     my $points = $score * $weight;
  657: 
  658:     # Check for nearness to 1/x.
  659:     my $check_for_nearness = sub {
  660:         my ($factor) = @_;
  661:         my $num = ($points * $factor) + $tolerance;
  662:         my $floored_num = floor($num);
  663:         if ($num - $floored_num < 2 * $tolerance * $factor) {
  664:             return $floored_num / $factor;
  665:         }
  666:         return $points;
  667:     };
  668: 
  669:     $points = $check_for_nearness->(10);
  670:     $points = $check_for_nearness->(3);
  671:     $points = $check_for_nearness->(4);
  672:     
  673:     return $points;
  674: }
  675: 
  676: #------------------ End of general use routines --------------------
  677: 
  678: #
  679: # Find most similar essay
  680: #
  681: 
  682: sub most_similar {
  683:     my ($uname,$udom,$uessay,$old_essays)=@_;
  684: 
  685: # ignore spaces and punctuation
  686: 
  687:     $uessay=~s/\W+/ /gs;
  688: 
  689: # ignore empty submissions (occuring when only files are sent)
  690: 
  691:     unless ($uessay=~/\w+/s) { return ''; }
  692: 
  693: # these will be returned. Do not care if not at least 50 percent similar
  694:     my $limit=0.6;
  695:     my $sname='';
  696:     my $sdom='';
  697:     my $scrsid='';
  698:     my $sessay='';
  699: # go through all essays ...
  700:     foreach my $tkey (keys(%$old_essays)) {
  701: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
  702: # ... except the same student
  703:         next if (($tname eq $uname) && ($tdom eq $udom));
  704: 	my $tessay=$old_essays->{$tkey};
  705: 	$tessay=~s/\W+/ /gs;
  706: # String similarity gives up if not even limit
  707: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
  708: # Found one
  709: 	if ($tsimilar>$limit) {
  710: 	    $limit=$tsimilar;
  711: 	    $sname=$tname;
  712: 	    $sdom=$tdom;
  713: 	    $scrsid=$tcrsid;
  714: 	    $sessay=$old_essays->{$tkey};
  715: 	}
  716:     }
  717:     if ($limit>0.6) {
  718:        return ($sname,$sdom,$scrsid,$sessay,$limit);
  719:     } else {
  720:        return ('','','','',0);
  721:     }
  722: }
  723: 
  724: #-------------------------------------------------------------------
  725: 
  726: #------------------------------------ Receipt Verification Routines
  727: #
  728: 
  729: sub initialverifyreceipt {
  730:    my ($request,$symb) = @_;
  731:    &commonJSfunctions($request);
  732:    return '<form name="gradingMenu"><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
  733:         &Apache::lonnet::recprefix($env{'request.course.id'}).
  734:         '-<input type="text" name="receipt" size="4" />'.
  735:         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  736:         '<input type="hidden" name="command" value="verify" />'.
  737:         "</form>\n";
  738: }
  739: 
  740: #--- Check whether a receipt number is valid.---
  741: sub verifyreceipt {
  742:     my ($request,$symb)  = @_;
  743: 
  744:     my $courseid = $env{'request.course.id'};
  745:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
  746: 	$env{'form.receipt'};
  747:     $receipt     =~ s/[^\-\d]//g;
  748: 
  749:     my $title.=
  750: 	'<h3><span class="LC_info">'.
  751: 	&mt('Verifying Receipt Number [_1]',$receipt).
  752: 	'</span></h3>'."\n";
  753: 
  754:     my ($string,$contents,$matches) = ('','',0);
  755:     my (undef,undef,$fullname) = &getclasslist('all','0');
  756:     
  757:     my $receiptparts=0;
  758:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
  759: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
  760:     my $parts=['0'];
  761:     if ($receiptparts) {
  762:         my $res_error; 
  763:         ($parts)=&response_type($symb,\$res_error);
  764:         if ($res_error) {
  765:             return &navmap_errormsg();
  766:         } 
  767:     }
  768:     
  769:     my $header = 
  770: 	&Apache::loncommon::start_data_table().
  771: 	&Apache::loncommon::start_data_table_header_row().
  772: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
  773: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
  774: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
  775:     if ($receiptparts) {
  776: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
  777:     }
  778:     $header.=
  779: 	&Apache::loncommon::end_data_table_header_row();
  780: 
  781:     foreach (sort 
  782: 	     {
  783: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  784: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  785: 		 }
  786: 		 return $a cmp $b;
  787: 	     } (keys(%$fullname))) {
  788: 	my ($uname,$udom)=split(/\:/);
  789: 	foreach my $part (@$parts) {
  790: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
  791: 		$contents.=
  792: 		    &Apache::loncommon::start_data_table_row().
  793: 		    '<td>&nbsp;'."\n".
  794: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
  795: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
  796: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
  797: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
  798: 		if ($receiptparts) {
  799: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
  800: 		}
  801: 		$contents.= 
  802: 		    &Apache::loncommon::end_data_table_row()."\n";
  803: 		
  804: 		$matches++;
  805: 	    }
  806: 	}
  807:     }
  808:     if ($matches == 0) {
  809:         $string = $title
  810:                  .'<p class="LC_warning">'
  811:                  .&mt('No match found for the above receipt number.')
  812:                  .'</p>';
  813:     } else {
  814: 	$string = &jscriptNform($symb).$title.
  815: 	    '<p>'.
  816: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
  817: 	    '</p>'.
  818: 	    $header.
  819: 	    $contents.
  820: 	    &Apache::loncommon::end_data_table()."\n";
  821:     }
  822:     return $string;
  823: }
  824: 
  825: #--- This is called by a number of programs.
  826: #--- Called from the Grading Menu - View/Grade an individual student
  827: #--- Also called directly when one clicks on the subm button 
  828: #    on the problem page.
  829: sub listStudents {
  830:     my ($request,$symb,$submitonly) = @_;
  831: 
  832:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
  833:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
  834:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
  835:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
  836:     unless ($submitonly) {
  837:        $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
  838:     }
  839: 
  840:     my $result='';
  841:     my $res_error;
  842:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
  843: 
  844:     my %lt = &Apache::lonlocal::texthash (
  845: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
  846: 		'single'   => 'Please select the student before clicking on the Next button.',
  847: 	     );
  848:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
  849:     function checkSelect(checkBox) {
  850: 	var ctr=0;
  851: 	var sense="";
  852: 	if (checkBox.length > 1) {
  853: 	    for (var i=0; i<checkBox.length; i++) {
  854: 		if (checkBox[i].checked) {
  855: 		    ctr++;
  856: 		}
  857: 	    }
  858: 	    sense = '$lt{'multiple'}';
  859: 	} else {
  860: 	    if (checkBox.checked) {
  861: 		ctr = 1;
  862: 	    }
  863: 	    sense = '$lt{'single'}';
  864: 	}
  865: 	if (ctr == 0) {
  866: 	    alert(sense);
  867: 	    return false;
  868: 	}
  869: 	document.gradesub.submit();
  870:     }
  871: 
  872:     function reLoadList(formname) {
  873: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
  874: 	formname.command.value = 'submission';
  875: 	formname.submit();
  876:     }
  877: LISTJAVASCRIPT
  878: 
  879:     &commonJSfunctions($request);
  880:     $request->print($result);
  881: 
  882:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
  883: 	"\n";
  884: 	
  885:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
  886:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
  887:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
  888:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
  889:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
  890:                   .&Apache::lonhtmlcommon::row_closure();
  891:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
  892:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
  893:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
  894:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
  895:                   .&Apache::lonhtmlcommon::row_closure();
  896: 
  897:     my $submission_options;
  898:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  899:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
  900:     $env{'form.Status'} = $saveStatus;
  901:     $submission_options.=
  902:         '<span class="LC_nobreak">'.
  903:         '<label><input type="radio" name="lastSub" value="lastonly" /> '.
  904:         &mt('last submission only').' </label></span>'."\n".
  905:         '<span class="LC_nobreak">'.
  906:         '<label><input type="radio" name="lastSub" value="last" /> '.
  907:         &mt('last submission &amp; parts info').' </label></span>'."\n".
  908:         '<span class="LC_nobreak">'.
  909:         '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.
  910:         &mt('by dates and submissions').'</label></span>'."\n".
  911:         '<span class="LC_nobreak">'.
  912:         '<label><input type="radio" name="lastSub" value="all" /> '.
  913:         &mt('all details').'</label></span>';
  914:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
  915:                   .$submission_options
  916:                   .&Apache::lonhtmlcommon::row_closure();
  917: 
  918:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
  919:                   .'<select name="increment">'
  920:                   .'<option value="1">'.&mt('Whole Points').'</option>'
  921:                   .'<option value=".5">'.&mt('Half Points').'</option>'
  922:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
  923:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
  924:                   .'</select>'
  925:                   .&Apache::lonhtmlcommon::row_closure();
  926: 
  927:     $gradeTable .= 
  928:         &build_section_inputs().
  929: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
  930: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  931: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
  932: 
  933:     if (exists($env{'form.Status'})) {
  934: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
  935:     } else {
  936:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
  937:                       .&Apache::lonhtmlcommon::StatusOptions(
  938:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
  939:                       .&Apache::lonhtmlcommon::row_closure();
  940:     }
  941: 
  942:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
  943:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
  944:                   .&Apache::lonhtmlcommon::row_closure(1)
  945:                   .&Apache::lonhtmlcommon::end_pick_box();
  946: 
  947:     $gradeTable .= '<p>'
  948:                   .&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"
  949:                   .'<input type="hidden" name="command" value="processGroup" />'
  950:                   .'</p>';
  951: 
  952: # checkall buttons
  953:     $gradeTable.=&check_script('gradesub', 'stuinfo');
  954:     $gradeTable.='<input type="button" '."\n".
  955:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
  956:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
  957:     $gradeTable.=&check_buttons();
  958:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
  959:     $gradeTable.= &Apache::loncommon::start_data_table().
  960: 	&Apache::loncommon::start_data_table_header_row();
  961:     my $loop = 0;
  962:     while ($loop < 2) {
  963: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
  964: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
  965: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
  966: 	    foreach my $part (sort(@$partlist)) {
  967: 		my $display_part=
  968: 		    &get_display_part((split(/_/,$part))[0],$symb);
  969: 		$gradeTable.=
  970: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
  971: 	    }
  972: 	} elsif ($submitonly eq 'queued') {
  973: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
  974: 	}
  975: 	$loop++;
  976: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
  977:     }
  978:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
  979: 
  980:     my $ctr = 0;
  981:     foreach my $student (sort 
  982: 			 {
  983: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  984: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  985: 			     }
  986: 			     return $a cmp $b;
  987: 			 }
  988: 			 (keys(%$fullname))) {
  989: 	my ($uname,$udom) = split(/:/,$student);
  990: 
  991: 	my %status = ();
  992: 
  993: 	if ($submitonly eq 'queued') {
  994: 	    my %queue_status = 
  995: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
  996: 							$udom,$uname);
  997: 	    next if (!defined($queue_status{'gradingqueue'}));
  998: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
  999: 	}
 1000: 
 1001: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1002: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
 1003: 	    my $submitted = 0;
 1004: 	    my $graded = 0;
 1005: 	    my $incorrect = 0;
 1006: 	    foreach (keys(%status)) {
 1007: 		$submitted = 1 if ($status{$_} ne 'nothing');
 1008: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
 1009: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
 1010: 		
 1011: 		my ($foo,$partid,$foo1) = split(/\./,$_);
 1012: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 1013: 		    $submitted = 0;
 1014: 		    my ($part)=split(/\./,$partid);
 1015: 		    $gradeTable.='<input type="hidden" name="'.
 1016: 			$student.':'.$part.':submitted_by" value="'.
 1017: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
 1018: 		}
 1019: 	    }
 1020: 	    
 1021: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 1022: 				     $submitonly eq 'incorrect' ||
 1023: 				     $submitonly eq 'graded'));
 1024: 	    next if (!$graded && ($submitonly eq 'graded'));
 1025: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 1026: 	}
 1027: 
 1028: 	$ctr++;
 1029: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
 1030:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
 1031: 	if ( $perm{'vgr'} eq 'F' ) {
 1032: 	    if ($ctr%2 ==1) {
 1033: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
 1034: 	    }
 1035: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
 1036:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
 1037:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
 1038: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
 1039: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
 1040: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
 1041: 
 1042: 	    if ($submitonly ne 'all') {
 1043: 		foreach (sort(keys(%status))) {
 1044: 		    next if ($_ =~ /^resource.*?submitted_by$/);
 1045: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
 1046: 		}
 1047: 	    }
 1048: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
 1049: 	    if ($ctr%2 ==0) {
 1050: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
 1051: 	    }
 1052: 	}
 1053:     }
 1054:     if ($ctr%2 ==1) {
 1055: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
 1056: 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1057: 		foreach (@$partlist) {
 1058: 		    $gradeTable.='<td>&nbsp;</td>';
 1059: 		}
 1060: 	    } elsif ($submitonly eq 'queued') {
 1061: 		$gradeTable.='<td>&nbsp;</td>';
 1062: 	    }
 1063: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
 1064:     }
 1065: 
 1066:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
 1067:         '<input type="button" '.
 1068:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
 1069:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
 1070:     if ($ctr == 0) {
 1071: 	my $num_students=(scalar(keys(%$fullname)));
 1072: 	if ($num_students eq 0) {
 1073: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
 1074: 	} else {
 1075: 	    my $submissions='submissions';
 1076: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
 1077: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
 1078: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
 1079: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
 1080: 		&mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
 1081: 		    $num_students).
 1082: 		'</span><br />';
 1083: 	}
 1084:     } elsif ($ctr == 1) {
 1085: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
 1086:     }
 1087:     $request->print($gradeTable);
 1088:     return '';
 1089: }
 1090: 
 1091: #---- Called from the listStudents routine
 1092: 
 1093: sub check_script {
 1094:     my ($form, $type)=@_;
 1095:     my $chkallscript= &Apache::lonhtmlcommon::scripttag('
 1096:     function checkall() {
 1097:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1098:             ele = document.forms.'.$form.'.elements[i];
 1099:             if (ele.name == "'.$type.'") {
 1100:             document.forms.'.$form.'.elements[i].checked=true;
 1101:                                        }
 1102:         }
 1103:     }
 1104: 
 1105:     function checksec() {
 1106:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1107:             ele = document.forms.'.$form.'.elements[i];
 1108:            string = document.forms.'.$form.'.chksec.value;
 1109:            if
 1110:           (ele.value.indexOf(":::SECTION"+string)>0) {
 1111:               document.forms.'.$form.'.elements[i].checked=true;
 1112:             }
 1113:         }
 1114:     }
 1115: 
 1116: 
 1117:     function uncheckall() {
 1118:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1119:             ele = document.forms.'.$form.'.elements[i];
 1120:             if (ele.name == "'.$type.'") {
 1121:             document.forms.'.$form.'.elements[i].checked=false;
 1122:                                        }
 1123:         }
 1124:     }
 1125: 
 1126: '."\n");
 1127:     return $chkallscript;
 1128: }
 1129: 
 1130: sub check_buttons {
 1131:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
 1132:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
 1133:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
 1134:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
 1135:     return $buttons;
 1136: }
 1137: 
 1138: #     Displays the submissions for one student or a group of students
 1139: sub processGroup {
 1140:     my ($request,$symb)  = @_;
 1141:     my $ctr        = 0;
 1142:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1143:     my $total      = scalar(@stuchecked)-1;
 1144: 
 1145:     foreach my $student (@stuchecked) {
 1146: 	my ($uname,$udom,$fullname) = split(/:/,$student);
 1147: 	$env{'form.student'}        = $uname;
 1148: 	$env{'form.userdom'}        = $udom;
 1149: 	$env{'form.fullname'}       = $fullname;
 1150: 	&submission($request,$ctr,$total,$symb);
 1151: 	$ctr++;
 1152:     }
 1153:     return '';
 1154: }
 1155: 
 1156: #------------------------------------------------------------------------------------
 1157: #
 1158: #-------------------------- Next few routines handles grading by student, essentially
 1159: #                           handles essay response type problem/part
 1160: #
 1161: #--- Javascript to handle the submission page functionality ---
 1162: sub sub_page_js {
 1163:     my $request = shift;
 1164: 	    my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 1165:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1166:     function updateRadio(formname,id,weight) {
 1167: 	var gradeBox = formname["GD_BOX"+id];
 1168: 	var radioButton = formname["RADVAL"+id];
 1169: 	var oldpts = formname["oldpts"+id].value;
 1170: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
 1171: 	gradeBox.value = pts;
 1172: 	var resetbox = false;
 1173: 	if (isNaN(pts) || pts < 0) {
 1174: 	    alert("$alertmsg"+pts);
 1175: 	    for (var i=0; i<radioButton.length; i++) {
 1176: 		if (radioButton[i].checked) {
 1177: 		    gradeBox.value = i;
 1178: 		    resetbox = true;
 1179: 		}
 1180: 	    }
 1181: 	    if (!resetbox) {
 1182: 		formtextbox.value = "";
 1183: 	    }
 1184: 	    return;
 1185: 	}
 1186: 
 1187: 	if (pts > weight) {
 1188: 	    var resp = confirm("You entered a value ("+pts+
 1189: 			       ") greater than the weight for the part. Accept?");
 1190: 	    if (resp == false) {
 1191: 		gradeBox.value = oldpts;
 1192: 		return;
 1193: 	    }
 1194: 	}
 1195: 
 1196: 	for (var i=0; i<radioButton.length; i++) {
 1197: 	    radioButton[i].checked=false;
 1198: 	    if (pts == i && pts != "") {
 1199: 		radioButton[i].checked=true;
 1200: 	    }
 1201: 	}
 1202: 	updateSelect(formname,id);
 1203: 	formname["stores"+id].value = "0";
 1204:     }
 1205: 
 1206:     function writeBox(formname,id,pts) {
 1207: 	var gradeBox = formname["GD_BOX"+id];
 1208: 	if (checkSolved(formname,id) == 'update') {
 1209: 	    gradeBox.value = pts;
 1210: 	} else {
 1211: 	    var oldpts = formname["oldpts"+id].value;
 1212: 	    gradeBox.value = oldpts;
 1213: 	    var radioButton = formname["RADVAL"+id];
 1214: 	    for (var i=0; i<radioButton.length; i++) {
 1215: 		radioButton[i].checked=false;
 1216: 		if (i == oldpts) {
 1217: 		    radioButton[i].checked=true;
 1218: 		}
 1219: 	    }
 1220: 	}
 1221: 	formname["stores"+id].value = "0";
 1222: 	updateSelect(formname,id);
 1223: 	return;
 1224:     }
 1225: 
 1226:     function clearRadBox(formname,id) {
 1227: 	if (checkSolved(formname,id) == 'noupdate') {
 1228: 	    updateSelect(formname,id);
 1229: 	    return;
 1230: 	}
 1231: 	gradeSelect = formname["GD_SEL"+id];
 1232: 	for (var i=0; i<gradeSelect.length; i++) {
 1233: 	    if (gradeSelect[i].selected) {
 1234: 		var selectx=i;
 1235: 	    }
 1236: 	}
 1237: 	var stores = formname["stores"+id];
 1238: 	if (selectx == stores.value) { return };
 1239: 	var gradeBox = formname["GD_BOX"+id];
 1240: 	gradeBox.value = "";
 1241: 	var radioButton = formname["RADVAL"+id];
 1242: 	for (var i=0; i<radioButton.length; i++) {
 1243: 	    radioButton[i].checked=false;
 1244: 	}
 1245: 	stores.value = selectx;
 1246:     }
 1247: 
 1248:     function checkSolved(formname,id) {
 1249: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
 1250: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
 1251: 	    if (!reply) {return "noupdate";}
 1252: 	    formname.overRideScore.value = 'yes';
 1253: 	}
 1254: 	return "update";
 1255:     }
 1256: 
 1257:     function updateSelect(formname,id) {
 1258: 	formname["GD_SEL"+id][0].selected = true;
 1259: 	return;
 1260:     }
 1261: 
 1262: //=========== Check that a point is assigned for all the parts  ============
 1263:     function checksubmit(formname,val,total,parttot) {
 1264: 	formname.gradeOpt.value = val;
 1265: 	if (val == "Save & Next") {
 1266: 	    for (i=0;i<=total;i++) {
 1267: 		for (j=0;j<parttot;j++) {
 1268: 		    var partid = formname["partid"+i+"_"+j].value;
 1269: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1270: 			var points = formname["GD_BOX"+i+"_"+partid].value;
 1271: 			if (points == "") {
 1272: 			    var name = formname["name"+i].value;
 1273: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
 1274: 			    var resp = confirm("You did not assign a score for "+studentID+
 1275: 					       ", part "+partid+". Continue?");
 1276: 			    if (resp == false) {
 1277: 				formname["GD_BOX"+i+"_"+partid].focus();
 1278: 				return false;
 1279: 			    }
 1280: 			}
 1281: 		    }
 1282: 		    
 1283: 		}
 1284: 	    }
 1285: 	    
 1286: 	}
 1287: 	formname.submit();
 1288:     }
 1289: 
 1290: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1291:     function checkSubmitPage(formname,total) {
 1292: 	noscore = new Array(100);
 1293: 	var ptr = 0;
 1294: 	for (i=1;i<total;i++) {
 1295: 	    var partid = formname["q_"+i].value;
 1296: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1297: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1298: 		var status = formname["solved"+i+"_"+partid].value;
 1299: 		if (points == "" && status != "correct_by_student") {
 1300: 		    noscore[ptr] = i;
 1301: 		    ptr++;
 1302: 		}
 1303: 	    }
 1304: 	}
 1305: 	if (ptr != 0) {
 1306: 	    var sense = ptr == 1 ? ": " : "s: ";
 1307: 	    var prolist = "";
 1308: 	    if (ptr == 1) {
 1309: 		prolist = noscore[0];
 1310: 	    } else {
 1311: 		var i = 0;
 1312: 		while (i < ptr-1) {
 1313: 		    prolist += noscore[i]+", ";
 1314: 		    i++;
 1315: 		}
 1316: 		prolist += "and "+noscore[i];
 1317: 	    }
 1318: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1319: 	    if (resp == false) {
 1320: 		return false;
 1321: 	    }
 1322: 	}
 1323: 
 1324: 	formname.submit();
 1325:     }
 1326: SUBJAVASCRIPT
 1327: }
 1328: 
 1329: #--- javascript for essay type problem --
 1330: sub sub_page_kw_js {
 1331:     my $request = shift;
 1332:     my $iconpath = $request->dir_config('lonIconsURL');
 1333:     &commonJSfunctions($request);
 1334: 
 1335:     my $inner_js_msg_central= (<<INNERJS);
 1336: <script type="text/javascript">
 1337:     function checkInput() {
 1338:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1339:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1340:       var usrctr = document.msgcenter.usrctr.value;
 1341:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1342:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1343: 
 1344:       var msgchk = "";
 1345:       if (document.msgcenter.subchk.checked) {
 1346:          msgchk = "msgsub,";
 1347:       }
 1348:       var includemsg = 0;
 1349:       for (var i=1; i<=nmsg; i++) {
 1350:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1351:           var frmmsg = document.msgcenter["msg"+i];
 1352:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1353:           var showflg = opener.document.SCORE["shownOnce"+i];
 1354:           showflg.value = "1";
 1355:           var chkbox = document.msgcenter["msgn"+i];
 1356:           if (chkbox.checked) {
 1357:              msgchk += "savemsg"+i+",";
 1358:              includemsg = 1;
 1359:           }
 1360:       }
 1361:       if (document.msgcenter.newmsgchk.checked) {
 1362:          msgchk += "newmsg"+usrctr;
 1363:          includemsg = 1;
 1364:       }
 1365:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1366:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1367:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1368:       includemsg.value = msgchk;
 1369: 
 1370:       self.close()
 1371: 
 1372:     }
 1373: </script>
 1374: INNERJS
 1375: 
 1376:     my $inner_js_highlight_central= (<<INNERJS);
 1377: <script type="text/javascript">
 1378:     function updateChoice(flag) {
 1379:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1380:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1381:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1382:       opener.document.SCORE.refresh.value = "on";
 1383:       if (opener.document.SCORE.keywords.value!=""){
 1384:          opener.document.SCORE.submit();
 1385:       }
 1386:       self.close()
 1387:     }
 1388: </script>
 1389: INNERJS
 1390: 
 1391:     my $start_page_msg_central = 
 1392:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1393: 				       {'js_ready'  => 1,
 1394: 					'only_body' => 1,
 1395: 					'bgcolor'   =>'#FFFFFF',});
 1396:     my $end_page_msg_central = 
 1397: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1398: 
 1399: 
 1400:     my $start_page_highlight_central = 
 1401:         &Apache::loncommon::start_page('Highlight Central',
 1402: 				       $inner_js_highlight_central,
 1403: 				       {'js_ready'  => 1,
 1404: 					'only_body' => 1,
 1405: 					'bgcolor'   =>'#FFFFFF',});
 1406:     my $end_page_highlight_central = 
 1407: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1408: 
 1409:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1410:     $docopen=~s/^document\.//;
 1411:     my %lt = &Apache::lonlocal::texthash(
 1412:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
 1413:                 plse => 'Please select a word or group of words from document and then click this link.',
 1414:                 adds => 'Add selection to keyword list? Edit if desired.',
 1415:                 comp => 'Compose Message for: ',
 1416:                 incl => 'Include',
 1417:                 subj => 'Subject',
 1418:                 mesa => 'Message',
 1419:                 new  => 'New',
 1420:                 save => 'Save',
 1421:                 canc => 'Cancel',
 1422:                 kehi => 'Keyword Highlight Options',
 1423:                 txtc => 'Text Color',
 1424:                 font => 'Font Size',
 1425:              );
 1426:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1427: 
 1428: //===================== Show list of keywords ====================
 1429:   function keywords(formname) {
 1430:     var nret = prompt("$lt{'keyw'}",formname.keywords.value);
 1431:     if (nret==null) return;
 1432:     formname.keywords.value = nret;
 1433: 
 1434:     if (formname.keywords.value != "") {
 1435: 	formname.refresh.value = "on";
 1436: 	formname.submit();
 1437:     }
 1438:     return;
 1439:   }
 1440: 
 1441: //===================== Script to view submitted by ==================
 1442:   function viewSubmitter(submitter) {
 1443:     document.SCORE.refresh.value = "on";
 1444:     document.SCORE.NCT.value = "1";
 1445:     document.SCORE.unamedom0.value = submitter;
 1446:     document.SCORE.submit();
 1447:     return;
 1448:   }
 1449: 
 1450: //===================== Script to add keyword(s) ==================
 1451:   function getSel() {
 1452:     if (document.getSelection) txt = document.getSelection();
 1453:     else if (document.selection) txt = document.selection.createRange().text;
 1454:     else return;
 1455:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1456:     if (cleantxt=="") {
 1457: 	alert("$lt{'plse'}");
 1458: 	return;
 1459:     }
 1460:     var nret = prompt("$lt{'adds'}",cleantxt);
 1461:     if (nret==null) return;
 1462:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1463:     if (document.SCORE.keywords.value != "") {
 1464: 	document.SCORE.refresh.value = "on";
 1465: 	document.SCORE.submit();
 1466:     }
 1467:     return;
 1468:   }
 1469: 
 1470: //====================== Script for composing message ==============
 1471:    // preload images
 1472:    img1 = new Image();
 1473:    img1.src = "$iconpath/mailbkgrd.gif";
 1474:    img2 = new Image();
 1475:    img2.src = "$iconpath/mailto.gif";
 1476: 
 1477:   function msgCenter(msgform,usrctr,fullname) {
 1478:     var Nmsg  = msgform.savemsgN.value;
 1479:     savedMsgHeader(Nmsg,usrctr,fullname);
 1480:     var subject = msgform.msgsub.value;
 1481:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1482:     re = /msgsub/;
 1483:     var shwsel = "";
 1484:     if (re.test(msgchk)) { shwsel = "checked" }
 1485:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1486:     displaySubject(checkEntities(subject),shwsel);
 1487:     for (var i=1; i<=Nmsg; i++) {
 1488: 	var testmsg = "savemsg"+i+",";
 1489: 	re = new RegExp(testmsg,"g");
 1490: 	shwsel = "";
 1491: 	if (re.test(msgchk)) { shwsel = "checked" }
 1492: 	var message = document.SCORE["savemsg"+i].value;
 1493: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1494: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1495: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1496:     }
 1497:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1498:     shwsel = "";
 1499:     re = /newmsg/;
 1500:     if (re.test(msgchk)) { shwsel = "checked" }
 1501:     newMsg(newmsg,shwsel);
 1502:     msgTail(); 
 1503:     return;
 1504:   }
 1505: 
 1506:   function checkEntities(strx) {
 1507:     if (strx.length == 0) return strx;
 1508:     var orgStr = ["&", "<", ">", '"']; 
 1509:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1510:     var counter = 0;
 1511:     while (counter < 4) {
 1512: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1513: 	counter++;
 1514:     }
 1515:     return strx;
 1516:   }
 1517: 
 1518:   function strReplace(strx, orgStr, newStr) {
 1519:     return strx.split(orgStr).join(newStr);
 1520:   }
 1521: 
 1522:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1523:     var height = 70*Nmsg+250;
 1524:     var scrollbar = "no";
 1525:     if (height > 600) {
 1526: 	height = 600;
 1527: 	scrollbar = "yes";
 1528:     }
 1529:     var xpos = (screen.width-600)/2;
 1530:     xpos = (xpos < 0) ? '0' : xpos;
 1531:     var ypos = (screen.height-height)/2-30;
 1532:     ypos = (ypos < 0) ? '0' : ypos;
 1533: 
 1534:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
 1535:     pWin.focus();
 1536:     pDoc = pWin.document;
 1537:     pDoc.$docopen;
 1538:     pDoc.write('$start_page_msg_central');
 1539: 
 1540:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1541:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1542:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;$lt{'comp'}\"+fullname+\"<\\/span><\\/h3><br /><br />");
 1543: 
 1544:     pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
 1545:     pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
 1546:     pDoc.write("<td><b>Type<\\/b><\\/td><td><b>$lt{'incl'}<\\/b><\\/td><td><b>$lt{'mesa'}<\\/td><\\/tr>");
 1547: }
 1548:     function displaySubject(msg,shwsel) {
 1549:     pDoc = pWin.document;
 1550:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1551:     pDoc.write("<td>$lt{'subj'}<\\/td>");
 1552:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1553:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
 1554: }
 1555: 
 1556:   function displaySavedMsg(ctr,msg,shwsel) {
 1557:     pDoc = pWin.document;
 1558:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1559:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
 1560:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1561:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
 1562: }
 1563: 
 1564:   function newMsg(newmsg,shwsel) {
 1565:     pDoc = pWin.document;
 1566:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1567:     pDoc.write("<td align=\\"center\\">$lt{'new'}<\\/td>");
 1568:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1569:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
 1570: }
 1571: 
 1572:   function msgTail() {
 1573:     pDoc = pWin.document;
 1574:     pDoc.write("<\\/table>");
 1575:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1576:     pDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1577:     pDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
 1578:     pDoc.write("<\\/form>");
 1579:     pDoc.write('$end_page_msg_central');
 1580:     pDoc.close();
 1581: }
 1582: 
 1583: //====================== Script for keyword highlight options ==============
 1584:   function kwhighlight() {
 1585:     var kwclr    = document.SCORE.kwclr.value;
 1586:     var kwsize   = document.SCORE.kwsize.value;
 1587:     var kwstyle  = document.SCORE.kwstyle.value;
 1588:     var redsel = "";
 1589:     var grnsel = "";
 1590:     var blusel = "";
 1591:     if (kwclr=="red")   {var redsel="checked"};
 1592:     if (kwclr=="green") {var grnsel="checked"};
 1593:     if (kwclr=="blue")  {var blusel="checked"};
 1594:     var sznsel = "";
 1595:     var sz1sel = "";
 1596:     var sz2sel = "";
 1597:     if (kwsize=="0")  {var sznsel="checked"};
 1598:     if (kwsize=="+1") {var sz1sel="checked"};
 1599:     if (kwsize=="+2") {var sz2sel="checked"};
 1600:     var synsel = "";
 1601:     var syisel = "";
 1602:     var sybsel = "";
 1603:     if (kwstyle=="")    {var synsel="checked"};
 1604:     if (kwstyle=="<i>") {var syisel="checked"};
 1605:     if (kwstyle=="<b>") {var sybsel="checked"};
 1606:     highlightCentral();
 1607:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
 1608:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
 1609:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
 1610:     highlightend();
 1611:     return;
 1612:   }
 1613: 
 1614:   function highlightCentral() {
 1615: //    if (window.hwdWin) window.hwdWin.close();
 1616:     var xpos = (screen.width-400)/2;
 1617:     xpos = (xpos < 0) ? '0' : xpos;
 1618:     var ypos = (screen.height-330)/2-30;
 1619:     ypos = (ypos < 0) ? '0' : ypos;
 1620: 
 1621:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1622:     hwdWin.focus();
 1623:     var hDoc = hwdWin.document;
 1624:     hDoc.$docopen;
 1625:     hDoc.write('$start_page_highlight_central');
 1626:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1627:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;$lt{'kehi'}<\\/span><\\/h3><br /><br />");
 1628: 
 1629:     hDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
 1630:     hDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
 1631:     hDoc.write("<td><b>$lt{'txtc'}<\\/b><\\/td><td><b>$lt{'font'}<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
 1632:   }
 1633: 
 1634:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1635:     var hDoc = hwdWin.document;
 1636:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1637:     hDoc.write("<td align=\\"left\\">");
 1638:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
 1639:     hDoc.write("<td align=\\"left\\">");
 1640:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
 1641:     hDoc.write("<td align=\\"left\\">");
 1642:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
 1643:     hDoc.write("<\\/tr>");
 1644:   }
 1645: 
 1646:   function highlightend() { 
 1647:     var hDoc = hwdWin.document;
 1648:     hDoc.write("<\\/table>");
 1649:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1650:     hDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
 1651:     hDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
 1652:     hDoc.write("<\\/form>");
 1653:     hDoc.write('$end_page_highlight_central');
 1654:     hDoc.close();
 1655:   }
 1656: 
 1657: SUBJAVASCRIPT
 1658: }
 1659: 
 1660: sub get_increment {
 1661:     my $increment = $env{'form.increment'};
 1662:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1663:         $increment != .1) {
 1664:         $increment = 1;
 1665:     }
 1666:     return $increment;
 1667: }
 1668: 
 1669: sub gradeBox_start {
 1670:     return (
 1671:         &Apache::loncommon::start_data_table()
 1672:        .&Apache::loncommon::start_data_table_header_row()
 1673:        .'<th>'.&mt('Part').'</th>'
 1674:        .'<th>'.&mt('Points').'</th>'
 1675:        .'<th>&nbsp;</th>'
 1676:        .'<th>'.&mt('Assign Grade').'</th>'
 1677:        .'<th>'.&mt('Weight').'</th>'
 1678:        .'<th>'.&mt('Grade Status').'</th>'
 1679:        .&Apache::loncommon::end_data_table_header_row()
 1680:     );
 1681: }
 1682: 
 1683: sub gradeBox_end {
 1684:     return (
 1685:         &Apache::loncommon::end_data_table()
 1686:     );
 1687: }
 1688: #--- displays the grading box, used in essay type problem and grading by page/sequence
 1689: sub gradeBox {
 1690:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 1691:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1692: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 1693:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 1694:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
 1695:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
 1696:     $wgt       = ($wgt > 0 ? $wgt : '1');
 1697:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 1698: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 1699:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 1700:     my $display_part= &get_display_part($partid,$symb);
 1701:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 1702: 				       [$partid]);
 1703:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 1704:     if ($last_resets{$partid}) {
 1705:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 1706:     }
 1707:     $result.=&Apache::loncommon::start_data_table_row();
 1708:     my $ctr = 0;
 1709:     my $thisweight = 0;
 1710:     my $increment = &get_increment();
 1711: 
 1712:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 1713:     while ($thisweight<=$wgt) {
 1714: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 1715:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 1716: 	    $thisweight.')" value="'.$thisweight.'" '.
 1717: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 1718: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 1719:         $thisweight += $increment;
 1720: 	$ctr++;
 1721:     }
 1722:     $radio.='</tr></table>';
 1723: 
 1724:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 1725: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 1726: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 1727: 	$wgt.')" /></td>'."\n";
 1728:     $line.='<td>/'.$wgt.' '.$wgtmsg.
 1729: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 1730: 	' </td>'."\n";
 1731:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
 1732: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 1733:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 1734: 	$line.='<option></option>'.
 1735: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
 1736:     } else {
 1737: 	$line.='<option selected="selected"></option>'.
 1738: 	    '<option value="excused" >'.&mt('excused').'</option>';
 1739:     }
 1740:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
 1741: 
 1742: 
 1743:     $result .= 
 1744: 	    '<td>'.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
 1745:     $result.=&Apache::loncommon::end_data_table_row();
 1746:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 1747: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 1748: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 1749: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 1750:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 1751:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 1752:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 1753:         $aggtries.'" />'."\n";
 1754:     my $res_error;
 1755:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
 1756:     if ($res_error) {
 1757:         return &navmap_errormsg();
 1758:     }
 1759:     return $result;
 1760: }
 1761: 
 1762: sub handback_box {
 1763:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
 1764:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error_pointer);
 1765:     my (@respids);
 1766:     my @part_response_id = &flatten_responseType($responseType);
 1767:     foreach my $part_response_id (@part_response_id) {
 1768:     	my ($part,$resp) = @{ $part_response_id };
 1769:         if ($part eq $partid) {
 1770:             push(@respids,$resp);
 1771:         }
 1772:     }
 1773:     my $result;
 1774:     foreach my $respid (@respids) {
 1775: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 1776: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 1777: 	next if (!@$files);
 1778: 	my $file_counter = 0;
 1779: 	foreach my $file (@$files) {
 1780: 	    if ($file =~ /\/portfolio\//) {
 1781:                 $file_counter++;
 1782:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 1783:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
 1784:     	        $file_disp = "$name.$ext";
 1785:     	        $file = $file_path.$file_disp;
 1786:     	        $result.=&mt('Return commented version of [_1] to student.',
 1787:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 1788:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 1789:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
 1790: 	    }
 1791: 	}
 1792:         if ($file_counter) {
 1793:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
 1794:                        '<span class="LC_info">'.
 1795:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
 1796:         }
 1797:     }
 1798:     return $result;    
 1799: }
 1800: 
 1801: sub show_problem {
 1802:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 1803:     my $rendered;
 1804:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 1805:     &Apache::lonxml::remember_problem_counter();
 1806:     if ($mode eq 'both' or $mode eq 'text') {
 1807: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 1808: 						       $env{'request.course.id'},
 1809: 						       undef,\%form);
 1810:     }
 1811:     if ($removeform) {
 1812: 	$rendered=~s|<form(.*?)>||g;
 1813: 	$rendered=~s|</form>||g;
 1814: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 1815:     }
 1816:     my $companswer;
 1817:     if ($mode eq 'both' or $mode eq 'answer') {
 1818: 	&Apache::lonxml::restore_problem_counter();
 1819: 	$companswer=
 1820: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 1821: 						    $env{'request.course.id'},
 1822: 						    %form);
 1823:     }
 1824:     if ($removeform) {
 1825: 	$companswer=~s|<form(.*?)>||g;
 1826: 	$companswer=~s|</form>||g;
 1827: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 1828:     }
 1829:     $rendered=
 1830:         '<div class="LC_Box">'
 1831:        .'<h3 class="LC_hcell">'.&mt('View of the problem').'</h3>'
 1832:        .$rendered
 1833:        .'</div>';
 1834:     $companswer=
 1835:         '<div class="LC_Box">'
 1836:        .'<h3 class="LC_hcell">'.&mt('Correct answer').'</h3>'
 1837:        .$companswer
 1838:        .'</div>';
 1839:     my $result;
 1840:     if ($mode eq 'both') {
 1841:         $result=$rendered.$companswer;
 1842:     } elsif ($mode eq 'text') {
 1843:         $result=$rendered;
 1844:     } elsif ($mode eq 'answer') {
 1845:         $result=$companswer;
 1846:     }
 1847:     return $result;
 1848: }
 1849: 
 1850: sub files_exist {
 1851:     my ($r, $symb) = @_;
 1852:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1853: 
 1854:     foreach my $student (@students) {
 1855:         my ($uname,$udom,$fullname) = split(/:/,$student);
 1856:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 1857: 					      $udom,$uname);
 1858:         my ($string,$timestamp)= &get_last_submission(\%record);
 1859:         foreach my $submission (@$string) {
 1860:             my ($partid,$respid) =
 1861: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 1862:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 1863: 					   \%record);
 1864:             return 1 if (@$files);
 1865:         }
 1866:     }
 1867:     return 0;
 1868: }
 1869: 
 1870: sub download_all_link {
 1871:     my ($r,$symb) = @_;
 1872:     unless (&files_exist($r, $symb)) {
 1873:        $r->print(&mt('There are currently no submitted documents.'));
 1874:        return;
 1875:     }
 1876: 
 1877:     my $all_students = 
 1878: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 1879: 
 1880:     my $parts =
 1881: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 1882: 
 1883:     my $identifier = &Apache::loncommon::get_cgi_id();
 1884:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 1885:                              'cgi.'.$identifier.'.symb' => $symb,
 1886:                              'cgi.'.$identifier.'.parts' => $parts,});
 1887:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 1888: 	      &mt('Download All Submitted Documents').'</a>');
 1889:     return;
 1890: }
 1891: 
 1892: sub submit_download_link {
 1893:     my ($request,$symb) = @_;
 1894:     if (!$symb) { return ''; }
 1895: #FIXME: Figure out which type of problem this is and provide appropriate download
 1896:     &download_all_link($request,$symb);
 1897: }
 1898: 
 1899: sub build_section_inputs {
 1900:     my $section_inputs;
 1901:     if ($env{'form.section'} eq '') {
 1902:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 1903:     } else {
 1904:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 1905:         foreach my $section (@sections) {
 1906:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 1907:         }
 1908:     }
 1909:     return $section_inputs;
 1910: }
 1911: 
 1912: # --------------------------- show submissions of a student, option to grade 
 1913: sub submission {
 1914:     my ($request,$counter,$total,$symb) = @_;
 1915:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 1916:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 1917:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 1918:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 1919: 
 1920:     my $probtitle=&Apache::lonnet::gettitle($symb); 
 1921:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 1922: 
 1923:     if (!&canview($usec)) {
 1924: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
 1925: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
 1926: 			$env{'request.course.id'}.')</span>');
 1927: 	return;
 1928:     }
 1929: 
 1930:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 1931:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 1932:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 1933:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 1934:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1935: 	'" src="'.$request->dir_config('lonIconsURL').
 1936: 	'/check.gif" height="16" border="0" />';
 1937: 
 1938:     my %old_essays;
 1939:     # header info
 1940:     if ($counter == 0) {
 1941: 	&sub_page_js($request);
 1942: 	&sub_page_kw_js($request);
 1943: 
 1944: 	# option to display problem, only once else it cause problems 
 1945:         # with the form later since the problem has a form.
 1946: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 1947: 	    my $mode;
 1948: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 1949: 		$mode='both';
 1950: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 1951: 		$mode='text';
 1952: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 1953: 		$mode='answer';
 1954: 	    }
 1955: 	    &Apache::lonxml::clear_problem_counter();
 1956: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 1957: 	}
 1958: 
 1959: 	# kwclr is the only variable that is guaranteed to be non blank 
 1960:         # if this subroutine has been called once.
 1961: 	my %keyhash = ();
 1962: #	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
 1963:         if (1) {
 1964: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 1965: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 1966: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 1967: 
 1968: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 1969: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 1970: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 1971: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 1972: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 1973: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
 1974: 		$keyhash{$symb.'_subject'} : $probtitle;
 1975: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 1976: 	}
 1977: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 1978: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 1979: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 1980: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 1981: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 1982: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 1983: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 1984: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 1985: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 1986: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 1987: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 1988: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 1989: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 1990: 			&build_section_inputs().
 1991: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 1992: 			'<input type="hidden" name="NCT"'.
 1993: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 1994: #	if ($env{'form.handgrade'} eq 'yes') {
 1995:         if (1) {
 1996: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 1997: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 1998: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 1999: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
 2000: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 2001: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 2002: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 2003: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
 2004: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
 2005: 	    }
 2006: 	}
 2007: 	
 2008: 	my ($cts,$prnmsg) = (1,'');
 2009: 	while ($cts <= $env{'form.savemsgN'}) {
 2010: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 2011: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 2012: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 2013: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 2014: 		'" />'."\n".
 2015: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 2016: 	    $cts++;
 2017: 	}
 2018: 	$request->print($prnmsg);
 2019: 
 2020: #	if ($env{'form.handgrade'} eq 'yes') {
 2021:         if (1) {
 2022: 
 2023:             my %lt = &Apache::lonlocal::texthash(
 2024:                           keyw => 'Keyword Options',
 2025:                           list => 'List',
 2026:                           past => 'Paste Selection to List',
 2027:                           high => 'Hightlight Attribute',
 2028:                      );    
 2029: #
 2030: # Print out the keyword options line
 2031: #
 2032: 	    $request->print(<<KEYWORDS);
 2033: <br /><b>$lt{'keyw'}:</b>&nbsp;
 2034: <a href="javascript:keywords(document.SCORE);" target="_self">$lt{'list'}</a>&nbsp; &nbsp;
 2035: <a href="#" onmousedown="javascript:getSel(); return false"
 2036:  CLASS="page">$lt{'past'}</a>&nbsp; &nbsp;
 2037: <a href="javascript:kwhighlight();" target="_self">$lt{'high'}</a><br /><br />
 2038: KEYWORDS
 2039: #
 2040: # Load the other essays for similarity check
 2041: #
 2042:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 2043: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 2044: 	    $apath=&escape($apath);
 2045: 	    $apath=~s/\W/\_/gs;
 2046: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
 2047:         }
 2048:     }
 2049: 
 2050: # This is where output for one specific student would start
 2051:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
 2052:     $request->print(
 2053:         "\n\n"
 2054:        .'<div class="LC_grade_show_user'.$add_class.'">'
 2055:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
 2056:        ."\n"
 2057:     );
 2058: 
 2059:     # Show additional functions if allowed
 2060:     if ($perm{'vgr'}) {
 2061:         $request->print(
 2062:             &Apache::loncommon::track_student_link(
 2063:                 &mt('View recent activity'),
 2064:                 $uname,$udom,'check')
 2065:            .' '
 2066:         );
 2067:     }
 2068:     if ($perm{'opa'}) {
 2069:         $request->print(
 2070:             &Apache::loncommon::pprmlink(
 2071:                 &mt('Set/Change parameters'),
 2072:                 $uname,$udom,$symb,'check'));
 2073:     }
 2074: 
 2075:     # Show Problem
 2076:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2077: 	my $mode;
 2078: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2079: 	    $mode='both';
 2080: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2081: 	    $mode='text';
 2082: 	} elsif ($env{'form.vAns'} eq 'all') {
 2083: 	    $mode='answer';
 2084: 	}
 2085: 	&Apache::lonxml::clear_problem_counter();
 2086: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2087:     }
 2088: 
 2089:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2090:     my $res_error;
 2091:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2092:     if ($res_error) {
 2093:         $request->print(&navmap_errormsg());
 2094:         return;
 2095:     }
 2096: 
 2097:     # Display student info
 2098:     $request->print(($counter == 0 ? '' : '<br />'));
 2099: 
 2100:     my $result='<div class="LC_Box">'
 2101:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
 2102:     $result.='<input type="hidden" name="name'.$counter.
 2103:              '" value="'.$env{'form.fullname'}.'" />'."\n";
 2104: #    if ($env{'form.handgrade'} eq 'no') {
 2105:     if (1) {
 2106:         $result.='<p class="LC_info">'
 2107:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
 2108:                 ."</p>\n";
 2109:     }
 2110: 
 2111:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
 2112:     my $fullname;
 2113:     my $col_fullnames = [];
 2114: #    if ($env{'form.handgrade'} eq 'yes') {
 2115:     if (1) {
 2116: 	(my $sub_result,$fullname,$col_fullnames)=
 2117: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2118: 				 $counter);
 2119: 	$result.=$sub_result;
 2120:     }
 2121:     $request->print($result."\n");
 2122: 
 2123:     # print student answer/submission
 2124:     # Options are (1) Handgraded submission only
 2125:     #             (2) Last submission, includes submission that is not handgraded 
 2126:     #                  (for multi-response type part)
 2127:     #             (3) Last submission plus the parts info
 2128:     #             (4) The whole record for this student
 2129:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
 2130: 	my ($string,$timestamp)= &get_last_submission(\%record);
 2131: 	
 2132: 	my $lastsubonly;
 2133: 
 2134:         if ($$timestamp eq '') {
 2135:             $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
 2136:         } else {
 2137:             $lastsubonly =
 2138:                 '<div class="LC_grade_submissions_body">'
 2139:                .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
 2140: 
 2141: 	    my %seenparts;
 2142: 	    my @part_response_id = &flatten_responseType($responseType);
 2143: 	    foreach my $part (@part_response_id) {
 2144: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
 2145: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
 2146: 
 2147: 		my ($partid,$respid) = @{ $part };
 2148: 		my $display_part=&get_display_part($partid,$symb);
 2149: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2150: 		    if (exists($seenparts{$partid})) { next; }
 2151: 		    $seenparts{$partid}=1;
 2152: 		    my $submitby='<b>Part:</b> '.$display_part.
 2153: 			' <b>Collaborative submission by:</b> '.
 2154: 			'<a href="javascript:viewSubmitter(\''.
 2155: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
 2156: 			'\');" target="_self">'.
 2157: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
 2158: 		    $request->print($submitby);
 2159: 		    next;
 2160: 		}
 2161: 		my $responsetype = $responseType->{$partid}->{$respid};
 2162: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
 2163:                     $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
 2164:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2165:                         ' <span class="LC_internal_info">'.
 2166:                         '('.&mt('Response ID: [_1]',$respid).')'.
 2167:                         '</span>&nbsp; &nbsp;'.
 2168: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
 2169: 		    next;
 2170: 		}
 2171: 		foreach my $submission (@$string) {
 2172: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2173: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2174: 		    my ($ressub,$hide,$subval) = split(/:/,$submission,3);
 2175: 		    # Similarity check
 2176: 		    my $similar='';
 2177:                     my ($type,$trial,$rndseed);
 2178:                     if ($hide eq 'rand') {
 2179:                         $type = 'randomizetry';
 2180:                         $trial = $record{"resource.$partid.tries"};
 2181:                         $rndseed = $record{"resource.$partid.rndseed"};
 2182:                     }
 2183: 		    if($env{'form.checkPlag'}){
 2184: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2185: 			    &most_similar($uname,$udom,$subval,\%old_essays);
 2186: 			if ($osim) {
 2187: 			    $osim=int($osim*100.0);
 2188: 			    my %old_course_desc = 
 2189: 				&Apache::lonnet::coursedescription($ocrsid,
 2190: 								   {'one_time' => 1});
 2191: 
 2192:                             if ($hide eq 'anon') {
 2193:                                 $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
 2194:                                          &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
 2195:                             } else {
 2196: 			        $similar="<hr /><h3><span class=\"LC_warning\">".
 2197: 				    &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
 2198: 				        $osim,
 2199: 				        &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
 2200: 				        $old_course_desc{'description'},
 2201: 				        $old_course_desc{'num'},
 2202: 				        $old_course_desc{'domain'}).
 2203: 				    '</span></h3><blockquote><i>'.
 2204: 				    &keywords_highlight($oessay).
 2205: 				    '</i></blockquote><hr />';
 2206:                             }
 2207: 			}
 2208: 		    }
 2209: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom,
 2210:                                          undef,$type,$trial,$rndseed);
 2211: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
 2212: 			($env{'form.lastSub'} eq 'hdgrade' && 
 2213: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
 2214: 			my $display_part=&get_display_part($partid,$symb);
 2215:                         $lastsubonly.='<div class="LC_grade_submission_part">'.
 2216:                             '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2217:                             ' <span class="LC_internal_info">'.
 2218:                             '('.&mt('Response ID: [_1]',$respid).')'.
 2219:                             '</span>&nbsp; &nbsp;';
 2220: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2221: 			if (@$files) {
 2222:                             if ($hide eq 'anon') {
 2223:                                 $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
 2224:                             } else {
 2225:                                 $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
 2226:                                 foreach my $file (@$files) {
 2227:                                     &Apache::lonnet::allowuploaded('/adm/grades',$file);
 2228:                                     $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" /> '.$file.'</a>';
 2229:                                 }
 2230:                             }
 2231: 			    $lastsubonly.='<br />';
 2232: 			}
 2233:                         if ($hide eq 'anon') {
 2234:                             $lastsubonly.='<b>'.&mt('Anonymous Survey').'</b>'; 
 2235:                         } else {
 2236: 			    $lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
 2237: 			        &cleanRecord($subval,$responsetype,$symb,$partid,
 2238: 					     $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
 2239:                         }
 2240: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2241: 			$lastsubonly.='</div>';
 2242: 		    }
 2243: 		}
 2244: 	    }
 2245: 	    $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
 2246: 	}
 2247: 	$request->print($lastsubonly);
 2248:    } elsif ($env{'form.lastSub'} eq 'datesub') {
 2249:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2250: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2251:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2252: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2253: 								 $env{'request.course.id'},
 2254: 								 $last,'.submission',
 2255: 								 'Apache::grades::keywords_highlight'));
 2256:     }
 2257:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2258: 	.$udom.'" />'."\n");
 2259:     # return if view submission with no grading option
 2260:     if (!&canmodify($usec)) {
 2261: 	$request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
 2262: 	return;
 2263:     } else {
 2264: 	$request->print('</div>'."\n");
 2265:     }
 2266: 
 2267:     # essay grading message center
 2268: #    if ($env{'form.handgrade'} eq 'yes') {
 2269:     if (1) {
 2270: 	my $result='<div class="LC_grade_message_center">';
 2271:     
 2272: 	$result.='<div class="LC_grade_message_center_header">'.
 2273: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
 2274: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2275: 	my $msgfor = $givenn.' '.$lastname;
 2276: 	if (scalar(@$col_fullnames) > 0) {
 2277: 	    my $lastone = pop(@$col_fullnames);
 2278: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2279: 	}
 2280: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2281: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2282: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
 2283: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2284: 	    ',\''.$msgfor.'\');" target="_self">'.
 2285: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
 2286: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2287: 	    '<img src="'.$request->dir_config('lonIconsURL').
 2288: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
 2289: 	    '<br />&nbsp;('.
 2290: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
 2291: 	$result.='</div></div>';
 2292: 	$request->print($result);
 2293:     }
 2294: 
 2295:     my %seen = ();
 2296:     my @partlist;
 2297:     my @gradePartRespid;
 2298:     my @part_response_id = &flatten_responseType($responseType);
 2299:     $request->print(
 2300:         '<div class="LC_Box">'
 2301:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
 2302:     );
 2303:     $request->print(&gradeBox_start());
 2304:     foreach my $part_response_id (@part_response_id) {
 2305:     	my ($partid,$respid) = @{ $part_response_id };
 2306: 	my $part_resp = join('_',@{ $part_response_id });
 2307: 	next if ($seen{$partid} > 0);
 2308: 	$seen{$partid}++;
 2309: 	next if ($$handgrade{$part_resp} ne 'yes' 
 2310: 		 && $env{'form.lastSub'} eq 'hdgrade');
 2311: 	push(@partlist,$partid);
 2312: 	push(@gradePartRespid,$partid.'.'.$respid);
 2313: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2314:     }
 2315:     $request->print(&gradeBox_end()); # </div>
 2316:     $request->print('</div>');
 2317: 
 2318:     $request->print('<div class="LC_grade_info_links">');
 2319:     $request->print('</div>');
 2320: 
 2321:     $result='<input type="hidden" name="partlist'.$counter.
 2322: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2323:     $result.='<input type="hidden" name="gradePartRespid'.
 2324: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2325:     my $ctr = 0;
 2326:     while ($ctr < scalar(@partlist)) {
 2327: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2328: 	    $partlist[$ctr].'" />'."\n";
 2329: 	$ctr++;
 2330:     }
 2331:     $request->print($result.''."\n");
 2332: 
 2333: # Done with printing info for one student
 2334: 
 2335:     $request->print('</div>');#LC_grade_show_user
 2336: 
 2337: 
 2338:     # print end of form
 2339:     if ($counter == $total) {
 2340:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
 2341: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2342: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
 2343: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2344: 	my $ntstu ='<select name="NTSTU">'.
 2345: 	    '<option>1</option><option>2</option>'.
 2346: 	    '<option>3</option><option>5</option>'.
 2347: 	    '<option>7</option><option>10</option></select>'."\n";
 2348: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2349: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2350:         $endform.=&mt('[_1]student(s)',$ntstu);
 2351: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2352: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2353: 	    '<input type="button" value="'.&mt('Next').'" '.
 2354: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2355:         $endform.='<span class="LC_warning">'.
 2356:                   &mt('(Next and Previous (student) do not save the scores.)').
 2357:                   '</span>'."\n" ;
 2358:         $endform.="<input type='hidden' value='".&get_increment().
 2359:             "' name='increment' />";
 2360: 	$endform.='</td></tr></table></form>';
 2361: 	$request->print($endform);
 2362:     }
 2363:     return '';
 2364: }
 2365: 
 2366: sub check_collaborators {
 2367:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2368:     my ($result,@col_fullnames);
 2369:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2370:     foreach my $part (keys(%$handgrade)) {
 2371: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2372: 					'.maxcollaborators',
 2373: 					$symb,$udom,$uname);
 2374: 	next if ($ncol <= 0);
 2375: 	$part =~ s/\_/\./g;
 2376: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2377: 	my (@good_collaborators, @bad_collaborators);
 2378: 	foreach my $possible_collaborator
 2379: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2380: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2381: 	    next if ($possible_collaborator eq '');
 2382: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
 2383: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2384: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2385: 	    # Doing this grep allows 'fuzzy' specification
 2386: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2387: 			       keys(%$classlist));
 2388: 	    if (! scalar(@matches)) {
 2389: 		push(@bad_collaborators, $possible_collaborator);
 2390: 	    } else {
 2391: 		push(@good_collaborators, @matches);
 2392: 	    }
 2393: 	}
 2394: 	if (scalar(@good_collaborators) != 0) {
 2395: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
 2396: 	    foreach my $name (@good_collaborators) {
 2397: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2398: 		push(@col_fullnames, $givenn.' '.$lastname);
 2399: 		$result.='<li>'.$fullname->{$name}.'</li>';
 2400: 	    }
 2401: 	    $result.='</ol><br />'."\n";
 2402: 	    my ($part)=split(/\./,$part);
 2403: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2404: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2405: 		"\n";
 2406: 	}
 2407: 	if (scalar(@bad_collaborators) > 0) {
 2408: 	    $result.='<div class="LC_warning">';
 2409: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2410: 	    $result .= '</div>';
 2411: 	}         
 2412: 	if (scalar(@bad_collaborators > $ncol)) {
 2413: 	    $result .= '<div class="LC_warning">';
 2414: 	    $result .= &mt('This student has submitted too many '.
 2415: 		'collaborators.  Maximum is [_1].',$ncol);
 2416: 	    $result .= '</div>';
 2417: 	}
 2418:     }
 2419:     return ($result,$fullname,\@col_fullnames);
 2420: }
 2421: 
 2422: #--- Retrieve the last submission for all the parts
 2423: sub get_last_submission {
 2424:     my ($returnhash)=@_;
 2425:     my (@string,$timestamp,%lasthidden);
 2426:     if ($$returnhash{'version'}) {
 2427: 	my %lasthash=();
 2428: 	my ($version);
 2429: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2430: 	    foreach my $key (sort(split(/\:/,
 2431: 					$$returnhash{$version.':keys'}))) {
 2432: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2433: 		$timestamp = 
 2434: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2435: 	    }
 2436: 	}
 2437:         my (%typeparts,%randombytry);
 2438:         my $showsurv = 
 2439:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
 2440:         foreach my $key (sort(keys(%lasthash))) {
 2441:             if ($key =~ /\.type$/) {
 2442:                 if (($lasthash{$key} eq 'anonsurvey') || 
 2443:                     ($lasthash{$key} eq 'anonsurveycred') ||
 2444:                     ($lasthash{$key} eq 'randomizetry')) {
 2445:                     my ($ign,@parts) = split(/\./,$key);
 2446:                     pop(@parts);
 2447:                     my $id = join('.',@parts);
 2448:                     if ($lasthash{$key} eq 'randomizetry') {
 2449:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
 2450:                     } else {
 2451:                         unless ($showsurv) {
 2452:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
 2453:                         }
 2454:                     }
 2455:                     delete($lasthash{$key});
 2456:                 }
 2457:             }
 2458:         }
 2459:         my @hidden = keys(%typeparts);
 2460:         my @randomize = keys(%randombytry);
 2461: 	foreach my $key (keys(%lasthash)) {
 2462: 	    next if ($key !~ /\.submission$/);
 2463:             my $hide;
 2464:             if (@hidden) {
 2465:                 foreach my $id (@hidden) {
 2466:                     if ($key =~ /^\Q$id\E/) {
 2467:                         $hide = 'anon';
 2468:                         last;
 2469:                     }
 2470:                 }
 2471:             }
 2472:             unless ($hide) {
 2473:                 if (@randomize) {
 2474:                     foreach my $id (@hidden) {
 2475:                         if ($key =~ /^\Q$id\E/) {
 2476:                             $hide = 'rand';
 2477:                             last;
 2478:                         }
 2479:                     }
 2480:                 }
 2481:             }
 2482: 	    my ($partid,$foo) = split(/submission$/,$key);
 2483: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
 2484: 		'<span class="LC_warning">Draft Copy</span> ' : '';
 2485: 	    push(@string, join(':', $key, $hide, $draft.$lasthash{$key}));
 2486: 	}
 2487:     }
 2488:     if (!@string) {
 2489: 	$string[0] =
 2490: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
 2491:     }
 2492:     return (\@string,\$timestamp);
 2493: }
 2494: 
 2495: #--- High light keywords, with style choosen by user.
 2496: sub keywords_highlight {
 2497:     my $string    = shift;
 2498:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2499:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2500:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2501:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2502:     foreach my $keyword (@keylist) {
 2503: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2504:     }
 2505:     return $string;
 2506: }
 2507: 
 2508: #--- Called from submission routine
 2509: sub processHandGrade {
 2510:     my ($request,$symb) = @_;
 2511:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2512:     my $button = $env{'form.gradeOpt'};
 2513:     my $ngrade = $env{'form.NCT'};
 2514:     my $ntstu  = $env{'form.NTSTU'};
 2515:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2516:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 2517: 
 2518:     if ($button eq 'Save & Next') {
 2519: 	my $ctr = 0;
 2520: 	while ($ctr < $ngrade) {
 2521: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 2522: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 2523: 	    if ($errorflag eq 'no_score') {
 2524: 		$ctr++;
 2525: 		next;
 2526: 	    }
 2527: 	    if ($errorflag eq 'not_allowed') {
 2528: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
 2529: 		$ctr++;
 2530: 		next;
 2531: 	    }
 2532: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 2533: 	    my ($subject,$message,$msgstatus) = ('','','');
 2534: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 2535:             my ($feedurl,$showsymb) =
 2536: 		&get_feedurl_and_symb($symb,$uname,$udom);
 2537: 	    my $messagetail;
 2538: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 2539: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 2540: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 2541: 		$subject.=' ['.$restitle.']';
 2542: 		my (@msgnum) = split(/,/,$includemsg);
 2543: 		foreach (@msgnum) {
 2544: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 2545: 		}
 2546: 		$message =&Apache::lonfeedback::clear_out_html($message);
 2547: 		if ($env{'form.withgrades'.$ctr}) {
 2548: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 2549: 		    $messagetail = " for <a href=\"".
 2550: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
 2551: 		}
 2552: 		$msgstatus = 
 2553:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 2554: 						     $message.$messagetail,
 2555:                                                      undef,$feedurl,undef,
 2556:                                                      undef,undef,$showsymb,
 2557:                                                      $restitle);
 2558: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
 2559: 				$msgstatus.'<br />');
 2560: 	    }
 2561: 	    if ($env{'form.collaborator'.$ctr}) {
 2562: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 2563: 		foreach my $collabstr (@collabstrs) {
 2564: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 2565: 		    foreach my $collaborator (@collaborators) {
 2566: 			my ($errorflag,$pts,$wgt) = 
 2567: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 2568: 					   $env{'form.unamedom'.$ctr},$part);
 2569: 			if ($errorflag eq 'not_allowed') {
 2570: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 2571: 			    next;
 2572: 			} elsif ($message ne '') {
 2573: 			    my ($baseurl,$showsymb) = 
 2574: 				&get_feedurl_and_symb($symb,$collaborator,
 2575: 						      $udom);
 2576: 			    if ($env{'form.withgrades'.$ctr}) {
 2577: 				$messagetail = " for <a href=\"".
 2578:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
 2579: 			    }
 2580: 			    $msgstatus = 
 2581: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 2582: 			}
 2583: 		    }
 2584: 		}
 2585: 	    }
 2586: 	    $ctr++;
 2587: 	}
 2588:     }
 2589: 
 2590: #    if ($env{'form.handgrade'} eq 'yes') {
 2591:     if (1) {
 2592: 	# Keywords sorted in alphabatical order
 2593: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2594: 	my %keyhash = ();
 2595: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 2596: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 2597: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 2598: 	$env{'form.keywords'} = join(' ',@keywords);
 2599: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 2600: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 2601: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 2602: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 2603: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 2604: 
 2605: 	# message center - Order of message gets changed. Blank line is eliminated.
 2606: 	# New messages are saved in env for the next student.
 2607: 	# All messages are saved in nohist_handgrade.db
 2608: 	my ($ctr,$idx) = (1,1);
 2609: 	while ($ctr <= $env{'form.savemsgN'}) {
 2610: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 2611: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 2612: 		$idx++;
 2613: 	    }
 2614: 	    $ctr++;
 2615: 	}
 2616: 	$ctr = 0;
 2617: 	while ($ctr < $ngrade) {
 2618: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 2619: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2620: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2621: 		$idx++;
 2622: 	    }
 2623: 	    $ctr++;
 2624: 	}
 2625: 	$env{'form.savemsgN'} = --$idx;
 2626: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 2627: 	my $putresult = &Apache::lonnet::put
 2628: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 2629:     }
 2630:     # Called by Save & Refresh from Highlight Attribute Window
 2631:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 2632:     if ($env{'form.refresh'} eq 'on') {
 2633: 	my ($ctr,$total) = (0,0);
 2634: 	while ($ctr < $ngrade) {
 2635: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 2636: 	    $ctr++;
 2637: 	}
 2638: 	$env{'form.NTSTU'}=$ngrade;
 2639: 	$ctr = 0;
 2640: 	while ($ctr < $total) {
 2641: 	    my $processUser = $env{'form.unamedom'.$ctr};
 2642: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2643: 	    $env{'form.fullname'} = $$fullname{$processUser};
 2644: 	    &submission($request,$ctr,$total-1,$symb);
 2645: 	    $ctr++;
 2646: 	}
 2647: 	return '';
 2648:     }
 2649: 
 2650:     # Get the next/previous one or group of students
 2651:     my $firststu = $env{'form.unamedom0'};
 2652:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 2653:     my $ctr = 2;
 2654:     while ($laststu eq '') {
 2655: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 2656: 	$ctr++;
 2657: 	$laststu = $firststu if ($ctr > $ngrade);
 2658:     }
 2659: 
 2660:     my (@parsedlist,@nextlist);
 2661:     my ($nextflg) = 0;
 2662:     foreach my $item (sort 
 2663: 	     {
 2664: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 2665: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 2666: 		 }
 2667: 		 return $a cmp $b;
 2668: 	     } (keys(%$fullname))) {
 2669: # FIXME: this is fishy, looks like the button label
 2670: 	if ($nextflg == 1 && $button =~ /Next$/) {
 2671: 	    push(@parsedlist,$item);
 2672: 	}
 2673: 	$nextflg = 1 if ($item eq $laststu);
 2674: 	if ($button eq 'Previous') {
 2675: 	    last if ($item eq $firststu);
 2676: 	    push(@parsedlist,$item);
 2677: 	}
 2678:     }
 2679:     $ctr = 0;
 2680: # FIXME: this is fishy, looks like the button label
 2681:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 2682:     my $res_error;
 2683:     my ($partlist) = &response_type($symb,\$res_error);
 2684:     if ($res_error) {
 2685:         $request->print(&navmap_errormsg());
 2686:         return;
 2687:     }
 2688:     foreach my $student (@parsedlist) {
 2689: 	my $submitonly=$env{'form.submitonly'};
 2690: 	my ($uname,$udom) = split(/:/,$student);
 2691: 	
 2692: 	if ($submitonly eq 'queued') {
 2693: 	    my %queue_status = 
 2694: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 2695: 							$udom,$uname);
 2696: 	    next if (!defined($queue_status{'gradingqueue'}));
 2697: 	}
 2698: 
 2699: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 2700: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2701: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 2702: 	    my $submitted = 0;
 2703: 	    my $ungraded = 0;
 2704: 	    my $incorrect = 0;
 2705: 	    foreach my $item (keys(%status)) {
 2706: 		$submitted = 1 if ($status{$item} ne 'nothing');
 2707: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 2708: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 2709: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 2710: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 2711: 		    $submitted = 0;
 2712: 		}
 2713: 	    }
 2714: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 2715: 				     $submitonly eq 'incorrect' ||
 2716: 				     $submitonly eq 'graded'));
 2717: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 2718: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 2719: 	}
 2720: 	push(@nextlist,$student) if ($ctr < $ntstu);
 2721: 	last if ($ctr == $ntstu);
 2722: 	$ctr++;
 2723:     }
 2724: 
 2725:     $ctr = 0;
 2726:     my $total = scalar(@nextlist)-1;
 2727: 
 2728:     foreach (sort(@nextlist)) {
 2729: 	my ($uname,$udom,$submitter) = split(/:/);
 2730: 	$env{'form.student'}  = $uname;
 2731: 	$env{'form.userdom'}  = $udom;
 2732: 	$env{'form.fullname'} = $$fullname{$_};
 2733: 	&submission($request,$ctr,$total,$symb);
 2734: 	$ctr++;
 2735:     }
 2736:     if ($total < 0) {
 2737: 	my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
 2738: 	$request->print($the_end);
 2739:     }
 2740:     return '';
 2741: }
 2742: 
 2743: #---- Save the score and award for each student, if changed
 2744: sub saveHandGrade {
 2745:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 2746:     my @version_parts;
 2747:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 2748: 					   $env{'request.course.id'});
 2749:     if (!&canmodify($usec)) { return('not_allowed'); }
 2750:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 2751:     my @parts_graded;
 2752:     my %newrecord  = ();
 2753:     my ($pts,$wgt) = ('','');
 2754:     my %aggregate = ();
 2755:     my $aggregateflag = 0;
 2756:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 2757:     foreach my $new_part (@parts) {
 2758: 	#collaborator ($submi may vary for different parts
 2759: 	if ($submitter && $new_part ne $part) { next; }
 2760: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 2761: 	if ($dropMenu eq 'excused') {
 2762: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 2763: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 2764: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 2765: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 2766: 		}
 2767: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 2768: 	    }
 2769: 	} elsif ($dropMenu eq 'reset status'
 2770: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 2771: 	    foreach my $key (keys(%record)) {
 2772: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 2773: 	    }
 2774: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2775: 		"$env{'user.name'}:$env{'user.domain'}";
 2776:             my $totaltries = $record{'resource.'.$part.'.tries'};
 2777: 
 2778:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 2779: 					       [$new_part]);
 2780:             my $aggtries =$totaltries;
 2781:             if ($last_resets{$new_part}) {
 2782:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 2783: 					   $new_part);
 2784:             }
 2785: 
 2786:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 2787:             if ($aggtries > 0) {
 2788:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 2789:                 $aggregateflag = 1;
 2790:             }
 2791: 	} elsif ($dropMenu eq '') {
 2792: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 2793: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 2794: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 2795: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 2796: 		next;
 2797: 	    }
 2798: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 2799: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 2800: 	    my $partial= $pts/$wgt;
 2801: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 2802: 		#do not update score for part if not changed.
 2803:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 2804: 		next;
 2805: 	    } else {
 2806: 	        push(@parts_graded,$new_part);
 2807: 	    }
 2808: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 2809: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 2810: 	    }
 2811: 	    my $reckey = 'resource.'.$new_part.'.solved';
 2812: 	    if ($partial == 0) {
 2813: 		if ($record{$reckey} ne 'incorrect_by_override') {
 2814: 		    $newrecord{$reckey} = 'incorrect_by_override';
 2815: 		}
 2816: 	    } else {
 2817: 		if ($record{$reckey} ne 'correct_by_override') {
 2818: 		    $newrecord{$reckey} = 'correct_by_override';
 2819: 		}
 2820: 	    }	    
 2821: 	    if ($submitter && 
 2822: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 2823: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 2824: 	    }
 2825: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2826: 		"$env{'user.name'}:$env{'user.domain'}";
 2827: 	}
 2828: 	# unless problem has been graded, set flag to version the submitted files
 2829: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 2830: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 2831: 	        $dropMenu eq 'reset status')
 2832: 	   {
 2833: 	    push(@version_parts,$new_part);
 2834: 	}
 2835:     }
 2836:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2837:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2838: 
 2839:     if (%newrecord) {
 2840:         if (@version_parts) {
 2841:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 2842:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 2843: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 2844: 	    foreach my $new_part (@version_parts) {
 2845: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 2846: 				$new_part,\%newrecord);
 2847: 	    }
 2848:         }
 2849: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 2850: 				$env{'request.course.id'},$domain,$stuname);
 2851: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 2852: 				     $cdom,$cnum,$domain,$stuname);
 2853:     }
 2854:     if ($aggregateflag) {
 2855:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 2856: 			      $cdom,$cnum);
 2857:     }
 2858:     return ('',$pts,$wgt);
 2859: }
 2860: 
 2861: sub check_and_remove_from_queue {
 2862:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 2863:     my @ungraded_parts;
 2864:     foreach my $part (@{$parts}) {
 2865: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 2866: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 2867: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 2868: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 2869: 		) {
 2870: 	    push(@ungraded_parts, $part);
 2871: 	}
 2872:     }
 2873:     if ( !@ungraded_parts ) {
 2874: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 2875: 					       $cnum,$domain,$stuname);
 2876:     }
 2877: }
 2878: 
 2879: sub handback_files {
 2880:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 2881:     my $portfolio_root = '/userfiles/portfolio';
 2882:     my $res_error;
 2883:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2884:     if ($res_error) {
 2885:         $request->print('<br />'.&navmap_errormsg().'<br />');
 2886:         return;
 2887:     }
 2888:     my @handedback;
 2889:     my $file_msg;
 2890:     my @part_response_id = &flatten_responseType($responseType);
 2891:     foreach my $part_response_id (@part_response_id) {
 2892:     	my ($part_id,$resp_id) = @{ $part_response_id };
 2893: 	my $part_resp = join('_',@{ $part_response_id });
 2894:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
 2895:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
 2896:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3' 
 2897:                 if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
 2898:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
 2899:                     my ($directory,$answer_file) = 
 2900:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
 2901:                     my ($answer_name,$answer_ver,$answer_ext) =
 2902: 		        &file_name_version_ext($answer_file);
 2903: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 2904:                     my $getpropath = 1;
 2905: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
 2906: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 2907:                     # fix file name
 2908:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 2909:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 2910:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
 2911:             	                                $save_file_name);
 2912:                     if ($result !~ m|^/uploaded/|) {
 2913:                         $request->print('<br /><span class="LC_error">'.
 2914:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 2915:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
 2916:                                         '</span>');
 2917:                     } else {
 2918:                         # mark the file as read only
 2919:                         push(@handedback,$save_file_name);
 2920: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 2921: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 2922: 			}
 2923:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 2924: 			$file_msg.= '<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
 2925:                     }
 2926:                     $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>'));
 2927:                 }
 2928:             }
 2929:         }
 2930:     }
 2931:     if (@handedback > 0) {
 2932:         $request->print('<br />');
 2933:         my @what = ($symb,$env{'request.course.id'},'handback');
 2934:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
 2935:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});    
 2936:         my ($subject,$message);
 2937:         if (scalar(@handedback) == 1) {
 2938:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
 2939:             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
 2940:         } else {
 2941:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
 2942:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
 2943:         }
 2944:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
 2945:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
 2946:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
 2947:         my ($feedurl,$showsymb) =
 2948:             &get_feedurl_and_symb($symb,$domain,$stuname);
 2949:         my $restitle = &Apache::lonnet::gettitle($symb);
 2950:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
 2951:         my $msgstatus =
 2952:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
 2953:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
 2954:                  $restitle);
 2955:         if ($msgstatus) {
 2956:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
 2957:         }
 2958:     }
 2959:     return;
 2960: }
 2961: 
 2962: sub get_feedurl_and_symb {
 2963:     my ($symb,$uname,$udom) = @_;
 2964:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2965:     $url = &Apache::lonnet::clutter($url);
 2966:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 2967: 					$symb,$udom,$uname);
 2968:     if ($encrypturl =~ /^yes$/i) {
 2969: 	&Apache::lonenc::encrypted(\$url,1);
 2970: 	&Apache::lonenc::encrypted(\$symb,1);
 2971:     }
 2972:     return ($url,$symb);
 2973: }
 2974: 
 2975: sub get_submitted_files {
 2976:     my ($udom,$uname,$partid,$respid,$record) = @_;
 2977:     my @files;
 2978:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 2979:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 2980:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 2981:     	    push(@files,$file_url.$file);
 2982:         }
 2983:     }
 2984:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 2985:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 2986:     }
 2987:     return (\@files);
 2988: }
 2989: 
 2990: # ----------- Provides number of tries since last reset.
 2991: sub get_num_tries {
 2992:     my ($record,$last_reset,$part) = @_;
 2993:     my $timestamp = '';
 2994:     my $num_tries = 0;
 2995:     if ($$record{'version'}) {
 2996:         for (my $version=$$record{'version'};$version>=1;$version--) {
 2997:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 2998:                 $timestamp = $$record{$version.':timestamp'};
 2999:                 if ($timestamp > $last_reset) {
 3000:                     $num_tries ++;
 3001:                 } else {
 3002:                     last;
 3003:                 }
 3004:             }
 3005:         }
 3006:     }
 3007:     return $num_tries;
 3008: }
 3009: 
 3010: # ----------- Determine decrements required in aggregate totals 
 3011: sub decrement_aggs {
 3012:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 3013:     my %decrement = (
 3014:                         attempts => 0,
 3015:                         users => 0,
 3016:                         correct => 0
 3017:                     );
 3018:     $decrement{'attempts'} = $aggtries;
 3019:     if ($solvedstatus =~ /^correct/) {
 3020:         $decrement{'correct'} = 1;
 3021:     }
 3022:     if ($aggtries == $totaltries) {
 3023:         $decrement{'users'} = 1;
 3024:     }
 3025:     foreach my $type (keys(%decrement)) {
 3026:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 3027:     }
 3028:     return;
 3029: }
 3030: 
 3031: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 3032: sub get_last_resets {
 3033:     my ($symb,$courseid,$partids) =@_;
 3034:     my %last_resets;
 3035:     my $cdom = $env{'course.'.$courseid.'.domain'};
 3036:     my $cname = $env{'course.'.$courseid.'.num'};
 3037:     my @keys;
 3038:     foreach my $part (@{$partids}) {
 3039: 	push(@keys,"$symb\0$part\0resettime");
 3040:     }
 3041:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 3042: 				     $cdom,$cname);
 3043:     foreach my $part (@{$partids}) {
 3044: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 3045:     }
 3046:     return %last_resets;
 3047: }
 3048: 
 3049: # ----------- Handles creating versions for portfolio files as answers
 3050: sub version_portfiles {
 3051:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 3052:     my $version_parts = join('|',@$v_flag);
 3053:     my @returned_keys;
 3054:     my $parts = join('|', @$parts_graded);
 3055:     my $portfolio_root = '/userfiles/portfolio';
 3056:     foreach my $key (keys(%$record)) {
 3057:         my $new_portfiles;
 3058:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 3059:             my @versioned_portfiles;
 3060:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 3061:             foreach my $file (@portfiles) {
 3062:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 3063:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 3064: 		my ($answer_name,$answer_ver,$answer_ext) =
 3065: 		    &file_name_version_ext($answer_file);
 3066:                 my $getpropath = 1;    
 3067:                 my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
 3068:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 3069:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
 3070:                 if ($new_answer ne 'problem getting file') {
 3071:                     push(@versioned_portfiles, $directory.$new_answer);
 3072:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
 3073:                         [$directory.$new_answer],
 3074:                         [$symb,$env{'request.course.id'},'graded']);
 3075:                 }
 3076:             }
 3077:             $$record{$key} = join(',',@versioned_portfiles);
 3078:             push(@returned_keys,$key);
 3079:         }
 3080:     } 
 3081:     return (@returned_keys);   
 3082: }
 3083: 
 3084: sub get_next_version {
 3085:     my ($answer_name, $answer_ext, $dir_list) = @_;
 3086:     my $version;
 3087:     foreach my $row (@$dir_list) {
 3088:         my ($file) = split(/\&/,$row,2);
 3089:         my ($file_name,$file_version,$file_ext) =
 3090: 	    &file_name_version_ext($file);
 3091:         if (($file_name eq $answer_name) && 
 3092: 	    ($file_ext eq $answer_ext)) {
 3093:                 # gets here if filename and extension match, regardless of version
 3094:                 if ($file_version ne '') {
 3095:                 # a versioned file is found  so save it for later
 3096:                 if ($file_version > $version) {
 3097: 		    $version = $file_version;
 3098: 	        }
 3099:             }
 3100:         }
 3101:     } 
 3102:     $version ++;
 3103:     return($version);
 3104: }
 3105: 
 3106: sub version_selected_portfile {
 3107:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 3108:     my ($answer_name,$answer_ver,$answer_ext) =
 3109:         &file_name_version_ext($file_name);
 3110:     my $new_answer;
 3111:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 3112:     if($env{'form.copy'} eq '-1') {
 3113:         $new_answer = 'problem getting file';
 3114:     } else {
 3115:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 3116:         my $copy_result = &Apache::lonnet::finishuserfileupload(
 3117:                             $stu_name,$domain,'copy',
 3118: 		        '/portfolio'.$directory.$new_answer);
 3119:     }    
 3120:     return ($new_answer);
 3121: }
 3122: 
 3123: sub file_name_version_ext {
 3124:     my ($file)=@_;
 3125:     my @file_parts = split(/\./, $file);
 3126:     my ($name,$version,$ext);
 3127:     if (@file_parts > 1) {
 3128: 	$ext=pop(@file_parts);
 3129: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 3130: 	    $version=pop(@file_parts);
 3131: 	}
 3132: 	$name=join('.',@file_parts);
 3133:     } else {
 3134: 	$name=join('.',@file_parts);
 3135:     }
 3136:     return($name,$version,$ext);
 3137: }
 3138: 
 3139: #--------------------------------------------------------------------------------------
 3140: #
 3141: #-------------------------- Next few routines handles grading by section or whole class
 3142: #
 3143: #--- Javascript to handle grading by section or whole class
 3144: sub viewgrades_js {
 3145:     my ($request) = shift;
 3146: 
 3147:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3148:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
 3149:    function writePoint(partid,weight,point) {
 3150: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3151: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3152: 	if (point == "textval") {
 3153: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3154: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3155: 		alert("$alertmsg"+parseFloat(point));
 3156: 		var resetbox = false;
 3157: 		for (var i=0; i<radioButton.length; i++) {
 3158: 		    if (radioButton[i].checked) {
 3159: 			textbox.value = i;
 3160: 			resetbox = true;
 3161: 		    }
 3162: 		}
 3163: 		if (!resetbox) {
 3164: 		    textbox.value = "";
 3165: 		}
 3166: 		return;
 3167: 	    }
 3168: 	    if (parseFloat(point) > parseFloat(weight)) {
 3169: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3170: 				   ") greater than the weight for the part. Accept?");
 3171: 		if (resp == false) {
 3172: 		    textbox.value = "";
 3173: 		    return;
 3174: 		}
 3175: 	    }
 3176: 	    for (var i=0; i<radioButton.length; i++) {
 3177: 		radioButton[i].checked=false;
 3178: 		if (parseFloat(point) == i) {
 3179: 		    radioButton[i].checked=true;
 3180: 		}
 3181: 	    }
 3182: 
 3183: 	} else {
 3184: 	    textbox.value = parseFloat(point);
 3185: 	}
 3186: 	for (i=0;i<document.classgrade.total.value;i++) {
 3187: 	    var user = document.classgrade["ctr"+i].value;
 3188: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3189: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3190: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3191: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3192: 	    if (saveval != "correct") {
 3193: 		scorename.value = point;
 3194: 		if (selname[0].selected != true) {
 3195: 		    selname[0].selected = true;
 3196: 		}
 3197: 	    }
 3198: 	}
 3199: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3200:     }
 3201: 
 3202:     function writeRadText(partid,weight) {
 3203: 	var selval   = document.classgrade["SELVAL_"+partid];
 3204: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3205:         var override = document.classgrade["FORCE_"+partid].checked;
 3206: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3207: 	if (selval[1].selected || selval[2].selected) {
 3208: 	    for (var i=0; i<radioButton.length; i++) {
 3209: 		radioButton[i].checked=false;
 3210: 
 3211: 	    }
 3212: 	    textbox.value = "";
 3213: 
 3214: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3215: 		var user = document.classgrade["ctr"+i].value;
 3216: 		user = user.replace(new RegExp(':', 'g'),"_");
 3217: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3218: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3219: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3220: 		if ((saveval != "correct") || override) {
 3221: 		    scorename.value = "";
 3222: 		    if (selval[1].selected) {
 3223: 			selname[1].selected = true;
 3224: 		    } else {
 3225: 			selname[2].selected = true;
 3226: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3227: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3228: 		    }
 3229: 		}
 3230: 	    }
 3231: 	} else {
 3232: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3233: 		var user = document.classgrade["ctr"+i].value;
 3234: 		user = user.replace(new RegExp(':', 'g'),"_");
 3235: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3236: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3237: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3238: 		if ((saveval != "correct") || override) {
 3239: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3240: 		    selname[0].selected = true;
 3241: 		}
 3242: 	    }
 3243: 	}	    
 3244:     }
 3245: 
 3246:     function changeSelect(partid,user) {
 3247: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3248: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3249: 	var point  = textbox.value;
 3250: 	var weight = document.classgrade["weight_"+partid].value;
 3251: 
 3252: 	if (isNaN(point) || parseFloat(point) < 0) {
 3253: 	    alert("$alertmsg"+parseFloat(point));
 3254: 	    textbox.value = "";
 3255: 	    return;
 3256: 	}
 3257: 	if (parseFloat(point) > parseFloat(weight)) {
 3258: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3259: 			       ") greater than the weight of the part. Accept?");
 3260: 	    if (resp == false) {
 3261: 		textbox.value = "";
 3262: 		return;
 3263: 	    }
 3264: 	}
 3265: 	selval[0].selected = true;
 3266:     }
 3267: 
 3268:     function changeOneScore(partid,user) {
 3269: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3270: 	if (selval[1].selected || selval[2].selected) {
 3271: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3272: 	    if (selval[2].selected) {
 3273: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3274: 	    }
 3275:         }
 3276:     }
 3277: 
 3278:     function resetEntry(numpart) {
 3279: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3280: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3281: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3282: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3283: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3284: 	    for (var i=0; i<radioButton.length; i++) {
 3285: 		radioButton[i].checked=false;
 3286: 
 3287: 	    }
 3288: 	    textbox.value = "";
 3289: 	    selval[0].selected = true;
 3290: 
 3291: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3292: 		var user = document.classgrade["ctr"+i].value;
 3293: 		user = user.replace(new RegExp(':', 'g'),"_");
 3294: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3295: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3296: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3297: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3298: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3299: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3300: 		if (saveselval == "excused") {
 3301: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3302: 		} else {
 3303: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3304: 		}
 3305: 	    }
 3306: 	}
 3307:     }
 3308: 
 3309: VIEWJAVASCRIPT
 3310: }
 3311: 
 3312: #--- show scores for a section or whole class w/ option to change/update a score
 3313: sub viewgrades {
 3314:     my ($request,$symb) = @_;
 3315:     &viewgrades_js($request);
 3316: 
 3317:     #need to make sure we have the correct data for later EXT calls, 
 3318:     #thus invalidate the cache
 3319:     &Apache::lonnet::devalidatecourseresdata(
 3320:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3321:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3322:     &Apache::lonnet::clear_EXT_cache_status();
 3323: 
 3324:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3325: 
 3326:     #view individual student submission form - called using Javascript viewOneStudent
 3327:     $result.=&jscriptNform($symb);
 3328: 
 3329:     #beginning of class grading form
 3330:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3331:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3332: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3333: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3334: 	&build_section_inputs().
 3335: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3336: 
 3337:     my ($common_header,$specific_header);
 3338:     if ($env{'form.section'} eq 'all') {
 3339: 	$common_header = &mt('Assign Common Grade to Class');
 3340:         $specific_header = &mt('Assign Grade to Specific Students in Class');
 3341:     } elsif ($env{'form.section'} eq 'none') {
 3342:         $common_header = &mt('Assign Common Grade to Students in no Section');
 3343: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
 3344:     } else {
 3345:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3346:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
 3347: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
 3348:     }
 3349:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
 3350:     #radio buttons/text box for assigning points for a section or class.
 3351:     #handles different parts of a problem
 3352:     my $res_error;
 3353:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3354:     if ($res_error) {
 3355:         return &navmap_errormsg();
 3356:     }
 3357:     my %weight = ();
 3358:     my $ctsparts = 0;
 3359:     my %seen = ();
 3360:     my @part_response_id = &flatten_responseType($responseType);
 3361:     foreach my $part_response_id (@part_response_id) {
 3362:     	my ($partid,$respid) = @{ $part_response_id };
 3363: 	my $part_resp = join('_',@{ $part_response_id });
 3364: 	next if $seen{$partid};
 3365: 	$seen{$partid}++;
 3366: 	my $handgrade=$$handgrade{$part_resp};
 3367: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 3368: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 3369: 
 3370: 	my $display_part=&get_display_part($partid,$symb);
 3371: 	my $radio.='<table border="0"><tr>';  
 3372: 	my $ctr = 0;
 3373: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 3374: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 3375: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 3376: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 3377: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 3378: 	    $ctr++;
 3379: 	}
 3380: 	$radio.='</tr></table>';
 3381: 	my $line = '<input type="text" name="TEXTVAL_'.
 3382: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
 3383: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 3384: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 3385: 	$line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
 3386: 	    'onchange="javascript:writeRadText(\''.$partid.'\','.
 3387: 		$weight{$partid}.')"> '.
 3388: 	    '<option selected="selected"> </option>'.
 3389: 	    '<option value="excused">'.&mt('excused').'</option>'.
 3390: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 3391: 	    '</select></td>'.
 3392:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 3393: 	$line.='<input type="hidden" name="partid_'.
 3394: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 3395: 	$line.='<input type="hidden" name="weight_'.
 3396: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 3397: 
 3398: 	$result.=
 3399: 	    &Apache::loncommon::start_data_table_row()."\n".
 3400: 	    '<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>'.
 3401: 	    &Apache::loncommon::end_data_table_row()."\n";
 3402: 	$ctsparts++;
 3403:     }
 3404:     $result.=&Apache::loncommon::end_data_table()."\n".
 3405: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 3406:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 3407: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
 3408: 
 3409:     #table listing all the students in a section/class
 3410:     #header of table
 3411:     $result.= '<h3>'.$specific_header.'</h3>'.
 3412:               &Apache::loncommon::start_data_table().
 3413: 	      &Apache::loncommon::start_data_table_header_row().
 3414: 	      '<th>'.&mt('No.').'</th>'.
 3415: 	      '<th>'.&nameUserString('header')."</th>\n";
 3416:     my $partserror;
 3417:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3418:     if ($partserror) {
 3419:         return &navmap_errormsg();
 3420:     }
 3421:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 3422:     my @partids = ();
 3423:     foreach my $part (@parts) {
 3424: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3425:         my $narrowtext = &mt('Tries');
 3426: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 3427: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 3428: 	my ($partid) = &split_part_type($part);
 3429:         push(@partids,$partid);
 3430: #
 3431: # FIXME: Looks like $display looks at English text
 3432: #
 3433: 	my $display_part=&get_display_part($partid,$symb);
 3434: 	if ($display =~ /^Partial Credit Factor/) {
 3435: 	    $result.='<th>'.
 3436: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
 3437: 		    $display_part,$weight{$partid}).'</th>'."\n";
 3438: 	    next;
 3439: 	    
 3440: 	} else {
 3441: 	    if ($display =~ /Problem Status/) {
 3442: 		my $grade_status_mt = &mt('Grade Status');
 3443: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 3444: 	    }
 3445: 	    my $part_mt = &mt('Part:');
 3446: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 3447: 	}
 3448: 
 3449: 	$result.='<th>'.$display.'</th>'."\n";
 3450:     }
 3451:     $result.=&Apache::loncommon::end_data_table_header_row();
 3452: 
 3453:     my %last_resets = 
 3454: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 3455: 
 3456:     #get info for each student
 3457:     #list all the students - with points and grade status
 3458:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3459:     my $ctr = 0;
 3460:     foreach (sort 
 3461: 	     {
 3462: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3463: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3464: 		 }
 3465: 		 return $a cmp $b;
 3466: 	     } (keys(%$fullname))) {
 3467: 	$ctr++;
 3468: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 3469: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
 3470:     }
 3471:     $result.=&Apache::loncommon::end_data_table();
 3472:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 3473:     $result.='<input type="button" value="'.&mt('Save').'" '.
 3474: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
 3475:     if (scalar(%$fullname) eq 0) {
 3476: 	my $colspan=3+scalar(@parts);
 3477: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3478:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 3479: 	$result='<span class="LC_warning">'.
 3480: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 3481: 	        $section_display, $stu_status).
 3482: 	    '</span>';
 3483:     }
 3484:     return $result;
 3485: }
 3486: 
 3487: #--- call by previous routine to display each student
 3488: sub viewstudentgrade {
 3489:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 3490:     my ($uname,$udom) = split(/:/,$student);
 3491:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 3492:     my %aggregates = (); 
 3493:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 3494: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
 3495: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
 3496: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 3497: 	'\');" target="_self">'.$fullname.'</a> '.
 3498: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 3499:     $student=~s/:/_/; # colon doen't work in javascript for names
 3500:     foreach my $apart (@$parts) {
 3501: 	my ($part,$type) = &split_part_type($apart);
 3502: 	my $score=$record{"resource.$part.$type"};
 3503:         $result.='<td align="center">';
 3504:         my ($aggtries,$totaltries);
 3505:         unless (exists($aggregates{$part})) {
 3506: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 3507: 
 3508: 	    $aggtries = $totaltries;
 3509:             if ($$last_resets{$part}) {  
 3510:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 3511: 					   $part);
 3512:             }
 3513:             $result.='<input type="hidden" name="'.
 3514:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 3515:             $result.='<input type="hidden" name="'.
 3516:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 3517:             $aggregates{$part} = 1;
 3518:         }
 3519: 	if ($type eq 'awarded') {
 3520: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 3521: 	    $result.='<input type="hidden" name="'.
 3522: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 3523: 	    $result.='<input type="text" name="'.
 3524: 		'GD_'.$student.'_'.$part.'_awarded" '.
 3525:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
 3526: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 3527: 	} elsif ($type eq 'solved') {
 3528: 	    my ($status,$foo)=split(/_/,$score,2);
 3529: 	    $status = 'nothing' if ($status eq '');
 3530: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 3531: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 3532: 	    $result.='&nbsp;<select name="'.
 3533: 		'GD_'.$student.'_'.$part.'_solved" '.
 3534:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 3535: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 3536: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 3537: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 3538: 	    $result.="</select>&nbsp;</td>\n";
 3539: 	} else {
 3540: 	    $result.='<input type="hidden" name="'.
 3541: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 3542: 		    "\n";
 3543: 	    $result.='<input type="text" name="'.
 3544: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 3545: 		'value="'.$score.'" size="4" /></td>'."\n";
 3546: 	}
 3547:     }
 3548:     $result.=&Apache::loncommon::end_data_table_row();
 3549:     return $result;
 3550: }
 3551: 
 3552: #--- change scores for all the students in a section/class
 3553: #    record does not get update if unchanged
 3554: sub editgrades {
 3555:     my ($request,$symb) = @_;
 3556: 
 3557:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3558:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 3559:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
 3560: 
 3561:     my $result= &Apache::loncommon::start_data_table().
 3562: 	&Apache::loncommon::start_data_table_header_row().
 3563: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 3564: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 3565:     my %scoreptr = (
 3566: 		    'correct'  =>'correct_by_override',
 3567: 		    'incorrect'=>'incorrect_by_override',
 3568: 		    'excused'  =>'excused',
 3569: 		    'ungraded' =>'ungraded_attempted',
 3570:                     'credited' =>'credit_attempted',
 3571: 		    'nothing'  => '',
 3572: 		    );
 3573:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 3574: 
 3575:     my (@partid);
 3576:     my %weight = ();
 3577:     my %columns = ();
 3578:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 3579: 
 3580:     my $partserror;
 3581:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3582:     if ($partserror) {
 3583:         return &navmap_errormsg();
 3584:     }
 3585:     my $header;
 3586:     while ($ctr < $env{'form.totalparts'}) {
 3587: 	my $partid = $env{'form.partid_'.$ctr};
 3588: 	push(@partid,$partid);
 3589: 	$weight{$partid} = $env{'form.weight_'.$partid};
 3590: 	$ctr++;
 3591:     }
 3592:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3593:     foreach my $partid (@partid) {
 3594: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 3595: 	    '<th align="center">'.&mt('New Score').'</th>';
 3596: 	$columns{$partid}=2;
 3597: 	foreach my $stores (@parts) {
 3598: 	    my ($part,$type) = &split_part_type($stores);
 3599: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 3600: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 3601: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 3602: 	    $display =~ s/\[Part: \Q$part\E\]//;
 3603:             my $narrowtext = &mt('Tries');
 3604: 	    $display =~ s/Number of Attempts/$narrowtext/;
 3605: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 3606: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 3607: 	    $columns{$partid}+=2;
 3608: 	}
 3609:     }
 3610:     foreach my $partid (@partid) {
 3611: 	my $display_part=&get_display_part($partid,$symb);
 3612: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 3613: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 3614: 	    '</th>';
 3615: 
 3616:     }
 3617:     $result .= &Apache::loncommon::end_data_table_header_row().
 3618: 	&Apache::loncommon::start_data_table_header_row().
 3619: 	$header.
 3620: 	&Apache::loncommon::end_data_table_header_row();
 3621:     my @noupdate;
 3622:     my ($updateCtr,$noupdateCtr) = (1,1);
 3623:     for ($i=0; $i<$env{'form.total'}; $i++) {
 3624: 	my $line;
 3625: 	my $user = $env{'form.ctr'.$i};
 3626: 	my ($uname,$udom)=split(/:/,$user);
 3627: 	my %newrecord;
 3628: 	my $updateflag = 0;
 3629: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 3630: 	my $usec=$classlist->{"$uname:$udom"}[5];
 3631: 	if (!&canmodify($usec)) {
 3632: 	    my $numcols=scalar(@partid)*4+2;
 3633: 	    push(@noupdate,
 3634: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
 3635: 		 &mt('Not allowed to modify student')."</span></td></tr>");
 3636: 	    next;
 3637: 	}
 3638:         my %aggregate = ();
 3639:         my $aggregateflag = 0;
 3640: 	$user=~s/:/_/; # colon doen't work in javascript for names
 3641: 	foreach (@partid) {
 3642: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 3643: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 3644: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 3645: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3646: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 3647: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 3648: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 3649: 	    my $score;
 3650: 	    if ($partial eq '') {
 3651: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3652: 	    } elsif ($partial > 0) {
 3653: 		$score = 'correct_by_override';
 3654: 	    } elsif ($partial == 0) {
 3655: 		$score = 'incorrect_by_override';
 3656: 	    }
 3657: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 3658: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 3659: 
 3660: 	    $newrecord{'resource.'.$_.'.regrader'}=
 3661: 		"$env{'user.name'}:$env{'user.domain'}";
 3662: 	    if ($dropMenu eq 'reset status' &&
 3663: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 3664: 		$newrecord{'resource.'.$_.'.tries'} = '';
 3665: 		$newrecord{'resource.'.$_.'.solved'} = '';
 3666: 		$newrecord{'resource.'.$_.'.award'} = '';
 3667: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 3668: 		$updateflag = 1;
 3669:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 3670:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 3671:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 3672:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 3673:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3674:                     $aggregateflag = 1;
 3675:                 }
 3676: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 3677: 		$updateflag = 1;
 3678: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 3679: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 3680: 		$rec_update++;
 3681: 	    }
 3682: 
 3683: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3684: 		'<td align="center">'.$awarded.
 3685: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 3686: 
 3687: 
 3688: 	    my $partid=$_;
 3689: 	    foreach my $stores (@parts) {
 3690: 		my ($part,$type) = &split_part_type($stores);
 3691: 		if ($part !~ m/^\Q$partid\E/) { next;}
 3692: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 3693: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 3694: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 3695: 		if ($awarded ne '' && $awarded ne $old_aw) {
 3696: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 3697: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3698: 		    $updateflag=1;
 3699: 		}
 3700: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3701: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 3702: 	    }
 3703: 	}
 3704: 	$line.="\n";
 3705: 
 3706: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3707: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3708: 
 3709: 	if ($updateflag) {
 3710: 	    $count++;
 3711: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 3712: 				    $udom,$uname);
 3713: 
 3714: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 3715: 					      $cnum,$udom,$uname)) {
 3716: 		# need to figure out if should be in queue.
 3717: 		my %record =  
 3718: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 3719: 					     $udom,$uname);
 3720: 		my $all_graded = 1;
 3721: 		my $none_graded = 1;
 3722: 		foreach my $part (@parts) {
 3723: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 3724: 			$all_graded = 0;
 3725: 		    } else {
 3726: 			$none_graded = 0;
 3727: 		    }
 3728: 		}
 3729: 
 3730: 		if ($all_graded || $none_graded) {
 3731: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 3732: 							   $symb,$cdom,$cnum,
 3733: 							   $udom,$uname);
 3734: 		}
 3735: 	    }
 3736: 
 3737: 	    $result.=&Apache::loncommon::start_data_table_row().
 3738: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 3739: 		&Apache::loncommon::end_data_table_row();
 3740: 	    $updateCtr++;
 3741: 	} else {
 3742: 	    push(@noupdate,
 3743: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 3744: 	    $noupdateCtr++;
 3745: 	}
 3746:         if ($aggregateflag) {
 3747:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3748: 				  $cdom,$cnum);
 3749:         }
 3750:     }
 3751:     if (@noupdate) {
 3752: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
 3753: 	my $numcols=scalar(@partid)*4+2;
 3754: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 3755: 	    '<td align="center" colspan="'.$numcols.'">'.
 3756: 	    &mt('No Changes Occurred For the Students Below').
 3757: 	    '</td>'.
 3758: 	    &Apache::loncommon::end_data_table_row();
 3759: 	foreach my $line (@noupdate) {
 3760: 	    $result.=
 3761: 		&Apache::loncommon::start_data_table_row().
 3762: 		$line.
 3763: 		&Apache::loncommon::end_data_table_row();
 3764: 	}
 3765:     }
 3766:     $result .= &Apache::loncommon::end_data_table();
 3767:     my $msg = '<p><b>'.
 3768: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 3769: 	    $rec_update,$count).'</b><br />'.
 3770: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 3771: 	'</b></p>';
 3772:     return $title.$msg.$result;
 3773: }
 3774: 
 3775: sub split_part_type {
 3776:     my ($partstr) = @_;
 3777:     my ($temp,@allparts)=split(/_/,$partstr);
 3778:     my $type=pop(@allparts);
 3779:     my $part=join('_',@allparts);
 3780:     return ($part,$type);
 3781: }
 3782: 
 3783: #------------- end of section for handling grading by section/class ---------
 3784: #
 3785: #----------------------------------------------------------------------------
 3786: 
 3787: 
 3788: #----------------------------------------------------------------------------
 3789: #
 3790: #-------------------------- Next few routines handles grading by csv upload
 3791: #
 3792: #--- Javascript to handle csv upload
 3793: sub csvupload_javascript_reverse_associate {
 3794:     my $error1=&mt('You need to specify the username or the student/employee ID');
 3795:     my $error2=&mt('You need to specify at least one grading field');
 3796:   return(<<ENDPICK);
 3797:   function verify(vf) {
 3798:     var foundsomething=0;
 3799:     var founduname=0;
 3800:     var foundID=0;
 3801:     for (i=0;i<=vf.nfields.value;i++) {
 3802:       tw=eval('vf.f'+i+'.selectedIndex');
 3803:       if (i==0 && tw!=0) { foundID=1; }
 3804:       if (i==1 && tw!=0) { founduname=1; }
 3805:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 3806:     }
 3807:     if (founduname==0 && foundID==0) {
 3808: 	alert('$error1');
 3809: 	return;
 3810:     }
 3811:     if (foundsomething==0) {
 3812: 	alert('$error2');
 3813: 	return;
 3814:     }
 3815:     vf.submit();
 3816:   }
 3817:   function flip(vf,tf) {
 3818:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3819:     var i;
 3820:     for (i=0;i<=vf.nfields.value;i++) {
 3821:       //can not pick the same destination field for both name and domain
 3822:       if (((i ==0)||(i ==1)) && 
 3823:           ((tf==0)||(tf==1)) && 
 3824:           (i!=tf) &&
 3825:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3826:         eval('vf.f'+i+'.selectedIndex=0;')
 3827:       }
 3828:     }
 3829:   }
 3830: ENDPICK
 3831: }
 3832: 
 3833: sub csvupload_javascript_forward_associate {
 3834:     my $error1=&mt('You need to specify the username or the student/employee ID');
 3835:     my $error2=&mt('You need to specify at least one grading field');
 3836:   return(<<ENDPICK);
 3837:   function verify(vf) {
 3838:     var foundsomething=0;
 3839:     var founduname=0;
 3840:     var foundID=0;
 3841:     for (i=0;i<=vf.nfields.value;i++) {
 3842:       tw=eval('vf.f'+i+'.selectedIndex');
 3843:       if (tw==1) { foundID=1; }
 3844:       if (tw==2) { founduname=1; }
 3845:       if (tw>3) { foundsomething=1; }
 3846:     }
 3847:     if (founduname==0 && foundID==0) {
 3848: 	alert('$error1');
 3849: 	return;
 3850:     }
 3851:     if (foundsomething==0) {
 3852: 	alert('$error2');
 3853: 	return;
 3854:     }
 3855:     vf.submit();
 3856:   }
 3857:   function flip(vf,tf) {
 3858:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3859:     var i;
 3860:     //can not pick the same destination field twice
 3861:     for (i=0;i<=vf.nfields.value;i++) {
 3862:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3863:         eval('vf.f'+i+'.selectedIndex=0;')
 3864:       }
 3865:     }
 3866:   }
 3867: ENDPICK
 3868: }
 3869: 
 3870: sub csvuploadmap_header {
 3871:     my ($request,$symb,$datatoken,$distotal)= @_;
 3872:     my $javascript;
 3873:     if ($env{'form.upfile_associate'} eq 'reverse') {
 3874: 	$javascript=&csvupload_javascript_reverse_associate();
 3875:     } else {
 3876: 	$javascript=&csvupload_javascript_forward_associate();
 3877:     }
 3878: 
 3879:     $symb = &Apache::lonenc::check_encrypt($symb);
 3880:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
 3881:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
 3882:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
 3883:     my $reverse=&mt("Reverse Association");
 3884:     $request->print(<<ENDPICK);
 3885: <br />
 3886: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 3887: <input type="hidden" name="associate"  value="" />
 3888: <input type="hidden" name="phase"      value="three" />
 3889: <input type="hidden" name="datatoken"  value="$datatoken" />
 3890: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 3891: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 3892: <input type="hidden" name="upfile_associate" 
 3893:                                        value="$env{'form.upfile_associate'}" />
 3894: <input type="hidden" name="symb"       value="$symb" />
 3895: <input type="hidden" name="command"    value="csvuploadoptions" />
 3896: <hr />
 3897: ENDPICK
 3898:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
 3899:     return '';
 3900: 
 3901: }
 3902: 
 3903: sub csvupload_fields {
 3904:     my ($symb,$errorref) = @_;
 3905:     my (@parts) = &getpartlist($symb,$errorref);
 3906:     if (ref($errorref)) {
 3907:         if ($$errorref) {
 3908:             return;
 3909:         }
 3910:     }
 3911: 
 3912:     my @fields=(['ID','Student/Employee ID'],
 3913: 		['username','Student Username'],
 3914: 		['domain','Student Domain']);
 3915:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3916:     foreach my $part (sort(@parts)) {
 3917: 	my @datum;
 3918: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3919: 	my $name=$part;
 3920: 	if  (!$display) { $display = $name; }
 3921: 	@datum=($name,$display);
 3922: 	if ($name=~/^stores_(.*)_awarded/) {
 3923: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 3924: 	}
 3925: 	push(@fields,\@datum);
 3926:     }
 3927:     return (@fields);
 3928: }
 3929: 
 3930: sub csvuploadmap_footer {
 3931:     my ($request,$i,$keyfields) =@_;
 3932:     $request->print(<<ENDPICK);
 3933: </table>
 3934: <input type="hidden" name="nfields" value="$i" />
 3935: <input type="hidden" name="keyfields" value="$keyfields" />
 3936: <input type="button" onclick="javascript:verify(this.form)" value="Assign Grades" /><br />
 3937: </form>
 3938: ENDPICK
 3939: }
 3940: 
 3941: sub checkforfile_js {
 3942:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 3943:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
 3944:     function checkUpload(formname) {
 3945: 	if (formname.upfile.value == "") {
 3946: 	    alert("$alertmsg");
 3947: 	    return false;
 3948: 	}
 3949: 	formname.submit();
 3950:     }
 3951: CSVFORMJS
 3952:     return $result;
 3953: }
 3954: 
 3955: sub upcsvScores_form {
 3956:     my ($request,$symb) = @_;
 3957:     if (!$symb) {return '';}
 3958:     my $result=&checkforfile_js();
 3959:     $result.=&Apache::loncommon::start_data_table().
 3960:              &Apache::loncommon::start_data_table_header_row().
 3961:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
 3962:              &Apache::loncommon::end_data_table_header_row().
 3963:              &Apache::loncommon::start_data_table_row().'<td>';
 3964:     my $upload=&mt("Upload Scores");
 3965:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 3966:     my $ignore=&mt('Ignore First Line');
 3967:     $symb = &Apache::lonenc::check_encrypt($symb);
 3968:     $result.=<<ENDUPFORM;
 3969: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3970: <input type="hidden" name="symb" value="$symb" />
 3971: <input type="hidden" name="command" value="csvuploadmap" />
 3972: $upfile_select
 3973: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 3974: </form>
 3975: ENDUPFORM
 3976:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 3977:                            &mt("How do I create a CSV file from a spreadsheet")).
 3978:              '</td>'.
 3979:             &Apache::loncommon::end_data_table_row().
 3980:             &Apache::loncommon::end_data_table();
 3981:     return $result;
 3982: }
 3983: 
 3984: 
 3985: sub csvuploadmap {
 3986:     my ($request,$symb)= @_;
 3987:     if (!$symb) {return '';}
 3988: 
 3989:     my $datatoken;
 3990:     if (!$env{'form.datatoken'}) {
 3991: 	$datatoken=&Apache::loncommon::upfile_store($request);
 3992:     } else {
 3993: 	$datatoken=$env{'form.datatoken'};
 3994: 	&Apache::loncommon::load_tmp_file($request);
 3995:     }
 3996:     my @records=&Apache::loncommon::upfile_record_sep();
 3997:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 3998:     my ($i,$keyfields);
 3999:     if (@records) {
 4000:         my $fieldserror;
 4001: 	my @fields=&csvupload_fields($symb,\$fieldserror);
 4002:         if ($fieldserror) {
 4003:             $request->print(&navmap_errormsg());
 4004:             return;
 4005:         }
 4006: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 4007: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 4008: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 4009: 							  \@fields);
 4010: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 4011: 	    chop($keyfields);
 4012: 	} else {
 4013: 	    unshift(@fields,['none','']);
 4014: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 4015: 							    \@fields);
 4016:             foreach my $rec (@records) {
 4017:                 my %temp = &Apache::loncommon::record_sep($rec);
 4018:                 if (%temp) {
 4019:                     $keyfields=join(',',sort(keys(%temp)));
 4020:                     last;
 4021:                 }
 4022:             }
 4023: 	}
 4024:     }
 4025:     &csvuploadmap_footer($request,$i,$keyfields);
 4026: 
 4027:     return '';
 4028: }
 4029: 
 4030: sub csvuploadoptions {
 4031:     my ($request,$symb)= @_;
 4032:     my $overwrite=&mt('Overwrite any existing score');
 4033:     $request->print(<<ENDPICK);
 4034: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4035: <input type="hidden" name="command"    value="csvuploadassign" />
 4036: <p>
 4037: <label>
 4038:    <input type="checkbox" name="overwite_scores" checked="checked" />
 4039:    $overwrite
 4040: </label>
 4041: </p>
 4042: ENDPICK
 4043:     my %fields=&get_fields();
 4044:     if (!defined($fields{'domain'})) {
 4045: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 4046: 	$request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
 4047:     }
 4048:     foreach my $key (sort(keys(%env))) {
 4049: 	if ($key !~ /^form\.(.*)$/) { next; }
 4050: 	my $cleankey=$1;
 4051: 	if ($cleankey eq 'command') { next; }
 4052: 	$request->print('<input type="hidden" name="'.$cleankey.
 4053: 			'"  value="'.$env{$key}.'" />'."\n");
 4054:     }
 4055:     # FIXME do a check for any duplicated user ids...
 4056:     # FIXME do a check for any invalid user ids?...
 4057:     $request->print('<input type="submit" value="Assign Grades" /><br />
 4058: <hr /></form>'."\n");
 4059:     return '';
 4060: }
 4061: 
 4062: sub get_fields {
 4063:     my %fields;
 4064:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 4065:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 4066: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 4067: 	    if ($env{'form.f'.$i} ne 'none') {
 4068: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 4069: 	    }
 4070: 	} else {
 4071: 	    if ($env{'form.f'.$i} ne 'none') {
 4072: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 4073: 	    }
 4074: 	}
 4075:     }
 4076:     return %fields;
 4077: }
 4078: 
 4079: sub csvuploadassign {
 4080:     my ($request,$symb)= @_;
 4081:     if (!$symb) {return '';}
 4082:     my $error_msg = '';
 4083:     &Apache::loncommon::load_tmp_file($request);
 4084:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 4085:     my %fields=&get_fields();
 4086:     my $courseid=$env{'request.course.id'};
 4087:     my ($classlist) = &getclasslist('all',0);
 4088:     my @notallowed;
 4089:     my @skipped;
 4090:     my $countdone=0;
 4091:     foreach my $grade (@gradedata) {
 4092: 	my %entries=&Apache::loncommon::record_sep($grade);
 4093: 	my $domain;
 4094: 	if ($entries{$fields{'domain'}}) {
 4095: 	    $domain=$entries{$fields{'domain'}};
 4096: 	} else {
 4097: 	    $domain=$env{'form.default_domain'};
 4098: 	}
 4099: 	$domain=~s/\s//g;
 4100: 	my $username=$entries{$fields{'username'}};
 4101: 	$username=~s/\s//g;
 4102: 	if (!$username) {
 4103: 	    my $id=$entries{$fields{'ID'}};
 4104: 	    $id=~s/\s//g;
 4105: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 4106: 	    $username=$ids{$id};
 4107: 	}
 4108: 	if (!exists($$classlist{"$username:$domain"})) {
 4109: 	    my $id=$entries{$fields{'ID'}};
 4110: 	    $id=~s/\s//g;
 4111: 	    if ($id) {
 4112: 		push(@skipped,"$id:$domain");
 4113: 	    } else {
 4114: 		push(@skipped,"$username:$domain");
 4115: 	    }
 4116: 	    next;
 4117: 	}
 4118: 	my $usec=$classlist->{"$username:$domain"}[5];
 4119: 	if (!&canmodify($usec)) {
 4120: 	    push(@notallowed,"$username:$domain");
 4121: 	    next;
 4122: 	}
 4123: 	my %points;
 4124: 	my %grades;
 4125: 	foreach my $dest (keys(%fields)) {
 4126: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 4127: 		$dest eq 'domain') { next; }
 4128: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 4129: 	    if ($dest=~/stores_(.*)_points/) {
 4130: 		my $part=$1;
 4131: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 4132: 					      $symb,$domain,$username);
 4133:                 if ($wgt) {
 4134:                     $entries{$fields{$dest}}=~s/\s//g;
 4135:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 4136:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 4137:                                           : 'correct_by_override';
 4138:                     if ($pcr>1) {
 4139:                        push(@skipped,&mt("[_1]: point value larger than weight","$username:$domain"));
 4140:                     }
 4141:                     $grades{"resource.$part.awarded"}=$pcr;
 4142:                     $grades{"resource.$part.solved"}=$award;
 4143:                     $points{$part}=1;
 4144:                 } else {
 4145:                     $error_msg = "<br />" .
 4146:                         &mt("Some point values were assigned"
 4147:                             ." for problems with a weight "
 4148:                             ."of zero. These values were "
 4149:                             ."ignored.");
 4150:                 }
 4151: 	    } else {
 4152: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 4153: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 4154: 		my $store_key=$dest;
 4155: 		$store_key=~s/^stores/resource/;
 4156: 		$store_key=~s/_/\./g;
 4157: 		$grades{$store_key}=$entries{$fields{$dest}};
 4158: 	    }
 4159: 	}
 4160: 	if (! %grades) { 
 4161:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 4162:         } else {
 4163: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 4164: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 4165: 					   $env{'request.course.id'},
 4166: 					   $domain,$username);
 4167: 	   if ($result eq 'ok') {
 4168: # Successfully stored
 4169: 	      $request->print('.');
 4170: # Remove from grading queue
 4171:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
 4172:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
 4173:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
 4174:                                              $domain,$username);
 4175:               $countdone++;
 4176:            } else {
 4177: 	      $request->print("<p><span class=\"LC_error\">".
 4178:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 4179:                                   "$username:$domain",$result)."</span></p>");
 4180: 	   }
 4181: 	   $request->rflush();
 4182:         }
 4183:     }
 4184:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
 4185:     if (@skipped) {
 4186: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
 4187:         $request->print(join(', ',@skipped));
 4188:     }
 4189:     if (@notallowed) {
 4190: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
 4191: 	$request->print(join(', ',@notallowed));
 4192:     }
 4193:     $request->print("<br />\n");
 4194:     return $error_msg;
 4195: }
 4196: #------------- end of section for handling csv file upload ---------
 4197: #
 4198: #-------------------------------------------------------------------
 4199: #
 4200: #-------------- Next few routines handle grading by page/sequence
 4201: #
 4202: #--- Select a page/sequence and a student to grade
 4203: sub pickStudentPage {
 4204:     my ($request,$symb) = @_;
 4205: 
 4206:     my $alertmsg = &mt('Please select the student you wish to grade.');
 4207:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
 4208: 
 4209: function checkPickOne(formname) {
 4210:     if (radioSelection(formname.student) == null) {
 4211: 	alert("$alertmsg");
 4212: 	return;
 4213:     }
 4214:     ptr = pullDownSelection(formname.selectpage);
 4215:     formname.page.value = formname["page"+ptr].value;
 4216:     formname.title.value = formname["title"+ptr].value;
 4217:     formname.submit();
 4218: }
 4219: 
 4220: LISTJAVASCRIPT
 4221:     &commonJSfunctions($request);
 4222: 
 4223:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4224:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4225:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4226: 
 4227:     my $result='<h3><span class="LC_info">&nbsp;'.
 4228: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 4229: 
 4230:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 4231:     my $map_error;
 4232:     my ($titles,$symbx) = &getSymbMap($map_error);
 4233:     if ($map_error) {
 4234:         $request->print(&navmap_errormsg());
 4235:         return; 
 4236:     }
 4237:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 4238: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 4239: #    my $type=($curpage =~ /\.(page|sequence)/);
 4240:     my $select = '<select name="selectpage">'."\n";
 4241:     my $ctr=0;
 4242:     foreach (@$titles) {
 4243: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4244: 	$select.='<option value="'.$ctr.'" '.
 4245: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4246: 	    '>'.$showtitle.'</option>'."\n";
 4247: 	$ctr++;
 4248:     }
 4249:     $select.= '</select>';
 4250:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
 4251: 
 4252:     $ctr=0;
 4253:     foreach (@$titles) {
 4254: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4255: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 4256: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 4257: 	$ctr++;
 4258:     }
 4259:     $result.='<input type="hidden" name="page" />'."\n".
 4260: 	'<input type="hidden" name="title" />'."\n";
 4261: 
 4262:     my $options =
 4263: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
 4264: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
 4265:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
 4266: 
 4267:     $options =
 4268: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
 4269: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
 4270: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
 4271:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
 4272:     
 4273:     $result.=&build_section_inputs();
 4274:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4275:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 4276: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 4277: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."<br />\n";
 4278: 
 4279:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
 4280: 
 4281:     $result.='&nbsp;<input type="button" '.
 4282:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 4283: 
 4284:     $request->print($result);
 4285: 
 4286:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 4287: 	&Apache::loncommon::start_data_table().
 4288: 	&Apache::loncommon::start_data_table_header_row().
 4289: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4290: 	'<th>'.&nameUserString('header').'</th>'.
 4291: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4292: 	'<th>'.&nameUserString('header').'</th>'.
 4293: 	&Apache::loncommon::end_data_table_header_row();
 4294:  
 4295:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 4296:     my $ptr = 1;
 4297:     foreach my $student (sort 
 4298: 			 {
 4299: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4300: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4301: 			     }
 4302: 			     return $a cmp $b;
 4303: 			 } (keys(%$fullname))) {
 4304: 	my ($uname,$udom) = split(/:/,$student);
 4305: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 4306:                                   : '</td>');
 4307: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 4308: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 4309: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 4310: 	$studentTable.=
 4311: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 4312:                          : '');
 4313: 	$ptr++;
 4314:     }
 4315:     if ($ptr%2 == 0) {
 4316: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 4317: 	    &Apache::loncommon::end_data_table_row();
 4318:     }
 4319:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 4320:     $studentTable.='<input type="button" '.
 4321:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 4322: 
 4323:     $request->print($studentTable);
 4324: 
 4325:     return '';
 4326: }
 4327: 
 4328: sub getSymbMap {
 4329:     my ($map_error) = @_;
 4330:     my $navmap = Apache::lonnavmaps::navmap->new();
 4331:     unless (ref($navmap)) {
 4332:         if (ref($map_error)) {
 4333:             $$map_error = 'navmap';
 4334:         }
 4335:         return;
 4336:     }
 4337:     my %symbx = ();
 4338:     my @titles = ();
 4339:     my $minder = 0;
 4340: 
 4341:     # Gather every sequence that has problems.
 4342:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 4343: 					       1,0,1);
 4344:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 4345: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 4346: 	    my $title = $minder.'.'.
 4347: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 4348: 	    push(@titles, $title); # minder in case two titles are identical
 4349: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 4350: 	    $minder++;
 4351: 	}
 4352:     }
 4353:     return \@titles,\%symbx;
 4354: }
 4355: 
 4356: #
 4357: #--- Displays a page/sequence w/wo problems, w/wo submissions
 4358: sub displayPage {
 4359:     my ($request,$symb) = @_;
 4360:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4361:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4362:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4363:     my $pageTitle = $env{'form.page'};
 4364:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4365:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4366:     my $usec=$classlist->{$env{'form.student'}}[5];
 4367: 
 4368:     #need to make sure we have the correct data for later EXT calls, 
 4369:     #thus invalidate the cache
 4370:     &Apache::lonnet::devalidatecourseresdata(
 4371:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 4372:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 4373:     &Apache::lonnet::clear_EXT_cache_status();
 4374: 
 4375:     if (!&canview($usec)) {
 4376: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
 4377: 	return;
 4378:     }
 4379:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4380:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 4381: 	'</h3>'."\n";
 4382:     $env{'form.CODE'} = uc($env{'form.CODE'});
 4383:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 4384: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 4385:     } else {
 4386: 	delete($env{'form.CODE'});
 4387:     }
 4388:     &sub_page_js($request);
 4389:     $request->print($result);
 4390: 
 4391:     my $navmap = Apache::lonnavmaps::navmap->new();
 4392:     unless (ref($navmap)) {
 4393:         $request->print(&navmap_errormsg());
 4394:         return;
 4395:     }
 4396:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 4397:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4398:     if (!$map) {
 4399: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 4400: 	return; 
 4401:     }
 4402:     my $iterator = $navmap->getIterator($map->map_start(),
 4403: 					$map->map_finish());
 4404: 
 4405:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 4406: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 4407: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 4408: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 4409: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 4410: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 4411: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4412: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
 4413: 
 4414:     if (defined($env{'form.CODE'})) {
 4415: 	$studentTable.=
 4416: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 4417:     }
 4418:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 4419: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 4420: 
 4421:     $studentTable.='&nbsp;<span class="LC_info">'.
 4422:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
 4423:         '</span>'."\n".
 4424: 	&Apache::loncommon::start_data_table().
 4425: 	&Apache::loncommon::start_data_table_header_row().
 4426: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
 4427: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 4428: 	&Apache::loncommon::end_data_table_header_row();
 4429: 
 4430:     &Apache::lonxml::clear_problem_counter();
 4431:     my ($depth,$question,$prob) = (1,1,1);
 4432:     $iterator->next(); # skip the first BEGIN_MAP
 4433:     my $curRes = $iterator->next(); # for "current resource"
 4434:     while ($depth > 0) {
 4435:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4436:         if($curRes == $iterator->END_MAP) { $depth--; }
 4437: 
 4438:         if (ref($curRes) && $curRes->is_problem()) {
 4439: 	    my $parts = $curRes->parts();
 4440:             my $title = $curRes->compTitle();
 4441: 	    my $symbx = $curRes->symb();
 4442: 	    $studentTable.=
 4443: 		&Apache::loncommon::start_data_table_row().
 4444: 		'<td align="center" valign="top" >'.$prob.
 4445: 		(scalar(@{$parts}) == 1 ? '' 
 4446: 		                        : '<br />('.&mt('[_1]parts)',
 4447: 							scalar(@{$parts}).'&nbsp;')
 4448: 		 ).
 4449: 		 '</td>';
 4450: 	    $studentTable.='<td valign="top">';
 4451: 	    my %form = ('CODE' => $env{'form.CODE'},);
 4452: 	    if ($env{'form.vProb'} eq 'yes' ) {
 4453: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 4454: 					     undef,'both',\%form);
 4455: 	    } else {
 4456: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 4457: 		$companswer =~ s|<form(.*?)>||g;
 4458: 		$companswer =~ s|</form>||g;
 4459: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 4460: #		    $companswer =~ s/$1/ /ms;
 4461: #		    $request->print('match='.$1."<br />\n");
 4462: #		}
 4463: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 4464: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 4465: 	    }
 4466: 
 4467: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 4468: 
 4469: 	    if ($env{'form.lastSub'} eq 'datesub') {
 4470: 		if ($record{'version'} eq '') {
 4471: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
 4472: 		} else {
 4473: 		    my %responseType = ();
 4474: 		    foreach my $partid (@{$parts}) {
 4475: 			my @responseIds =$curRes->responseIds($partid);
 4476: 			my @responseType =$curRes->responseType($partid);
 4477: 			my %responseIds;
 4478: 			for (my $i=0;$i<=$#responseIds;$i++) {
 4479: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 4480: 			}
 4481: 			$responseType{$partid} = \%responseIds;
 4482: 		    }
 4483: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 4484: 
 4485: 		}
 4486: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 4487: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 4488: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 4489: 									$env{'request.course.id'},
 4490: 									'','.submission');
 4491:  
 4492: 	    }
 4493: 	    if (&canmodify($usec)) {
 4494:             $studentTable.=&gradeBox_start();
 4495: 		foreach my $partid (@{$parts}) {
 4496: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 4497: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 4498: 		    $question++;
 4499: 		}
 4500:             $studentTable.=&gradeBox_end();
 4501: 		$prob++;
 4502: 	    }
 4503: 	    $studentTable.='</td></tr>';
 4504: 
 4505: 	}
 4506:         $curRes = $iterator->next();
 4507:     }
 4508: 
 4509:     $studentTable.=
 4510:         '</table>'."\n".
 4511:         '<input type="button" value="'.&mt('Save').'" '.
 4512:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 4513:         '</form>'."\n";
 4514:     $request->print($studentTable);
 4515: 
 4516:     return '';
 4517: }
 4518: 
 4519: sub displaySubByDates {
 4520:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 4521:     my $isCODE=0;
 4522:     my $isTask = ($symb =~/\.task$/);
 4523:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 4524:     my $studentTable=&Apache::loncommon::start_data_table().
 4525: 	&Apache::loncommon::start_data_table_header_row().
 4526: 	'<th>'.&mt('Date/Time').'</th>'.
 4527: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 4528: 	'<th>'.&mt('Submission').'</th>'.
 4529: 	'<th>'.&mt('Status').'</th>'.
 4530: 	&Apache::loncommon::end_data_table_header_row();
 4531:     my ($version);
 4532:     my %mark;
 4533:     my %orders;
 4534:     $mark{'correct_by_student'} = $checkIcon;
 4535:     if (!exists($$record{'1:timestamp'})) {
 4536: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 4537:     }
 4538: 
 4539:     my $interaction;
 4540:     my $no_increment = 1;
 4541:     my %lastrndseed;
 4542:     for ($version=1;$version<=$$record{'version'};$version++) {
 4543: 	my $timestamp = 
 4544: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 4545: 	if (exists($$record{$version.':resource.0.version'})) {
 4546: 	    $interaction = $$record{$version.':resource.0.version'};
 4547: 	}
 4548: 
 4549: 	my $where = ($isTask ? "$version:resource.$interaction"
 4550: 		             : "$version:resource");
 4551: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 4552: 	    '<td>'.$timestamp.'</td>';
 4553: 	if ($isCODE) {
 4554: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 4555: 	}
 4556: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 4557: 	my @displaySub = ();
 4558: 	foreach my $partid (@{$parts}) {
 4559:             my ($hidden,$type);
 4560:             $type = $$record{$version.':resource.'.$partid.'.type'};
 4561:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
 4562:                 $hidden = 1;
 4563:             }
 4564: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
 4565: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 4566: 	    
 4567: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 4568: 	    my $display_part=&get_display_part($partid,$symb);
 4569: 	    foreach my $matchKey (@matchKey) {
 4570: 		if (exists($$record{$version.':'.$matchKey}) &&
 4571: 		    $$record{$version.':'.$matchKey} ne '') {
 4572:                     
 4573: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 4574: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 4575:                     $displaySub[0].='<span class="LC_nobreak"';
 4576:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
 4577:                                    .' <span class="LC_internal_info">'
 4578:                                    .'('.&mt('Response ID: [_1]',$responseId).')'
 4579:                                    .'</span>'
 4580:                                    .' <b>';
 4581:                     if ($hidden) {
 4582:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
 4583:                     } else {
 4584:                         my ($trial,$rndseed,$newvariation);
 4585:                         if ($type eq 'randomizetry') {
 4586:                             $trial = $$record{"$where.$partid.tries"};
 4587:                             $rndseed = $$record{"$where.$partid.rndseed"};
 4588:                         }
 4589: 		        if ($$record{"$where.$partid.tries"} eq '') {
 4590: 			    $displaySub[0].=&mt('Trial not counted');
 4591: 		        } else {
 4592: 			    $displaySub[0].=&mt('Trial: [_1]',
 4593: 					    $$record{"$where.$partid.tries"});
 4594:                             if ($rndseed || $lastrndseed{$partid}) {
 4595:                                 if ($rndseed ne $lastrndseed{$partid}) {
 4596:                                     $newvariation = '&nbsp;('.&mt('New variation this try').')';
 4597:                                 }
 4598:                             }
 4599:                             $lastrndseed{$partid} = $rndseed;
 4600: 		        }
 4601: 		        my $responseType=($isTask ? 'Task'
 4602:                                               : $responseType->{$partid}->{$responseId});
 4603: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
 4604: 		        if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
 4605: 			    $orders{$partid}->{$responseId}=
 4606: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
 4607:                                            $no_increment,$type,$trial,$rndseed);
 4608: 		        }
 4609: 		        $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
 4610: 		        $displaySub[0].='&nbsp; '.
 4611: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
 4612:                     }
 4613: 		}
 4614: 	    }
 4615: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 4616: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 4617: 				    $$record{"$where.$partid.checkedin"},
 4618: 				    $$record{"$where.$partid.checkedin.slot"}).
 4619: 					'<br />';
 4620: 	    }
 4621: 	    if (exists $$record{"$where.$partid.award"}) {
 4622: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 4623: 		    lc($$record{"$where.$partid.award"}).' '.
 4624: 		    $mark{$$record{"$where.$partid.solved"}}.
 4625: 		    '<br />';
 4626: 	    }
 4627: 	    if (exists $$record{"$where.$partid.regrader"}) {
 4628: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 4629: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4630: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 4631: 		$displaySub[2].=
 4632: 		    $$record{"$version:resource.$partid.regrader"}.
 4633: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4634: 	    }
 4635: 	}
 4636: 	# needed because old essay regrader has not parts info
 4637: 	if (exists $$record{"$version:resource.regrader"}) {
 4638: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 4639: 	}
 4640: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 4641: 	if ($displaySub[2]) {
 4642: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 4643: 	}
 4644: 	$studentTable.='&nbsp;</td>'.
 4645: 	    &Apache::loncommon::end_data_table_row();
 4646:     }
 4647:     $studentTable.=&Apache::loncommon::end_data_table();
 4648:     return $studentTable;
 4649: }
 4650: 
 4651: sub updateGradeByPage {
 4652:     my ($request,$symb) = @_;
 4653: 
 4654:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4655:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4656:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4657:     my $pageTitle = $env{'form.page'};
 4658:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4659:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4660:     my $usec=$classlist->{$env{'form.student'}}[5];
 4661:     if (!&canmodify($usec)) {
 4662: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 4663: 	return;
 4664:     }
 4665:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4666:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 4667: 	'</h3>'."\n";
 4668: 
 4669:     $request->print($result);
 4670: 
 4671: 
 4672:     my $navmap = Apache::lonnavmaps::navmap->new();
 4673:     unless (ref($navmap)) {
 4674:         $request->print(&navmap_errormsg());
 4675:         return;
 4676:     }
 4677:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 4678:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4679:     if (!$map) {
 4680: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 4681: 	return; 
 4682:     }
 4683:     my $iterator = $navmap->getIterator($map->map_start(),
 4684: 					$map->map_finish());
 4685: 
 4686:     my $studentTable=
 4687: 	&Apache::loncommon::start_data_table().
 4688: 	&Apache::loncommon::start_data_table_header_row().
 4689: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 4690: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 4691: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 4692: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 4693: 	&Apache::loncommon::end_data_table_header_row();
 4694: 
 4695:     $iterator->next(); # skip the first BEGIN_MAP
 4696:     my $curRes = $iterator->next(); # for "current resource"
 4697:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
 4698:     while ($depth > 0) {
 4699:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4700:         if($curRes == $iterator->END_MAP) { $depth--; }
 4701: 
 4702:         if (ref($curRes) && $curRes->is_problem()) {
 4703: 	    my $parts = $curRes->parts();
 4704:             my $title = $curRes->compTitle();
 4705: 	    my $symbx = $curRes->symb();
 4706: 	    $studentTable.=
 4707: 		&Apache::loncommon::start_data_table_row().
 4708: 		'<td align="center" valign="top" >'.$prob.
 4709: 		(scalar(@{$parts}) == 1 ? '' 
 4710:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
 4711: 		.')').'</td>';
 4712: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 4713: 
 4714: 	    my %newrecord=();
 4715: 	    my @displayPts=();
 4716:             my %aggregate = ();
 4717:             my $aggregateflag = 0;
 4718: 	    foreach my $partid (@{$parts}) {
 4719: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 4720: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 4721: 
 4722: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 4723: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 4724: 		my $partial = $newpts/$wgt;
 4725: 		my $score;
 4726: 		if ($partial > 0) {
 4727: 		    $score = 'correct_by_override';
 4728: 		} elsif ($newpts ne '') { #empty is taken as 0
 4729: 		    $score = 'incorrect_by_override';
 4730: 		}
 4731: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 4732: 		if ($dropMenu eq 'excused') {
 4733: 		    $partial = '';
 4734: 		    $score = 'excused';
 4735: 		} elsif ($dropMenu eq 'reset status'
 4736: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 4737: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 4738: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 4739: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 4740: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 4741: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 4742: 		    $changeflag++;
 4743: 		    $newpts = '';
 4744:                     
 4745:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 4746:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 4747:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 4748:                     if ($aggtries > 0) {
 4749:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4750:                         $aggregateflag = 1;
 4751:                     }
 4752: 		}
 4753: 		my $display_part=&get_display_part($partid,$curRes->symb());
 4754: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 4755: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4756: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 4757: 		    '&nbsp;<br />';
 4758: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4759: 		     (($score eq 'excused') ? 'excused' : $newpts).
 4760: 		    '&nbsp;<br />';
 4761: 		$question++;
 4762: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 4763: 
 4764: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 4765: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 4766: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 4767: 		    if (scalar(keys(%newrecord)) > 0);
 4768: 
 4769: 		$changeflag++;
 4770: 	    }
 4771: 	    if (scalar(keys(%newrecord)) > 0) {
 4772: 		my %record = 
 4773: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 4774: 					     $udom,$uname);
 4775: 
 4776: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 4777: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 4778: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 4779: 		    $newrecord{'resource.CODE'} = '';
 4780: 		}
 4781: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 4782: 					$udom,$uname);
 4783: 		%record = &Apache::lonnet::restore($symbx,
 4784: 						   $env{'request.course.id'},
 4785: 						   $udom,$uname);
 4786: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 4787: 					     $cdom,$cnum,$udom,$uname);
 4788: 	    }
 4789: 	    
 4790:             if ($aggregateflag) {
 4791:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4792:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 4793:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 4794:             }
 4795: 
 4796: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 4797: 		'<td valign="top">'.$displayPts[1].'</td>'.
 4798: 		&Apache::loncommon::end_data_table_row();
 4799: 
 4800: 	    $prob++;
 4801: 	}
 4802:         $curRes = $iterator->next();
 4803:     }
 4804: 
 4805:     $studentTable.=&Apache::loncommon::end_data_table();
 4806:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 4807: 		  &mt('The scores were changed for [quant,_1,problem].',
 4808: 		  $changeflag));
 4809:     $request->print($grademsg.$studentTable);
 4810: 
 4811:     return '';
 4812: }
 4813: 
 4814: #-------- end of section for handling grading by page/sequence ---------
 4815: #
 4816: #-------------------------------------------------------------------
 4817: 
 4818: #-------------------- Bubblesheet (Scantron) Grading -------------------
 4819: #
 4820: #------ start of section for handling grading by page/sequence ---------
 4821: 
 4822: =pod
 4823: 
 4824: =head1 Bubble sheet grading routines
 4825: 
 4826:   For this documentation:
 4827: 
 4828:    'scanline' refers to the full line of characters
 4829:    from the file that we are parsing that represents one entire sheet
 4830: 
 4831:    'bubble line' refers to the data
 4832:    representing the line of bubbles that are on the physical bubble sheet
 4833: 
 4834: 
 4835: The overall process is that a scanned in bubble sheet data is uploaded
 4836: into a course. When a user wants to grade, they select a
 4837: sequence/folder of resources, a file of bubble sheet info, and pick
 4838: one of the predefined configurations for what each scanline looks
 4839: like.
 4840: 
 4841: Next each scanline is checked for any errors of either 'missing
 4842: bubbles' (it's an error because it may have been mis-scanned
 4843: because too light bubbling), 'double bubble' (each bubble line should
 4844: have no more that one letter picked), invalid or duplicated CODE,
 4845: invalid student/employee ID
 4846: 
 4847: If the CODE option is used that determines the randomization of the
 4848: homework problems, either way the student/employee ID is looked up into a
 4849: username:domain.
 4850: 
 4851: During the validation phase the instructor can choose to skip scanlines. 
 4852: 
 4853: After the validation phase, there are now 3 bubble sheet files
 4854: 
 4855:   scantron_original_filename (unmodified original file)
 4856:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 4857:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 4858: 
 4859: Also there is a separate hash nohist_scantrondata that contains extra
 4860: correction information that isn't representable in the bubble sheet
 4861: file (see &scantron_getfile() for more information)
 4862: 
 4863: After all scanlines are either valid, marked as valid or skipped, then
 4864: foreach line foreach problem in the picked sequence, an ssi request is
 4865: made that simulates a user submitting their selected letter(s) against
 4866: the homework problem.
 4867: 
 4868: =over 4
 4869: 
 4870: 
 4871: 
 4872: =item defaultFormData
 4873: 
 4874:   Returns html hidden inputs used to hold context/default values.
 4875: 
 4876:  Arguments:
 4877:   $symb - $symb of the current resource 
 4878: 
 4879: =cut
 4880: 
 4881: sub defaultFormData {
 4882:     my ($symb)=@_;
 4883:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />';
 4884: }
 4885: 
 4886: 
 4887: =pod 
 4888: 
 4889: =item getSequenceDropDown
 4890: 
 4891:    Return html dropdown of possible sequences to grade
 4892:  
 4893:  Arguments:
 4894:    $symb - $symb of the current resource
 4895:    $map_error - ref to scalar which will container error if
 4896:                 $navmap object is unavailable in &getSymbMap().
 4897: 
 4898: =cut
 4899: 
 4900: sub getSequenceDropDown {
 4901:     my ($symb,$map_error)=@_;
 4902:     my $result='<select name="selectpage">'."\n";
 4903:     my ($titles,$symbx) = &getSymbMap($map_error);
 4904:     if (ref($map_error)) {
 4905:         return if ($$map_error);
 4906:     }
 4907:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 4908:     my $ctr=0;
 4909:     foreach (@$titles) {
 4910: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4911: 	$result.='<option value="'.$$symbx{$_}.'" '.
 4912: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4913: 	    '>'.$showtitle.'</option>'."\n";
 4914: 	$ctr++;
 4915:     }
 4916:     $result.= '</select>';
 4917:     return $result;
 4918: }
 4919: 
 4920: my %bubble_lines_per_response;     # no. bubble lines for each response.
 4921:                                    # key is zero-based index - 0, 1, 2 ...
 4922: 
 4923: my %first_bubble_line;             # First bubble line no. for each bubble.
 4924: 
 4925: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 4926:                                    # matchresponse or rankresponse, where 
 4927:                                    # an individual response can have multiple 
 4928:                                    # lines
 4929: 
 4930: my %responsetype_per_response;     # responsetype for each response
 4931: 
 4932: # Save and restore the bubble lines array to the form env.
 4933: 
 4934: 
 4935: sub save_bubble_lines {
 4936:     foreach my $line (keys(%bubble_lines_per_response)) {
 4937: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 4938: 	$env{"form.scantron.first_bubble_line.$line"} =
 4939: 	    $first_bubble_line{$line};
 4940:         $env{"form.scantron.sub_bubblelines.$line"} = 
 4941:             $subdivided_bubble_lines{$line};
 4942:         $env{"form.scantron.responsetype.$line"} =
 4943:             $responsetype_per_response{$line};
 4944:     }
 4945: }
 4946: 
 4947: 
 4948: sub restore_bubble_lines {
 4949:     my $line = 0;
 4950:     %bubble_lines_per_response = ();
 4951:     while ($env{"form.scantron.bubblelines.$line"}) {
 4952: 	my $value = $env{"form.scantron.bubblelines.$line"};
 4953: 	$bubble_lines_per_response{$line} = $value;
 4954: 	$first_bubble_line{$line}  =
 4955: 	    $env{"form.scantron.first_bubble_line.$line"};
 4956:         $subdivided_bubble_lines{$line} =
 4957:             $env{"form.scantron.sub_bubblelines.$line"};
 4958:         $responsetype_per_response{$line} =
 4959:             $env{"form.scantron.responsetype.$line"};
 4960: 	$line++;
 4961:     }
 4962: }
 4963: 
 4964: #  Given the parsed scanline, get the response for 
 4965: #  'answer' number n:
 4966: 
 4967: sub get_response_bubbles {
 4968:     my ($parsed_line, $response)  = @_;
 4969: 
 4970:     my $bubble_line = $first_bubble_line{$response-1} +1;
 4971:     my $bubble_lines= $bubble_lines_per_response{$response-1};
 4972:     
 4973:     my $selected = "";
 4974: 
 4975:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
 4976: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
 4977: 	$bubble_line++;
 4978:     }
 4979:     return $selected;
 4980: }
 4981: 
 4982: =pod 
 4983: 
 4984: =item scantron_filenames
 4985: 
 4986:    Returns a list of the scantron files in the current course 
 4987: 
 4988: =cut
 4989: 
 4990: sub scantron_filenames {
 4991:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4992:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4993:     my $getpropath = 1;
 4994:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
 4995:                                        $getpropath);
 4996:     my @possiblenames;
 4997:     foreach my $filename (sort(@files)) {
 4998: 	($filename)=split(/&/,$filename);
 4999: 	if ($filename!~/^scantron_orig_/) { next ; }
 5000: 	$filename=~s/^scantron_orig_//;
 5001: 	push(@possiblenames,$filename);
 5002:     }
 5003:     return @possiblenames;
 5004: }
 5005: 
 5006: =pod 
 5007: 
 5008: =item scantron_uploads
 5009: 
 5010:    Returns  html drop-down list of scantron files in current course.
 5011: 
 5012:  Arguments:
 5013:    $file2grade - filename to set as selected in the dropdown
 5014: 
 5015: =cut
 5016: 
 5017: sub scantron_uploads {
 5018:     my ($file2grade) = @_;
 5019:     my $result=	'<select name="scantron_selectfile">';
 5020:     $result.="<option></option>";
 5021:     foreach my $filename (sort(&scantron_filenames())) {
 5022: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 5023:     }
 5024:     $result.="</select>";
 5025:     return $result;
 5026: }
 5027: 
 5028: =pod 
 5029: 
 5030: =item scantron_scantab
 5031: 
 5032:   Returns html drop down of the scantron formats in the scantronformat.tab
 5033:   file.
 5034: 
 5035: =cut
 5036: 
 5037: sub scantron_scantab {
 5038:     my $result='<select name="scantron_format">'."\n";
 5039:     $result.='<option></option>'."\n";
 5040:     my @lines = &get_scantronformat_file();
 5041:     if (@lines > 0) {
 5042:         foreach my $line (@lines) {
 5043:             next if (($line =~ /^\#/) || ($line eq ''));
 5044: 	    my ($name,$descrip)=split(/:/,$line);
 5045: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 5046:         }
 5047:     }
 5048:     $result.='</select>'."\n";
 5049:     return $result;
 5050: }
 5051: 
 5052: =pod
 5053: 
 5054: =item get_scantronformat_file
 5055: 
 5056:   Returns an array containing lines from the scantron format file for
 5057:   the domain of the course.
 5058: 
 5059:   If a url for a custom.tab file is listed in domain's configuration.db, 
 5060:   lines are from this file.
 5061: 
 5062:   Otherwise, if a default.tab has been published in RES space by the 
 5063:   domainconfig user, lines are from this file.
 5064: 
 5065:   Otherwise, fall back to getting lines from the legacy file on the
 5066:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
 5067: 
 5068: =cut
 5069: 
 5070: sub get_scantronformat_file {
 5071:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5072:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
 5073:     my $gottab = 0;
 5074:     my @lines;
 5075:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 5076:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 5077:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 5078:             if ($formatfile ne '-1') {
 5079:                 @lines = split("\n",$formatfile,-1);
 5080:                 $gottab = 1;
 5081:             }
 5082:         }
 5083:     }
 5084:     if (!$gottab) {
 5085:         my $confname = $cdom.'-domainconfig';
 5086:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 5087:         my $formatfile =  &Apache::lonnet::getfile($default);
 5088:         if ($formatfile ne '-1') {
 5089:             @lines = split("\n",$formatfile,-1);
 5090:             $gottab = 1;
 5091:         }
 5092:     }
 5093:     if (!$gottab) {
 5094:         my @domains = &Apache::lonnet::current_machine_domains();
 5095:         if (grep(/^\Q$cdom\E$/,@domains)) {
 5096:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 5097:             @lines = <$fh>;
 5098:             close($fh);
 5099:         } else {
 5100:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
 5101:             @lines = <$fh>;
 5102:             close($fh);
 5103:         }
 5104:     }
 5105:     return @lines;
 5106: }
 5107: 
 5108: =pod 
 5109: 
 5110: =item scantron_CODElist
 5111: 
 5112:   Returns html drop down of the saved CODE lists from current course,
 5113:   generated from earlier printings.
 5114: 
 5115: =cut
 5116: 
 5117: sub scantron_CODElist {
 5118:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5119:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5120:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 5121:     my $namechoice='<option></option>';
 5122:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 5123: 	if ($name =~ /^error: 2 /) { next; }
 5124: 	if ($name =~ /^type\0/) { next; }
 5125: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 5126:     }
 5127:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 5128:     return $namechoice;
 5129: }
 5130: 
 5131: =pod 
 5132: 
 5133: =item scantron_CODEunique
 5134: 
 5135:   Returns the html for "Each CODE to be used once" radio.
 5136: 
 5137: =cut
 5138: 
 5139: sub scantron_CODEunique {
 5140:     my $result='<span class="LC_nobreak">
 5141:                  <label><input type="radio" name="scantron_CODEunique"
 5142:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 5143:                 </span>
 5144:                 <span class="LC_nobreak">
 5145:                  <label><input type="radio" name="scantron_CODEunique"
 5146:                         value="no" />'.&mt('No').' </label>
 5147:                 </span>';
 5148:     return $result;
 5149: }
 5150: 
 5151: =pod 
 5152: 
 5153: =item scantron_selectphase
 5154: 
 5155:   Generates the initial screen to start the bubble sheet process.
 5156:   Allows for - starting a grading run.
 5157:              - downloading existing scan data (original, corrected
 5158:                                                 or skipped info)
 5159: 
 5160:              - uploading new scan data
 5161: 
 5162:  Arguments:
 5163:   $r          - The Apache request object
 5164:   $file2grade - name of the file that contain the scanned data to score
 5165: 
 5166: =cut
 5167: 
 5168: sub scantron_selectphase {
 5169:     my ($r,$file2grade,$symb) = @_;
 5170:     if (!$symb) {return '';}
 5171:     my $map_error;
 5172:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
 5173:     if ($map_error) {
 5174:         $r->print('<br />'.&navmap_errormsg().'<br />');
 5175:         return;
 5176:     }
 5177:     my $default_form_data=&defaultFormData($symb);
 5178:     my $file_selector=&scantron_uploads($file2grade);
 5179:     my $format_selector=&scantron_scantab();
 5180:     my $CODE_selector=&scantron_CODElist();
 5181:     my $CODE_unique=&scantron_CODEunique();
 5182:     my $result;
 5183: 
 5184:     $ssi_error = 0;
 5185: 
 5186:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 5187:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 5188: 
 5189: 	# Chunk of form to prompt for a scantron file upload.
 5190: 
 5191:         $r->print('
 5192:     <br />
 5193:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5194:        '.&Apache::loncommon::start_data_table_header_row().'
 5195:             <th>
 5196:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
 5197:             </th>
 5198:        '.&Apache::loncommon::end_data_table_header_row().'
 5199:        '.&Apache::loncommon::start_data_table_row().'
 5200:             <td>
 5201: ');
 5202:     my $default_form_data=&defaultFormData($symb);
 5203:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5204:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 5205:     $r->print(&Apache::lonhtmlcommon::scripttag('
 5206:     function checkUpload(formname) {
 5207: 	if (formname.upfile.value == "") {
 5208: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
 5209: 	    return false;
 5210: 	}
 5211: 	formname.submit();
 5212:     }'));
 5213:     $r->print('
 5214:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 5215:                 '.$default_form_data.'
 5216:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 5217:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 5218:                 <input name="command" value="scantronupload_save" type="hidden" />
 5219:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
 5220:                 <br />
 5221:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 5222:               </form>
 5223: ');
 5224: 
 5225:         $r->print('
 5226:             </td>
 5227:        '.&Apache::loncommon::end_data_table_row().'
 5228:        '.&Apache::loncommon::end_data_table().'
 5229: ');
 5230:     }
 5231: 
 5232:     # Chunk of form to prompt for a file to grade and how:
 5233: 
 5234:     $result.= '
 5235:     <br />
 5236:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 5237:     <input type="hidden" name="command" value="scantron_warning" />
 5238:     '.$default_form_data.'
 5239:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5240:        '.&Apache::loncommon::start_data_table_header_row().'
 5241:             <th colspan="2">
 5242:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 5243:             </th>
 5244:        '.&Apache::loncommon::end_data_table_header_row().'
 5245:        '.&Apache::loncommon::start_data_table_row().'
 5246:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 5247:        '.&Apache::loncommon::end_data_table_row().'
 5248:        '.&Apache::loncommon::start_data_table_row().'
 5249:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
 5250:        '.&Apache::loncommon::end_data_table_row().'
 5251:        '.&Apache::loncommon::start_data_table_row().'
 5252:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
 5253:        '.&Apache::loncommon::end_data_table_row().'
 5254:        '.&Apache::loncommon::start_data_table_row().'
 5255:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 5256:        '.&Apache::loncommon::end_data_table_row().'
 5257:        '.&Apache::loncommon::start_data_table_row().'
 5258:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 5259:        '.&Apache::loncommon::end_data_table_row().'
 5260:        '.&Apache::loncommon::start_data_table_row().'
 5261: 	    <td> '.&mt('Options:').' </td>
 5262:             <td>
 5263: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 5264:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 5265:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 5266: 	    </td>
 5267:        '.&Apache::loncommon::end_data_table_row().'
 5268:        '.&Apache::loncommon::start_data_table_row().'
 5269:             <td colspan="2">
 5270:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
 5271:             </td>
 5272:        '.&Apache::loncommon::end_data_table_row().'
 5273:     '.&Apache::loncommon::end_data_table().'
 5274:     </form>
 5275: ';
 5276:    
 5277:     $r->print($result);
 5278: 
 5279: 
 5280: 
 5281:     # Chunk of the form that prompts to view a scoring office file,
 5282:     # corrected file, skipped records in a file.
 5283: 
 5284:     $r->print('
 5285:    <br />
 5286:    <form action="/adm/grades" name="scantron_download">
 5287:      '.$default_form_data.'
 5288:      <input type="hidden" name="command" value="scantron_download" />
 5289:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5290:        '.&Apache::loncommon::start_data_table_header_row().'
 5291:               <th>
 5292:                 &nbsp;'.&mt('Download a scoring office file').'
 5293:               </th>
 5294:        '.&Apache::loncommon::end_data_table_header_row().'
 5295:        '.&Apache::loncommon::start_data_table_row().'
 5296:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 5297:                 <br />
 5298:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 5299:        '.&Apache::loncommon::end_data_table_row().'
 5300:      '.&Apache::loncommon::end_data_table().'
 5301:    </form>
 5302:    <br />
 5303: ');
 5304: 
 5305:     &Apache::lonpickcode::code_list($r,2);
 5306: 
 5307:     $r->print('<br /><form method="post" name="checkscantron">'.
 5308:              $default_form_data."\n".
 5309:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 5310:              &Apache::loncommon::start_data_table_header_row()."\n".
 5311:              '<th colspan="2">
 5312:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
 5313:              '</th>'."\n".
 5314:               &Apache::loncommon::end_data_table_header_row()."\n".
 5315:               &Apache::loncommon::start_data_table_row()."\n".
 5316:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 5317:               '<td> '.$sequence_selector.' </td>'.
 5318:               &Apache::loncommon::end_data_table_row()."\n".
 5319:               &Apache::loncommon::start_data_table_row()."\n".
 5320:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 5321:               '<td> '.$file_selector.' </td>'."\n".
 5322:               &Apache::loncommon::end_data_table_row()."\n".
 5323:               &Apache::loncommon::start_data_table_row()."\n".
 5324:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 5325:               '<td> '.$format_selector.' </td>'."\n".
 5326:               &Apache::loncommon::end_data_table_row()."\n".
 5327:               &Apache::loncommon::start_data_table_row()."\n".
 5328:               '<td> '.&mt('Options').' </td>'."\n".
 5329:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
 5330:               &Apache::loncommon::end_data_table_row()."\n".
 5331:               &Apache::loncommon::start_data_table_row()."\n".
 5332:               '<td colspan="2">'."\n".
 5333:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 5334:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
 5335:               '</td>'."\n".
 5336:               &Apache::loncommon::end_data_table_row()."\n".
 5337:               &Apache::loncommon::end_data_table()."\n".
 5338:               '</form><br />');
 5339:     return;
 5340: }
 5341: 
 5342: =pod
 5343: 
 5344: =item get_scantron_config
 5345: 
 5346:    Parse and return the scantron configuration line selected as a
 5347:    hash of configuration file fields.
 5348: 
 5349:  Arguments:
 5350:     which - the name of the configuration to parse from the file.
 5351: 
 5352: 
 5353:  Returns:
 5354:             If the named configuration is not in the file, an empty
 5355:             hash is returned.
 5356:     a hash with the fields
 5357:       name         - internal name for the this configuration setup
 5358:       description  - text to display to operator that describes this config
 5359:       CODElocation - if 0 or the string 'none'
 5360:                           - no CODE exists for this config
 5361:                      if -1 || the string 'letter'
 5362:                           - a CODE exists for this config and is
 5363:                             a string of letters
 5364:                      Unsupported value (but planned for future support)
 5365:                           if a positive integer
 5366:                                - The CODE exists as the first n items from
 5367:                                  the question section of the form
 5368:                           if the string 'number'
 5369:                                - The CODE exists for this config and is
 5370:                                  a string of numbers
 5371:       CODEstart   - (only matter if a CODE exists) column in the line where
 5372:                      the CODE starts
 5373:       CODElength  - length of the CODE
 5374:       IDstart     - column where the student/employee ID starts
 5375:       IDlength    - length of the student/employee ID info
 5376:       Qstart      - column where the information from the bubbled
 5377:                     'questions' start
 5378:       Qlength     - number of columns comprising a single bubble line from
 5379:                     the sheet. (usually either 1 or 10)
 5380:       Qon         - either a single character representing the character used
 5381:                     to signal a bubble was chosen in the positional setup, or
 5382:                     the string 'letter' if the letter of the chosen bubble is
 5383:                     in the final, or 'number' if a number representing the
 5384:                     chosen bubble is in the file (1->A 0->J)
 5385:       Qoff        - the character used to represent that a bubble was
 5386:                     left blank
 5387:       PaperID     - if the scanning process generates a unique number for each
 5388:                     sheet scanned the column that this ID number starts in
 5389:       PaperIDlength - number of columns that comprise the unique ID number
 5390:                       for the sheet of paper
 5391:       FirstName   - column that the first name starts in
 5392:       FirstNameLength - number of columns that the first name spans
 5393:  
 5394:       LastName    - column that the last name starts in
 5395:       LastNameLength - number of columns that the last name spans
 5396:       BubblesPerRow - number of bubbles available in each row used to 
 5397:                       bubble an answer. (If not specified, 10 assumed).
 5398: =cut
 5399: 
 5400: sub get_scantron_config {
 5401:     my ($which) = @_;
 5402:     my @lines = &get_scantronformat_file();
 5403:     my %config;
 5404:     #FIXME probably should move to XML it has already gotten a bit much now
 5405:     foreach my $line (@lines) {
 5406: 	my ($name,$descrip)=split(/:/,$line);
 5407: 	if ($name ne $which ) { next; }
 5408: 	chomp($line);
 5409: 	my @config=split(/:/,$line);
 5410: 	$config{'name'}=$config[0];
 5411: 	$config{'description'}=$config[1];
 5412: 	$config{'CODElocation'}=$config[2];
 5413: 	$config{'CODEstart'}=$config[3];
 5414: 	$config{'CODElength'}=$config[4];
 5415: 	$config{'IDstart'}=$config[5];
 5416: 	$config{'IDlength'}=$config[6];
 5417: 	$config{'Qstart'}=$config[7];
 5418:  	$config{'Qlength'}=$config[8];
 5419: 	$config{'Qoff'}=$config[9];
 5420: 	$config{'Qon'}=$config[10];
 5421: 	$config{'PaperID'}=$config[11];
 5422: 	$config{'PaperIDlength'}=$config[12];
 5423: 	$config{'FirstName'}=$config[13];
 5424: 	$config{'FirstNamelength'}=$config[14];
 5425: 	$config{'LastName'}=$config[15];
 5426: 	$config{'LastNamelength'}=$config[16];
 5427:         $config{'BubblesPerRow'}=$config[17];
 5428: 	last;
 5429:     }
 5430:     return %config;
 5431: }
 5432: 
 5433: =pod 
 5434: 
 5435: =item username_to_idmap
 5436: 
 5437:     creates a hash keyed by student/employee ID with values of the corresponding
 5438:     student username:domain.
 5439: 
 5440:   Arguments:
 5441: 
 5442:     $classlist - reference to the class list hash. This is a hash
 5443:                  keyed by student name:domain  whose elements are references
 5444:                  to arrays containing various chunks of information
 5445:                  about the student. (See loncoursedata for more info).
 5446: 
 5447:   Returns
 5448:     %idmap - the constructed hash
 5449: 
 5450: =cut
 5451: 
 5452: sub username_to_idmap {
 5453:     my ($classlist)= @_;
 5454:     my %idmap;
 5455:     foreach my $student (keys(%$classlist)) {
 5456: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
 5457: 	    $student;
 5458:     }
 5459:     return %idmap;
 5460: }
 5461: 
 5462: =pod
 5463: 
 5464: =item scantron_fixup_scanline
 5465: 
 5466:    Process a requested correction to a scanline.
 5467: 
 5468:   Arguments:
 5469:     $scantron_config   - hash from &get_scantron_config()
 5470:     $scan_data         - hash of correction information 
 5471:                           (see &scantron_getfile())
 5472:     $line              - existing scanline
 5473:     $whichline         - line number of the passed in scanline
 5474:     $field             - type of change to process 
 5475:                          (either 
 5476:                           'ID'     -> correct the student/employee ID
 5477:                           'CODE'   -> correct the CODE
 5478:                           'answer' -> fixup the submitted answers)
 5479:     
 5480:    $args               - hash of additional info,
 5481:                           - 'ID' 
 5482:                                'newid' -> studentID to use in replacement
 5483:                                           of existing one
 5484:                           - 'CODE' 
 5485:                                'CODE_ignore_dup' - set to true if duplicates
 5486:                                                    should be ignored.
 5487: 	                       'CODE' - is new code or 'use_unfound'
 5488:                                         if the existing unfound code should
 5489:                                         be used as is
 5490:                           - 'answer'
 5491:                                'response' - new answer or 'none' if blank
 5492:                                'question' - the bubble line to change
 5493:                                'questionnum' - the question identifier,
 5494:                                                may include subquestion. 
 5495: 
 5496:   Returns:
 5497:     $line - the modified scanline
 5498: 
 5499:   Side effects: 
 5500:     $scan_data - may be updated
 5501: 
 5502: =cut
 5503: 
 5504: 
 5505: sub scantron_fixup_scanline {
 5506:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 5507:     if ($field eq 'ID') {
 5508: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 5509: 	    return ($line,1,'New value too large');
 5510: 	}
 5511: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 5512: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 5513: 				     $args->{'newid'});
 5514: 	}
 5515: 	substr($line,$$scantron_config{'IDstart'}-1,
 5516: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 5517: 	if ($args->{'newid'}=~/^\s*$/) {
 5518: 	    &scan_data($scan_data,"$whichline.user",
 5519: 		       $args->{'username'}.':'.$args->{'domain'});
 5520: 	}
 5521:     } elsif ($field eq 'CODE') {
 5522: 	if ($args->{'CODE_ignore_dup'}) {
 5523: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 5524: 	}
 5525: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 5526: 	if ($args->{'CODE'} ne 'use_unfound') {
 5527: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 5528: 		return ($line,1,'New CODE value too large');
 5529: 	    }
 5530: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 5531: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 5532: 	    }
 5533: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 5534: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 5535: 	}
 5536:     } elsif ($field eq 'answer') {
 5537: 	my $length=$scantron_config->{'Qlength'};
 5538: 	my $off=$scantron_config->{'Qoff'};
 5539: 	my $on=$scantron_config->{'Qon'};
 5540: 	my $answer=${off}x$length;
 5541: 	if ($args->{'response'} eq 'none') {
 5542: 	    &scan_data($scan_data,
 5543: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 5544: 	} else {
 5545: 	    if ($on eq 'letter') {
 5546: 		my @alphabet=('A'..'Z');
 5547: 		$answer=$alphabet[$args->{'response'}];
 5548: 	    } elsif ($on eq 'number') {
 5549: 		$answer=$args->{'response'}+1;
 5550: 		if ($answer == 10) { $answer = '0'; }
 5551: 	    } else {
 5552: 		substr($answer,$args->{'response'},1)=$on;
 5553: 	    }
 5554: 	    &scan_data($scan_data,
 5555: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 5556: 	}
 5557: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 5558: 	substr($line,$where-1,$length)=$answer;
 5559:     }
 5560:     return $line;
 5561: }
 5562: 
 5563: =pod
 5564: 
 5565: =item scan_data
 5566: 
 5567:     Edit or look up  an item in the scan_data hash.
 5568: 
 5569:   Arguments:
 5570:     $scan_data  - The hash (see scantron_getfile)
 5571:     $key        - shorthand of the key to edit (actual key is
 5572:                   scantronfilename_key).
 5573:     $data        - New value of the hash entry.
 5574:     $delete      - If true, the entry is removed from the hash.
 5575: 
 5576:   Returns:
 5577:     The new value of the hash table field (undefined if deleted).
 5578: 
 5579: =cut
 5580: 
 5581: 
 5582: sub scan_data {
 5583:     my ($scan_data,$key,$value,$delete)=@_;
 5584:     my $filename=$env{'form.scantron_selectfile'};
 5585:     if (defined($value)) {
 5586: 	$scan_data->{$filename.'_'.$key} = $value;
 5587:     }
 5588:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 5589:     return $scan_data->{$filename.'_'.$key};
 5590: }
 5591: 
 5592: # ----- These first few routines are general use routines.----
 5593: 
 5594: # Return the number of occurences of a pattern in a string.
 5595: 
 5596: sub occurence_count {
 5597:     my ($string, $pattern) = @_;
 5598: 
 5599:     my @matches = ($string =~ /$pattern/g);
 5600: 
 5601:     return scalar(@matches);
 5602: }
 5603: 
 5604: 
 5605: # Take a string known to have digits and convert all the
 5606: # digits into letters in the range J,A..I.
 5607: 
 5608: sub digits_to_letters {
 5609:     my ($input) = @_;
 5610: 
 5611:     my @alphabet = ('J', 'A'..'I');
 5612: 
 5613:     my @input    = split(//, $input);
 5614:     my $output ='';
 5615:     for (my $i = 0; $i < scalar(@input); $i++) {
 5616: 	if ($input[$i] =~ /\d/) {
 5617: 	    $output .= $alphabet[$input[$i]];
 5618: 	} else {
 5619: 	    $output .= $input[$i];
 5620: 	}
 5621:     }
 5622:     return $output;
 5623: }
 5624: 
 5625: =pod 
 5626: 
 5627: =item scantron_parse_scanline
 5628: 
 5629:   Decodes a scanline from the selected scantron file
 5630: 
 5631:  Arguments:
 5632:     line             - The text of the scantron file line to process
 5633:     whichline        - Line number
 5634:     scantron_config  - Hash describing the format of the scantron lines.
 5635:     scan_data        - Hash of extra information about the scanline
 5636:                        (see scantron_getfile for more information)
 5637:     just_header      - True if should not process question answers but only
 5638:                        the stuff to the left of the answers.
 5639:  Returns:
 5640:    Hash containing the result of parsing the scanline
 5641: 
 5642:    Keys are all proceeded by the string 'scantron.'
 5643: 
 5644:        CODE    - the CODE in use for this scanline
 5645:        useCODE - 1 if the CODE is invalid but it usage has been forced
 5646:                  by the operator
 5647:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 5648:                             CODEs were selected, but the usage has been
 5649:                             forced by the operator
 5650:        ID  - student/employee ID
 5651:        PaperID - if used, the ID number printed on the sheet when the 
 5652:                  paper was scanned
 5653:        FirstName - first name from the sheet
 5654:        LastName  - last name from the sheet
 5655: 
 5656:      if just_header was not true these key may also exist
 5657: 
 5658:        missingerror - a list of bubble ranges that are considered to be answers
 5659:                       to a single question that don't have any bubbles filled in.
 5660:                       Of the form questionnumber:firstbubblenumber:count.
 5661:        doubleerror  - a list of bubble ranges that are considered to be answers
 5662:                       to a single question that have more than one bubble filled in.
 5663:                       Of the form questionnumber::firstbubblenumber:count
 5664:    
 5665:                 In the above, count is the number of bubble responses in the
 5666:                 input line needed to represent the possible answers to the question.
 5667:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 5668:                 per line would have count = 2.
 5669: 
 5670:        maxquest     - the number of the last bubble line that was parsed
 5671: 
 5672:        (<number> starts at 1)
 5673:        <number>.answer - zero or more letters representing the selected
 5674:                          letters from the scanline for the bubble line 
 5675:                          <number>.
 5676:                          if blank there was either no bubble or there where
 5677:                          multiple bubbles, (consult the keys missingerror and
 5678:                          doubleerror if this is an error condition)
 5679: 
 5680: =cut
 5681: 
 5682: sub scantron_parse_scanline {
 5683:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
 5684: 
 5685:     my %record;
 5686:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 5687:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 5688:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
 5689:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 5690: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 5691: 	if ($$scantron_config{'CODElocation'} < 0 ||
 5692: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 5693: 	    $$scantron_config{'CODElocation'} eq 'number') {
 5694: 	    $record{'scantron.CODE'}=substr($data,
 5695: 					    $$scantron_config{'CODEstart'}-1,
 5696: 					    $$scantron_config{'CODElength'});
 5697: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 5698: 		$record{'scantron.useCODE'}=1;
 5699: 	    }
 5700: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 5701: 		$record{'scantron.CODE_ignore_dup'}=1;
 5702: 	    }
 5703: 	} else {
 5704: 	    #FIXME interpret first N questions
 5705: 	}
 5706:     }
 5707:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 5708: 				  $$scantron_config{'IDlength'});
 5709:     $record{'scantron.PaperID'}=
 5710: 	substr($data,$$scantron_config{'PaperID'}-1,
 5711: 	       $$scantron_config{'PaperIDlength'});
 5712:     $record{'scantron.FirstName'}=
 5713: 	substr($data,$$scantron_config{'FirstName'}-1,
 5714: 	       $$scantron_config{'FirstNamelength'});
 5715:     $record{'scantron.LastName'}=
 5716: 	substr($data,$$scantron_config{'LastName'}-1,
 5717: 	       $$scantron_config{'LastNamelength'});
 5718:     if ($just_header) { return \%record; }
 5719: 
 5720:     my @alphabet=('A'..'Z');
 5721:     my $questnum=0;
 5722:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 5723: 
 5724:     chomp($questions);		# Get rid of any trailing \n.
 5725:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 5726:     while (length($questions)) {
 5727: 	my $answers_needed = $bubble_lines_per_response{$questnum};
 5728:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 5729:                              || 1;
 5730:         $questnum++;
 5731:         my $quest_id = $questnum;
 5732:         my $currentquest = substr($questions,0,$answer_length);
 5733:         $questions       = substr($questions,$answer_length);
 5734:         if (length($currentquest) < $answer_length) { next; }
 5735: 
 5736:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
 5737:             my $subquestnum = 1;
 5738:             my $subquestions = $currentquest;
 5739:             my @subanswers_needed = 
 5740:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
 5741:             foreach my $subans (@subanswers_needed) {
 5742:                 my $subans_length =
 5743:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 5744:                 my $currsubquest = substr($subquestions,0,$subans_length);
 5745:                 $subquestions   = substr($subquestions,$subans_length);
 5746:                 $quest_id = "$questnum.$subquestnum";
 5747:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 5748:                     ($$scantron_config{'Qon'} eq 'number')) {
 5749:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 5750:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 5751:                         \@alphabet,\%record,$scantron_config,$scan_data);
 5752:                 } else {
 5753:                     $ansnum = &scantron_validator_positional($ansnum,
 5754:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
 5755:                 }
 5756:                 $subquestnum ++;
 5757:             }
 5758:         } else {
 5759:             if (($$scantron_config{'Qon'} eq 'letter') ||
 5760:                 ($$scantron_config{'Qon'} eq 'number')) {
 5761:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 5762:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5763:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5764:             } else {
 5765:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 5766:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5767:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5768:             }
 5769:         }
 5770:     }
 5771:     $record{'scantron.maxquest'}=$questnum;
 5772:     return \%record;
 5773: }
 5774: 
 5775: sub scantron_validator_lettnum {
 5776:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 5777:         $alphabet,$record,$scantron_config,$scan_data) = @_;
 5778: 
 5779:     # Qon 'letter' implies for each slot in currquest we have:
 5780:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 5781:     #    about anything else (esp. a value of Qoff) for missing
 5782:     #    bubbles.
 5783:     #
 5784:     # Qon 'number' implies each slot gives a digit that indexes the
 5785:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 5786:     #    and * or ? for double bubbles on a single line.
 5787:     #
 5788: 
 5789:     my $matchon;
 5790:     if ($$scantron_config{'Qon'} eq 'letter') {
 5791:         $matchon = '[A-Z]';
 5792:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 5793:         $matchon = '\d';
 5794:     }
 5795:     my $occurrences = 0;
 5796:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5797:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5798:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5799:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5800:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5801:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5802:         my @singlelines = split('',$currquest);
 5803:         foreach my $entry (@singlelines) {
 5804:             $occurrences = &occurence_count($entry,$matchon);
 5805:             if ($occurrences > 1) {
 5806:                 last;
 5807:             }
 5808:         } 
 5809:     } else {
 5810:         $occurrences = &occurence_count($currquest,$matchon); 
 5811:     }
 5812:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 5813:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5814:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5815:             my $bubble = substr($currquest,$ans,1);
 5816:             if ($bubble =~ /$matchon/ ) {
 5817:                 if ($$scantron_config{'Qon'} eq 'number') {
 5818:                     if ($bubble == 0) {
 5819:                         $bubble = 10; 
 5820:                     }
 5821:                     $record->{"scantron.$ansnum.answer"} = 
 5822:                         $alphabet->[$bubble-1];
 5823:                 } else {
 5824:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 5825:                 }
 5826:             } else {
 5827:                 $record->{"scantron.$ansnum.answer"}='';
 5828:             }
 5829:             $ansnum++;
 5830:         }
 5831:     } elsif (!defined($currquest)
 5832:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 5833:             || (&occurence_count($currquest,$matchon) == 0)) {
 5834:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5835:             $record->{"scantron.$ansnum.answer"}='';
 5836:             $ansnum++;
 5837:         }
 5838:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5839:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 5840:         }
 5841:     } else {
 5842:         if ($$scantron_config{'Qon'} eq 'number') {
 5843:             $currquest = &digits_to_letters($currquest);            
 5844:         }
 5845:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5846:             my $bubble = substr($currquest,$ans,1);
 5847:             $record->{"scantron.$ansnum.answer"} = $bubble;
 5848:             $ansnum++;
 5849:         }
 5850:     }
 5851:     return $ansnum;
 5852: }
 5853: 
 5854: sub scantron_validator_positional {
 5855:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 5856:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
 5857: 
 5858:     # Otherwise there's a positional notation;
 5859:     # each bubble line requires Qlength items, and there are filled in
 5860:     # bubbles for each case where there 'Qon' characters.
 5861:     #
 5862: 
 5863:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 5864: 
 5865:     # If the split only gives us one element.. the full length of the
 5866:     # answer string, no bubbles are filled in:
 5867: 
 5868:     if ($answers_needed eq '') {
 5869:         return;
 5870:     }
 5871: 
 5872:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 5873:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5874:             $record->{"scantron.$ansnum.answer"}='';
 5875:             $ansnum++;
 5876:         }
 5877:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5878:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 5879:         }
 5880:     } elsif (scalar(@array) == 2) {
 5881:         my $location = length($array[0]);
 5882:         my $line_num = int($location / $$scantron_config{'Qlength'});
 5883:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 5884:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5885:             if ($ans eq $line_num) {
 5886:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 5887:             } else {
 5888:                 $record->{"scantron.$ansnum.answer"} = ' ';
 5889:             }
 5890:             $ansnum++;
 5891:          }
 5892:     } else {
 5893:         #  If there's more than one instance of a bubble character
 5894:         #  That's a double bubble; with positional notation we can
 5895:         #  record all the bubbles filled in as well as the
 5896:         #  fact this response consists of multiple bubbles.
 5897:         #
 5898:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5899:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5900:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5901:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5902:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5903:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5904:             my $doubleerror = 0;
 5905:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 5906:                    (!$doubleerror)) {
 5907:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 5908:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 5909:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 5910:                if (length(@currarray) > 2) {
 5911:                    $doubleerror = 1;
 5912:                } 
 5913:             }
 5914:             if ($doubleerror) {
 5915:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5916:             }
 5917:         } else {
 5918:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5919:         }
 5920:         my $item = $ansnum;
 5921:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5922:             $record->{"scantron.$item.answer"} = '';
 5923:             $item ++;
 5924:         }
 5925: 
 5926:         my @ans=@array;
 5927:         my $i=0;
 5928:         my $increment = 0;
 5929:         while ($#ans) {
 5930:             $i+=length($ans[0]) + $increment;
 5931:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 5932:             my $bubble = $i%$$scantron_config{'Qlength'};
 5933:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 5934:             shift(@ans);
 5935:             $increment = 1;
 5936:         }
 5937:         $ansnum += $answers_needed;
 5938:     }
 5939:     return $ansnum;
 5940: }
 5941: 
 5942: =pod
 5943: 
 5944: =item scantron_add_delay
 5945: 
 5946:    Adds an error message that occurred during the grading phase to a
 5947:    queue of messages to be shown after grading pass is complete
 5948: 
 5949:  Arguments:
 5950:    $delayqueue  - arrary ref of hash ref of error messages
 5951:    $scanline    - the scanline that caused the error
 5952:    $errormesage - the error message
 5953:    $errorcode   - a numeric code for the error
 5954: 
 5955:  Side Effects:
 5956:    updates the $delayqueue to have a new hash ref of the error
 5957: 
 5958: =cut
 5959: 
 5960: sub scantron_add_delay {
 5961:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 5962:     push(@$delayqueue,
 5963: 	 {'line' => $scanline, 'emsg' => $errormessage,
 5964: 	  'ecode' => $errorcode }
 5965: 	 );
 5966: }
 5967: 
 5968: =pod
 5969: 
 5970: =item scantron_find_student
 5971: 
 5972:    Finds the username for the current scanline
 5973: 
 5974:   Arguments:
 5975:    $scantron_record - hash result from scantron_parse_scanline
 5976:    $scan_data       - hash of correction information 
 5977:                       (see &scantron_getfile() form more information)
 5978:    $idmap           - hash from &username_to_idmap()
 5979:    $line            - number of current scanline
 5980:  
 5981:   Returns:
 5982:    Either 'username:domain' or undef if unknown
 5983: 
 5984: =cut
 5985: 
 5986: sub scantron_find_student {
 5987:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 5988:     my $scanID=$$scantron_record{'scantron.ID'};
 5989:     if ($scanID =~ /^\s*$/) {
 5990:  	return &scan_data($scan_data,"$line.user");
 5991:     }
 5992:     foreach my $id (keys(%$idmap)) {
 5993:  	if (lc($id) eq lc($scanID)) {
 5994:  	    return $$idmap{$id};
 5995:  	}
 5996:     }
 5997:     return undef;
 5998: }
 5999: 
 6000: =pod
 6001: 
 6002: =item scantron_filter
 6003: 
 6004:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 6005:    hidden resources was selected
 6006: 
 6007: =cut
 6008: 
 6009: sub scantron_filter {
 6010:     my ($curres)=@_;
 6011: 
 6012:     if (ref($curres) && $curres->is_problem()) {
 6013: 	# if the user has asked to not have either hidden
 6014: 	# or 'randomout' controlled resources to be graded
 6015: 	# don't include them
 6016: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6017: 	    && $curres->randomout) {
 6018: 	    return 0;
 6019: 	}
 6020: 	return 1;
 6021:     }
 6022:     return 0;
 6023: }
 6024: 
 6025: =pod
 6026: 
 6027: =item scantron_process_corrections
 6028: 
 6029:    Gets correction information out of submitted form data and corrects
 6030:    the scanline
 6031: 
 6032: =cut
 6033: 
 6034: sub scantron_process_corrections {
 6035:     my ($r) = @_;
 6036:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6037:     my ($scanlines,$scan_data)=&scantron_getfile();
 6038:     my $classlist=&Apache::loncoursedata::get_classlist();
 6039:     my $which=$env{'form.scantron_line'};
 6040:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 6041:     my ($skip,$err,$errmsg);
 6042:     if ($env{'form.scantron_skip_record'}) {
 6043: 	$skip=1;
 6044:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 6045: 	my $newstudent=$env{'form.scantron_username'}.':'.
 6046: 	    $env{'form.scantron_domain'};
 6047: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 6048: 	($line,$err,$errmsg)=
 6049: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6050: 				     'ID',{'newid'=>$newid,
 6051: 				    'username'=>$env{'form.scantron_username'},
 6052: 				    'domain'=>$env{'form.scantron_domain'}});
 6053:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 6054: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 6055: 	my $newCODE;
 6056: 	my %args;
 6057: 	if      ($resolution eq 'use_unfound') {
 6058: 	    $newCODE='use_unfound';
 6059: 	} elsif ($resolution eq 'use_found') {
 6060: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 6061: 	} elsif ($resolution eq 'use_typed') {
 6062: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 6063: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 6064: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 6065: 	}
 6066: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 6067: 	    $args{'CODE_ignore_dup'}=1;
 6068: 	}
 6069: 	$args{'CODE'}=$newCODE;
 6070: 	($line,$err,$errmsg)=
 6071: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6072: 				     'CODE',\%args);
 6073:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 6074: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 6075: 	    ($line,$err,$errmsg)=
 6076: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 6077: 					 $which,'answer',
 6078: 					 { 'question'=>$question,
 6079: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 6080:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 6081: 	    if ($err) { last; }
 6082: 	}
 6083:     }
 6084:     if ($err) {
 6085: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
 6086:     } else {
 6087: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 6088: 	&scantron_putfile($scanlines,$scan_data);
 6089:     }
 6090: }
 6091: 
 6092: =pod
 6093: 
 6094: =item reset_skipping_status
 6095: 
 6096:    Forgets the current set of remember skipped scanlines (and thus
 6097:    reverts back to considering all lines in the
 6098:    scantron_skipped_<filename> file)
 6099: 
 6100: =cut
 6101: 
 6102: sub reset_skipping_status {
 6103:     my ($scanlines,$scan_data)=&scantron_getfile();
 6104:     &scan_data($scan_data,'remember_skipping',undef,1);
 6105:     &scantron_putfile(undef,$scan_data);
 6106: }
 6107: 
 6108: =pod
 6109: 
 6110: =item start_skipping
 6111: 
 6112:    Marks a scanline to be skipped. 
 6113: 
 6114: =cut
 6115: 
 6116: sub start_skipping {
 6117:     my ($scan_data,$i)=@_;
 6118:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6119:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 6120: 	$remembered{$i}=2;
 6121:     } else {
 6122: 	$remembered{$i}=1;
 6123:     }
 6124:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 6125: }
 6126: 
 6127: =pod
 6128: 
 6129: =item should_be_skipped
 6130: 
 6131:    Checks whether a scanline should be skipped.
 6132: 
 6133: =cut
 6134: 
 6135: sub should_be_skipped {
 6136:     my ($scanlines,$scan_data,$i)=@_;
 6137:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 6138: 	# not redoing old skips
 6139: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 6140: 	return 0;
 6141:     }
 6142:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6143: 
 6144:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 6145: 	return 0;
 6146:     }
 6147:     return 1;
 6148: }
 6149: 
 6150: =pod
 6151: 
 6152: =item remember_current_skipped
 6153: 
 6154:    Discovers what scanlines are in the scantron_skipped_<filename>
 6155:    file and remembers them into scan_data for later use.
 6156: 
 6157: =cut
 6158: 
 6159: sub remember_current_skipped {
 6160:     my ($scanlines,$scan_data)=&scantron_getfile();
 6161:     my %to_remember;
 6162:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6163: 	if ($scanlines->{'skipped'}[$i]) {
 6164: 	    $to_remember{$i}=1;
 6165: 	}
 6166:     }
 6167: 
 6168:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 6169:     &scantron_putfile(undef,$scan_data);
 6170: }
 6171: 
 6172: =pod
 6173: 
 6174: =item check_for_error
 6175: 
 6176:     Checks if there was an error when attempting to remove a specific
 6177:     scantron_.. bubble sheet data file. Prints out an error if
 6178:     something went wrong.
 6179: 
 6180: =cut
 6181: 
 6182: sub check_for_error {
 6183:     my ($r,$result)=@_;
 6184:     if ($result ne 'ok' && $result ne 'not_found' ) {
 6185: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 6186:     }
 6187: }
 6188: 
 6189: =pod
 6190: 
 6191: =item scantron_warning_screen
 6192: 
 6193:    Interstitial screen to make sure the operator has selected the
 6194:    correct options before we start the validation phase.
 6195: 
 6196: =cut
 6197: 
 6198: sub scantron_warning_screen {
 6199:     my ($button_text,$symb)=@_;
 6200:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 6201:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6202:     my $CODElist;
 6203:     if ($scantron_config{'CODElocation'} &&
 6204: 	$scantron_config{'CODEstart'} &&
 6205: 	$scantron_config{'CODElength'}) {
 6206: 	$CODElist=$env{'form.scantron_CODElist'};
 6207: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
 6208: 	$CODElist=
 6209: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 6210: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 6211:     }
 6212:     return ('
 6213: <p>
 6214: <span class="LC_warning">
 6215: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
 6216: </p>
 6217: <table>
 6218: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 6219: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 6220: '.$CODElist.'
 6221: </table>
 6222: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'<br />
 6223: '.&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>
 6224: 
 6225: <br />
 6226: ');
 6227: }
 6228: 
 6229: =pod
 6230: 
 6231: =item scantron_do_warning
 6232: 
 6233:    Check if the operator has picked something for all required
 6234:    fields. Error out if something is missing.
 6235: 
 6236: =cut
 6237: 
 6238: sub scantron_do_warning {
 6239:     my ($r,$symb)=@_;
 6240:     if (!$symb) {return '';}
 6241:     my $default_form_data=&defaultFormData($symb);
 6242:     $r->print(&scantron_form_start().$default_form_data);
 6243:     if ( $env{'form.selectpage'} eq '' ||
 6244: 	 $env{'form.scantron_selectfile'} eq '' ||
 6245: 	 $env{'form.scantron_format'} eq '' ) {
 6246: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
 6247: 	if ( $env{'form.selectpage'} eq '') {
 6248: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 6249: 	} 
 6250: 	if ( $env{'form.scantron_selectfile'} eq '') {
 6251: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected a file that contains the student's response data.").'</span></p>');
 6252: 	} 
 6253: 	if ( $env{'form.scantron_format'} eq '') {
 6254: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected the format of the student's response data.").'</span></p>');
 6255: 	} 
 6256:     } else {
 6257: 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
 6258: 	$r->print('
 6259: '.$warning.'
 6260: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 6261: <input type="hidden" name="command" value="scantron_validate" />
 6262: ');
 6263:     }
 6264:     $r->print("</form><br />");
 6265:     return '';
 6266: }
 6267: 
 6268: =pod
 6269: 
 6270: =item scantron_form_start
 6271: 
 6272:     html hidden input for remembering all selected grading options
 6273: 
 6274: =cut
 6275: 
 6276: sub scantron_form_start {
 6277:     my ($max_bubble)=@_;
 6278:     my $result= <<SCANTRONFORM;
 6279: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 6280:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 6281:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 6282:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 6283:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 6284:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 6285:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 6286:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 6287:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 6288:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 6289: SCANTRONFORM
 6290: 
 6291:   my $line = 0;
 6292:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 6293:        my $chunk =
 6294: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 6295:        $chunk .=
 6296: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 6297:        $chunk .= 
 6298:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 6299:        $chunk .=
 6300:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 6301:        $result .= $chunk;
 6302:        $line++;
 6303:    }
 6304:     return $result;
 6305: }
 6306: 
 6307: =pod
 6308: 
 6309: =item scantron_validate_file
 6310: 
 6311:     Dispatch routine for doing validation of a bubble sheet data file.
 6312: 
 6313:     Also processes any necessary information resets that need to
 6314:     occur before validation begins (ignore previous corrections,
 6315:     restarting the skipped records processing)
 6316: 
 6317: =cut
 6318: 
 6319: sub scantron_validate_file {
 6320:     my ($r,$symb) = @_;
 6321:     if (!$symb) {return '';}
 6322:     my $default_form_data=&defaultFormData($symb);
 6323:     
 6324:     # do the detection of only doing skipped records first befroe we delete
 6325:     # them when doing the corrections reset
 6326:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 6327: 	&reset_skipping_status();
 6328:     }
 6329:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 6330: 	&remember_current_skipped();
 6331: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 6332:     }
 6333: 
 6334:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 6335: 	&check_for_error($r,&scantron_remove_file('corrected'));
 6336: 	&check_for_error($r,&scantron_remove_file('skipped'));
 6337: 	&check_for_error($r,&scantron_remove_scan_data());
 6338: 	$env{'form.scantron_options_ignore'}='done';
 6339:     }
 6340: 
 6341:     if ($env{'form.scantron_corrections'}) {
 6342: 	&scantron_process_corrections($r);
 6343:     }
 6344:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 6345:     #get the student pick code ready
 6346:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 6347:     my $nav_error;
 6348:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6349:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 6350:     if ($nav_error) {
 6351:         $r->print(&navmap_errormsg());
 6352:         return '';
 6353:     }
 6354:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 6355:     $r->print($result);
 6356:     
 6357:     my @validate_phases=( 'sequence',
 6358: 			  'ID',
 6359: 			  'CODE',
 6360: 			  'doublebubble',
 6361: 			  'missingbubbles');
 6362:     if (!$env{'form.validatepass'}) {
 6363: 	$env{'form.validatepass'} = 0;
 6364:     }
 6365:     my $currentphase=$env{'form.validatepass'};
 6366: 
 6367: 
 6368:     my $stop=0;
 6369:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 6370: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 6371: 	$r->rflush();
 6372: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 6373: 	{
 6374: 	    no strict 'refs';
 6375: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 6376: 	}
 6377:     }
 6378:     if (!$stop) {
 6379: 	my $warning=&scantron_warning_screen('Start Grading',$symb);
 6380: 	$r->print(&mt('Validation process complete.').'<br />'.
 6381:                   $warning.
 6382:                   &mt('Perform verification for each student after storage of submissions?').
 6383:                   '&nbsp;<span class="LC_nobreak"><label>'.
 6384:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 6385:                   ('&nbsp;'x3).'<label>'.
 6386:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 6387:                   '</label></span><br />'.
 6388:                   &mt('Grading will take longer if you use verification.').'<br />'.
 6389:                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
 6390:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 6391:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 6392:     } else {
 6393: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 6394: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 6395:     }
 6396:     if ($stop) {
 6397: 	if ($validate_phases[$currentphase] eq 'sequence') {
 6398: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 6399: 	    $r->print(' '.&mt('this error').' <br />');
 6400: 
 6401: 	    $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>');
 6402: 	} else {
 6403:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 6404: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 6405:             } else {
 6406:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 6407:             }
 6408: 	    $r->print(' '.&mt('using corrected info').' <br />');
 6409: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 6410: 	    $r->print(" ".&mt("this scanline saving it for later."));
 6411: 	}
 6412:     }
 6413:     $r->print(" </form><br />");
 6414:     return '';
 6415: }
 6416: 
 6417: 
 6418: =pod
 6419: 
 6420: =item scantron_remove_file
 6421: 
 6422:    Removes the requested bubble sheet data file, makes sure that
 6423:    scantron_original_<filename> is never removed
 6424: 
 6425: 
 6426: =cut
 6427: 
 6428: sub scantron_remove_file {
 6429:     my ($which)=@_;
 6430:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6431:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6432:     my $file='scantron_';
 6433:     if ($which eq 'corrected' || $which eq 'skipped') {
 6434: 	$file.=$which.'_';
 6435:     } else {
 6436: 	return 'refused';
 6437:     }
 6438:     $file.=$env{'form.scantron_selectfile'};
 6439:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 6440: }
 6441: 
 6442: 
 6443: =pod
 6444: 
 6445: =item scantron_remove_scan_data
 6446: 
 6447:    Removes all scan_data correction for the requested bubble sheet
 6448:    data file.  (In the case that both the are doing skipped records we need
 6449:    to remember the old skipped lines for the time being so that element
 6450:    persists for a while.)
 6451: 
 6452: =cut
 6453: 
 6454: sub scantron_remove_scan_data {
 6455:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6456:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6457:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 6458:     my @todelete;
 6459:     my $filename=$env{'form.scantron_selectfile'};
 6460:     foreach my $key (@keys) {
 6461: 	if ($key=~/^\Q$filename\E_/) {
 6462: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 6463: 		$key=~/remember_skipping/) {
 6464: 		next;
 6465: 	    }
 6466: 	    push(@todelete,$key);
 6467: 	}
 6468:     }
 6469:     my $result;
 6470:     if (@todelete) {
 6471: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 6472: 				       \@todelete,$cdom,$cname);
 6473:     } else {
 6474: 	$result = 'ok';
 6475:     }
 6476:     return $result;
 6477: }
 6478: 
 6479: 
 6480: =pod
 6481: 
 6482: =item scantron_getfile
 6483: 
 6484:     Fetches the requested bubble sheet data file (all 3 versions), and
 6485:     the scan_data hash
 6486:   
 6487:   Arguments:
 6488:     None
 6489: 
 6490:   Returns:
 6491:     2 hash references
 6492: 
 6493:      - first one has 
 6494:          orig      -
 6495:          corrected -
 6496:          skipped   -  each of which points to an array ref of the specified
 6497:                       file broken up into individual lines
 6498:          count     - number of scanlines
 6499:  
 6500:      - second is the scan_data hash possible keys are
 6501:        ($number refers to scanline numbered $number and thus the key affects
 6502:         only that scanline
 6503:         $bubline refers to the specific bubble line element and the aspects
 6504:         refers to that specific bubble line element)
 6505: 
 6506:        $number.user - username:domain to use
 6507:        $number.CODE_ignore_dup 
 6508:                     - ignore the duplicate CODE error 
 6509:        $number.useCODE
 6510:                     - use the CODE in the scanline as is
 6511:        $number.no_bubble.$bubline
 6512:                     - it is valid that there is no bubbled in bubble
 6513:                       at $number $bubline
 6514:        remember_skipping
 6515:                     - a frozen hash containing keys of $number and values
 6516:                       of either 
 6517:                         1 - we are on a 'do skipped records pass' and plan
 6518:                             on processing this line
 6519:                         2 - we are on a 'do skipped records pass' and this
 6520:                             scanline has been marked to skip yet again
 6521: 
 6522: =cut
 6523: 
 6524: sub scantron_getfile {
 6525:     #FIXME really would prefer a scantron directory
 6526:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6527:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6528:     my $lines;
 6529:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6530: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 6531:     my %scanlines;
 6532:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 6533:     my $temp=$scanlines{'orig'};
 6534:     $scanlines{'count'}=$#$temp;
 6535: 
 6536:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6537: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 6538:     if ($lines eq '-1') {
 6539: 	$scanlines{'corrected'}=[];
 6540:     } else {
 6541: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 6542:     }
 6543:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6544: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 6545:     if ($lines eq '-1') {
 6546: 	$scanlines{'skipped'}=[];
 6547:     } else {
 6548: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 6549:     }
 6550:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 6551:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 6552:     my %scan_data = @tmp;
 6553:     return (\%scanlines,\%scan_data);
 6554: }
 6555: 
 6556: =pod
 6557: 
 6558: =item lonnet_putfile
 6559: 
 6560:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 6561: 
 6562:  Arguments:
 6563:    $contents - data to store
 6564:    $filename - filename to store $contents into
 6565: 
 6566:  Returns:
 6567:    result value from &Apache::lonnet::finishuserfileupload
 6568: 
 6569: =cut
 6570: 
 6571: sub lonnet_putfile {
 6572:     my ($contents,$filename)=@_;
 6573:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6574:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6575:     $env{'form.sillywaytopassafilearound'}=$contents;
 6576:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 6577: 
 6578: }
 6579: 
 6580: =pod
 6581: 
 6582: =item scantron_putfile
 6583: 
 6584:     Stores the current version of the bubble sheet data files, and the
 6585:     scan_data hash. (Does not modify the original version only the
 6586:     corrected and skipped versions.
 6587: 
 6588:  Arguments:
 6589:     $scanlines - hash ref that looks like the first return value from
 6590:                  &scantron_getfile()
 6591:     $scan_data - hash ref that looks like the second return value from
 6592:                  &scantron_getfile()
 6593: 
 6594: =cut
 6595: 
 6596: sub scantron_putfile {
 6597:     my ($scanlines,$scan_data) = @_;
 6598:     #FIXME really would prefer a scantron directory
 6599:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6600:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6601:     if ($scanlines) {
 6602: 	my $prefix='scantron_';
 6603: # no need to update orig, shouldn't change
 6604: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 6605: #		    $env{'form.scantron_selectfile'});
 6606: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 6607: 			$prefix.'corrected_'.
 6608: 			$env{'form.scantron_selectfile'});
 6609: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 6610: 			$prefix.'skipped_'.
 6611: 			$env{'form.scantron_selectfile'});
 6612:     }
 6613:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 6614: }
 6615: 
 6616: =pod
 6617: 
 6618: =item scantron_get_line
 6619: 
 6620:    Returns the correct version of the scanline
 6621: 
 6622:  Arguments:
 6623:     $scanlines - hash ref that looks like the first return value from
 6624:                  &scantron_getfile()
 6625:     $scan_data - hash ref that looks like the second return value from
 6626:                  &scantron_getfile()
 6627:     $i         - number of the requested line (starts at 0)
 6628: 
 6629:  Returns:
 6630:    A scanline, (either the original or the corrected one if it
 6631:    exists), or undef if the requested scanline should be
 6632:    skipped. (Either because it's an skipped scanline, or it's an
 6633:    unskipped scanline and we are not doing a 'do skipped scanlines'
 6634:    pass.
 6635: 
 6636: =cut
 6637: 
 6638: sub scantron_get_line {
 6639:     my ($scanlines,$scan_data,$i)=@_;
 6640:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 6641:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 6642:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 6643:     return $scanlines->{'orig'}[$i]; 
 6644: }
 6645: 
 6646: =pod
 6647: 
 6648: =item scantron_todo_count
 6649: 
 6650:     Counts the number of scanlines that need processing.
 6651: 
 6652:  Arguments:
 6653:     $scanlines - hash ref that looks like the first return value from
 6654:                  &scantron_getfile()
 6655:     $scan_data - hash ref that looks like the second return value from
 6656:                  &scantron_getfile()
 6657: 
 6658:  Returns:
 6659:     $count - number of scanlines to process
 6660: 
 6661: =cut
 6662: 
 6663: sub get_todo_count {
 6664:     my ($scanlines,$scan_data)=@_;
 6665:     my $count=0;
 6666:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6667: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6668: 	if ($line=~/^[\s\cz]*$/) { next; }
 6669: 	$count++;
 6670:     }
 6671:     return $count;
 6672: }
 6673: 
 6674: =pod
 6675: 
 6676: =item scantron_put_line
 6677: 
 6678:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
 6679:     data file.
 6680: 
 6681:  Arguments:
 6682:     $scanlines - hash ref that looks like the first return value from
 6683:                  &scantron_getfile()
 6684:     $scan_data - hash ref that looks like the second return value from
 6685:                  &scantron_getfile()
 6686:     $i         - line number to update
 6687:     $newline   - contents of the updated scanline
 6688:     $skip      - if true make the line for skipping and update the
 6689:                  'skipped' file
 6690: 
 6691: =cut
 6692: 
 6693: sub scantron_put_line {
 6694:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 6695:     if ($skip) {
 6696: 	$scanlines->{'skipped'}[$i]=$newline;
 6697: 	&start_skipping($scan_data,$i);
 6698: 	return;
 6699:     }
 6700:     $scanlines->{'corrected'}[$i]=$newline;
 6701: }
 6702: 
 6703: =pod
 6704: 
 6705: =item scantron_clear_skip
 6706: 
 6707:    Remove a line from the 'skipped' file
 6708: 
 6709:  Arguments:
 6710:     $scanlines - hash ref that looks like the first return value from
 6711:                  &scantron_getfile()
 6712:     $scan_data - hash ref that looks like the second return value from
 6713:                  &scantron_getfile()
 6714:     $i         - line number to update
 6715: 
 6716: =cut
 6717: 
 6718: sub scantron_clear_skip {
 6719:     my ($scanlines,$scan_data,$i)=@_;
 6720:     if (exists($scanlines->{'skipped'}[$i])) {
 6721: 	undef($scanlines->{'skipped'}[$i]);
 6722: 	return 1;
 6723:     }
 6724:     return 0;
 6725: }
 6726: 
 6727: =pod
 6728: 
 6729: =item scantron_filter_not_exam
 6730: 
 6731:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 6732:    filter out resources that are not marked as 'exam' mode
 6733: 
 6734: =cut
 6735: 
 6736: sub scantron_filter_not_exam {
 6737:     my ($curres)=@_;
 6738:     
 6739:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 6740: 	# if the user has asked to not have either hidden
 6741: 	# or 'randomout' controlled resources to be graded
 6742: 	# don't include them
 6743: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6744: 	    && $curres->randomout) {
 6745: 	    return 0;
 6746: 	}
 6747: 	return 1;
 6748:     }
 6749:     return 0;
 6750: }
 6751: 
 6752: =pod
 6753: 
 6754: =item scantron_validate_sequence
 6755: 
 6756:     Validates the selected sequence, checking for resource that are
 6757:     not set to exam mode.
 6758: 
 6759: =cut
 6760: 
 6761: sub scantron_validate_sequence {
 6762:     my ($r,$currentphase) = @_;
 6763: 
 6764:     my $navmap=Apache::lonnavmaps::navmap->new();
 6765:     unless (ref($navmap)) {
 6766:         $r->print(&navmap_errormsg());
 6767:         return (1,$currentphase);
 6768:     }
 6769:     my (undef,undef,$sequence)=
 6770: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 6771: 
 6772:     my $map=$navmap->getResourceByUrl($sequence);
 6773: 
 6774:     $r->print('<input type="hidden" name="validate_sequence_exam"
 6775:                                     value="ignore" />');
 6776:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 6777: 	my @resources=
 6778: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 6779: 	if (@resources) {
 6780: 	    $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>");
 6781: 	    return (1,$currentphase);
 6782: 	}
 6783:     }
 6784: 
 6785:     return (0,$currentphase+1);
 6786: }
 6787: 
 6788: 
 6789: 
 6790: sub scantron_validate_ID {
 6791:     my ($r,$currentphase) = @_;
 6792:     
 6793:     #get student info
 6794:     my $classlist=&Apache::loncoursedata::get_classlist();
 6795:     my %idmap=&username_to_idmap($classlist);
 6796: 
 6797:     #get scantron line setup
 6798:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6799:     my ($scanlines,$scan_data)=&scantron_getfile();
 6800: 
 6801:     my $nav_error;
 6802:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
 6803:     if ($nav_error) {
 6804:         $r->print(&navmap_errormsg());
 6805:         return(1,$currentphase);
 6806:     }
 6807: 
 6808:     my %found=('ids'=>{},'usernames'=>{});
 6809:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6810: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6811: 	if ($line=~/^[\s\cz]*$/) { next; }
 6812: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 6813: 						 $scan_data);
 6814: 	my $id=$$scan_record{'scantron.ID'};
 6815: 	my $found;
 6816: 	foreach my $checkid (keys(%idmap)) {
 6817: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 6818: 	}
 6819: 	if ($found) {
 6820: 	    my $username=$idmap{$found};
 6821: 	    if ($found{'ids'}{$found}) {
 6822: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6823: 					 $line,'duplicateID',$found);
 6824: 		return(1,$currentphase);
 6825: 	    } elsif ($found{'usernames'}{$username}) {
 6826: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6827: 					 $line,'duplicateID',$username);
 6828: 		return(1,$currentphase);
 6829: 	    }
 6830: 	    #FIXME store away line we previously saw the ID on to use above
 6831: 	    $found{'ids'}{$found}++;
 6832: 	    $found{'usernames'}{$username}++;
 6833: 	} else {
 6834: 	    if ($id =~ /^\s*$/) {
 6835: 		my $username=&scan_data($scan_data,"$i.user");
 6836: 		if (defined($username) && $found{'usernames'}{$username}) {
 6837: 		    &scantron_get_correction($r,$i,$scan_record,
 6838: 					     \%scantron_config,
 6839: 					     $line,'duplicateID',$username);
 6840: 		    return(1,$currentphase);
 6841: 		} elsif (!defined($username)) {
 6842: 		    &scantron_get_correction($r,$i,$scan_record,
 6843: 					     \%scantron_config,
 6844: 					     $line,'incorrectID');
 6845: 		    return(1,$currentphase);
 6846: 		}
 6847: 		$found{'usernames'}{$username}++;
 6848: 	    } else {
 6849: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6850: 					 $line,'incorrectID');
 6851: 		return(1,$currentphase);
 6852: 	    }
 6853: 	}
 6854:     }
 6855: 
 6856:     return (0,$currentphase+1);
 6857: }
 6858: 
 6859: 
 6860: sub scantron_get_correction {
 6861:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
 6862: #FIXME in the case of a duplicated ID the previous line, probably need
 6863: #to show both the current line and the previous one and allow skipping
 6864: #the previous one or the current one
 6865: 
 6866:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 6867: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6868: 			    " for PaperID <tt>[_1]</tt>",
 6869: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
 6870:     } else {
 6871: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6872: 			    " in scanline [_1] <pre>[_2]</pre>",
 6873: 			    $i,$line)."</p> \n");
 6874:     }
 6875:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
 6876: 			  "The name on the paper is [_2],[_3]",
 6877: 			  $$scan_record{'scantron.ID'},
 6878: 			  $$scan_record{'scantron.LastName'},
 6879: 			  $$scan_record{'scantron.FirstName'})."</p>";
 6880: 
 6881:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 6882:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 6883:                            # Array populated for doublebubble or
 6884:     my @lines_to_correct;  # missingbubble errors to build javascript
 6885:                            # to validate radio button checking   
 6886: 
 6887:     if ($error =~ /ID$/) {
 6888: 	if ($error eq 'incorrectID') {
 6889: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
 6890: 		      "</p>\n");
 6891: 	} elsif ($error eq 'duplicateID') {
 6892: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 6893: 	}
 6894: 	$r->print($message);
 6895: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6896: 	$r->print("\n<ul><li> ");
 6897: 	#FIXME it would be nice if this sent back the user ID and
 6898: 	#could do partial userID matches
 6899: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 6900: 				       'scantron_username','scantron_domain'));
 6901: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 6902: 	$r->print("\n@".
 6903: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 6904: 
 6905: 	$r->print('</li>');
 6906:     } elsif ($error =~ /CODE$/) {
 6907: 	if ($error eq 'incorrectCODE') {
 6908: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 6909: 	} elsif ($error eq 'duplicateCODE') {
 6910: 	    $r->print("<p>".&mt("The encoded CODE has also been used by a previous paper [_1], and CODEs are supposed to be unique.",join(', ',@{$arg}))."</p>\n");
 6911: 	}
 6912: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
 6913: 			    $$scan_record{'scantron.CODE'})."<br />\n");
 6914: 	$r->print($message);
 6915: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6916: 	$r->print("\n<br /> ");
 6917: 	my $i=0;
 6918: 	if ($error eq 'incorrectCODE' 
 6919: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 6920: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 6921: 	    if ($closest > 0) {
 6922: 		foreach my $testcode (@{$closest}) {
 6923: 		    my $checked='';
 6924: 		    if (!$i) { $checked=' checked="checked"'; }
 6925: 		    $r->print("
 6926:    <label>
 6927:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
 6928:        ".&mt("Use the similar CODE [_1] instead.",
 6929: 	    "<b><tt>".$testcode."</tt></b>")."
 6930:     </label>
 6931:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 6932: 		    $r->print("\n<br />");
 6933: 		    $i++;
 6934: 		}
 6935: 	    }
 6936: 	}
 6937: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 6938: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
 6939: 	    $r->print("
 6940:     <label>
 6941:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
 6942:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
 6943: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 6944:     </label>");
 6945: 	    $r->print("\n<br />");
 6946: 	}
 6947: 
 6948: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
 6949: function change_radio(field) {
 6950:     var slct=document.scantronupload.scantron_CODE_resolution;
 6951:     var i;
 6952:     for (i=0;i<slct.length;i++) {
 6953:         if (slct[i].value==field) { slct[i].checked=true; }
 6954:     }
 6955: }
 6956: ENDSCRIPT
 6957: 	my $href="/adm/pickcode?".
 6958: 	   "form=".&escape("scantronupload").
 6959: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 6960: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 6961: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 6962: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 6963: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 6964: 	    $r->print("
 6965:     <label>
 6966:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 6967:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 6968: 	     "<a target='_blank' href='$href'>","</a>")."
 6969:     </label> 
 6970:     ".&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\')" />'));
 6971: 	    $r->print("\n<br />");
 6972: 	}
 6973: 	$r->print("
 6974:     <label>
 6975:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 6976:        ".&mt("Use [_1] as the CODE.",
 6977: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 6978: 	$r->print("\n<br /><br />");
 6979:     } elsif ($error eq 'doublebubble') {
 6980: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 6981: 
 6982: 	# The form field scantron_questions is acutally a list of line numbers.
 6983: 	# represented by this form so:
 6984: 
 6985: 	my $line_list = &questions_to_line_list($arg);
 6986: 
 6987: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 6988: 		  $line_list.'" />');
 6989: 	$r->print($message);
 6990: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 6991: 	foreach my $question (@{$arg}) {
 6992: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 6993:                                                    $scan_record, $error);
 6994:             push(@lines_to_correct,@linenums);
 6995: 	}
 6996:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 6997:     } elsif ($error eq 'missingbubble') {
 6998: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
 6999: 	$r->print($message);
 7000: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 7001: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 7002: 
 7003: 	# The form field scantron_questions is actually a list of line numbers not
 7004: 	# a list of question numbers. Therefore:
 7005: 	#
 7006: 	
 7007: 	my $line_list = &questions_to_line_list($arg);
 7008: 
 7009: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7010: 		  $line_list.'" />');
 7011: 	foreach my $question (@{$arg}) {
 7012: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7013:                                                    $scan_record, $error);
 7014:             push(@lines_to_correct,@linenums);
 7015: 	}
 7016:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7017:     } else {
 7018: 	$r->print("\n<ul>");
 7019:     }
 7020:     $r->print("\n</li></ul>");
 7021: }
 7022: 
 7023: sub verify_bubbles_checked {
 7024:     my (@ansnums) = @_;
 7025:     my $ansnumstr = join('","',@ansnums);
 7026:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 7027:     my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
 7028: function verify_bubble_radio(form) {
 7029:     var ansnumArray = new Array ("$ansnumstr");
 7030:     var need_bubble_count = 0;
 7031:     for (var i=0; i<ansnumArray.length; i++) {
 7032:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 7033:             var bubble_picked = 0; 
 7034:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 7035:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 7036:                     bubble_picked = 1;
 7037:                 }
 7038:             }
 7039:             if (bubble_picked == 0) {
 7040:                 need_bubble_count ++;
 7041:             }
 7042:         }
 7043:     }
 7044:     if (need_bubble_count) {
 7045:         alert("$warning");
 7046:         return;
 7047:     }
 7048:     form.submit(); 
 7049: }
 7050: ENDSCRIPT
 7051:     return $output;
 7052: }
 7053: 
 7054: =pod
 7055: 
 7056: =item  questions_to_line_list
 7057: 
 7058: Converts a list of questions into a string of comma separated
 7059: line numbers in the answer sheet used by the questions.  This is
 7060: used to fill in the scantron_questions form field.
 7061: 
 7062:   Arguments:
 7063:      questions    - Reference to an array of questions.
 7064: 
 7065: =cut
 7066: 
 7067: 
 7068: sub questions_to_line_list {
 7069:     my ($questions) = @_;
 7070:     my @lines;
 7071: 
 7072:     foreach my $item (@{$questions}) {
 7073:         my $question = $item;
 7074:         my ($first,$count,$last);
 7075:         if ($item =~ /^(\d+)\.(\d+)$/) {
 7076:             $question = $1;
 7077:             my $subquestion = $2;
 7078:             $first = $first_bubble_line{$question-1} + 1;
 7079:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7080:             my $subcount = 1;
 7081:             while ($subcount<$subquestion) {
 7082:                 $first += $subans[$subcount-1];
 7083:                 $subcount ++;
 7084:             }
 7085:             $count = $subans[$subquestion-1];
 7086:         } else {
 7087: 	    $first   = $first_bubble_line{$question-1} + 1;
 7088: 	    $count   = $bubble_lines_per_response{$question-1};
 7089:         }
 7090:         $last = $first+$count-1;
 7091:         push(@lines, ($first..$last));
 7092:     }
 7093:     return join(',', @lines);
 7094: }
 7095: 
 7096: =pod 
 7097: 
 7098: =item prompt_for_corrections
 7099: 
 7100: Prompts for a potentially multiline correction to the
 7101: user's bubbling (factors out common code from scantron_get_correction
 7102: for multi and missing bubble cases).
 7103: 
 7104:  Arguments:
 7105:    $r           - Apache request object.
 7106:    $question    - The question number to prompt for.
 7107:    $scan_config - The scantron file configuration hash.
 7108:    $scan_record - Reference to the hash that has the the parsed scanlines.
 7109:    $error       - Type of error
 7110: 
 7111:  Implicit inputs:
 7112:    %bubble_lines_per_response   - Starting line numbers for each question.
 7113:                                   Numbered from 0 (but question numbers are from
 7114:                                   1.
 7115:    %first_bubble_line           - Starting bubble line for each question.
 7116:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 7117:                                   type problems render as separate sub-questions, 
 7118:                                   in exam mode. This hash contains a 
 7119:                                   comma-separated list of the lines per 
 7120:                                   sub-question.
 7121:    %responsetype_per_response   - essayresponse, formularesponse,
 7122:                                   stringresponse, imageresponse, reactionresponse,
 7123:                                   and organicresponse type problem parts can have
 7124:                                   multiple lines per response if the weight
 7125:                                   assigned exceeds 10.  In this case, only
 7126:                                   one bubble per line is permitted, but more 
 7127:                                   than one line might contain bubbles, e.g.
 7128:                                   bubbling of: line 1 - J, line 2 - J, 
 7129:                                   line 3 - B would assign 22 points.  
 7130: 
 7131: =cut
 7132: 
 7133: sub prompt_for_corrections {
 7134:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
 7135:     my ($current_line,$lines);
 7136:     my @linenums;
 7137:     my $questionnum = $question;
 7138:     if ($question =~ /^(\d+)\.(\d+)$/) {
 7139:         $question = $1;
 7140:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7141:         my $subquestion = $2;
 7142:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7143:         my $subcount = 1;
 7144:         while ($subcount<$subquestion) {
 7145:             $current_line += $subans[$subcount-1];
 7146:             $subcount ++;
 7147:         }
 7148:         $lines = $subans[$subquestion-1];
 7149:     } else {
 7150:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7151:         $lines        = $bubble_lines_per_response{$question-1};
 7152:     }
 7153:     if ($lines > 1) {
 7154:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 7155:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
 7156:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
 7157:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
 7158:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
 7159:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
 7160:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
 7161:             $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 />');
 7162:         } else {
 7163:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 7164:         }
 7165:     }
 7166:     for (my $i =0; $i < $lines; $i++) {
 7167:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 7168: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
 7169: 	        		  $questionnum,$error,split('', $selected));
 7170:         push(@linenums,$current_line);
 7171: 	$current_line++;
 7172:     }
 7173:     if ($lines > 1) {
 7174: 	$r->print("<hr /><br />");
 7175:     }
 7176:     return @linenums;
 7177: }
 7178: 
 7179: =pod
 7180: 
 7181: =item scantron_bubble_selector
 7182:   
 7183:    Generates the html radiobuttons to correct a single bubble line
 7184:    possibly showing the existing the selected bubbles if known
 7185: 
 7186:  Arguments:
 7187:     $r           - Apache request object
 7188:     $scan_config - hash from &get_scantron_config()
 7189:     $line        - Number of the line being displayed.
 7190:     $questionnum - Question number (may include subquestion)
 7191:     $error       - Type of error.
 7192:     @selected    - Array of bubbles picked on this line.
 7193: 
 7194: =cut
 7195: 
 7196: sub scantron_bubble_selector {
 7197:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 7198:     my $max=$$scan_config{'Qlength'};
 7199: 
 7200:     my $scmode=$$scan_config{'Qon'};
 7201:     if ($scmode eq 'number' || $scmode eq 'letter') { 
 7202:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
 7203:             ($$scan_config{'BubblesPerRow'} > 0)) {
 7204:             $max=$$scan_config{'BubblesPerRow'};
 7205:             if (($scmode eq 'number') && ($max > 10)) {
 7206:                 $max = 10;
 7207:             } elsif (($scmode eq 'letter') && $max > 26) {
 7208:                 $max = 26;
 7209:             }
 7210:         } else {
 7211:             $max = 10;
 7212:         }
 7213:     }
 7214: 
 7215:     my @alphabet=('A'..'Z');
 7216:     $r->print(&Apache::loncommon::start_data_table().
 7217:               &Apache::loncommon::start_data_table_row());
 7218:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 7219:     for (my $i=0;$i<$max+1;$i++) {
 7220: 	$r->print("\n".'<td align="center">');
 7221: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 7222: 	else { $r->print('&nbsp;'); }
 7223: 	$r->print('</td>');
 7224:     }
 7225:     $r->print(&Apache::loncommon::end_data_table_row().
 7226:               &Apache::loncommon::start_data_table_row());
 7227:     for (my $i=0;$i<$max;$i++) {
 7228: 	$r->print("\n".
 7229: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 7230: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 7231:     }
 7232:     my $nobub_checked = ' ';
 7233:     if ($error eq 'missingbubble') {
 7234:         $nobub_checked = ' checked = "checked" ';
 7235:     }
 7236:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 7237: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 7238:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 7239:               $line.'" value="'.$questionnum.'" /></td>');
 7240:     $r->print(&Apache::loncommon::end_data_table_row().
 7241:               &Apache::loncommon::end_data_table());
 7242: }
 7243: 
 7244: =pod
 7245: 
 7246: =item num_matches
 7247: 
 7248:    Counts the number of characters that are the same between the two arguments.
 7249: 
 7250:  Arguments:
 7251:    $orig - CODE from the scanline
 7252:    $code - CODE to match against
 7253: 
 7254:  Returns:
 7255:    $count - integer count of the number of same characters between the
 7256:             two arguments
 7257: 
 7258: =cut
 7259: 
 7260: sub num_matches {
 7261:     my ($orig,$code) = @_;
 7262:     my @code=split(//,$code);
 7263:     my @orig=split(//,$orig);
 7264:     my $same=0;
 7265:     for (my $i=0;$i<scalar(@code);$i++) {
 7266: 	if ($code[$i] eq $orig[$i]) { $same++; }
 7267:     }
 7268:     return $same;
 7269: }
 7270: 
 7271: =pod
 7272: 
 7273: =item scantron_get_closely_matching_CODEs
 7274: 
 7275:    Cycles through all CODEs and finds the set that has the greatest
 7276:    number of same characters as the provided CODE
 7277: 
 7278:  Arguments:
 7279:    $allcodes - hash ref returned by &get_codes()
 7280:    $CODE     - CODE from the current scanline
 7281: 
 7282:  Returns:
 7283:    2 element list
 7284:     - first elements is number of how closely matching the best fit is 
 7285:       (5 means best set has 5 matching characters)
 7286:     - second element is an arrary ref containing the set of valid CODEs
 7287:       that best fit the passed in CODE
 7288: 
 7289: =cut
 7290: 
 7291: sub scantron_get_closely_matching_CODEs {
 7292:     my ($allcodes,$CODE)=@_;
 7293:     my @CODEs;
 7294:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 7295: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 7296:     }
 7297: 
 7298:     return ($#CODEs,$CODEs[-1]);
 7299: }
 7300: 
 7301: =pod
 7302: 
 7303: =item get_codes
 7304: 
 7305:    Builds a hash which has keys of all of the valid CODEs from the selected
 7306:    set of remembered CODEs.
 7307: 
 7308:  Arguments:
 7309:   $old_name - name of the set of remembered CODEs
 7310:   $cdom     - domain of the course
 7311:   $cnum     - internal course name
 7312: 
 7313:  Returns:
 7314:   %allcodes - keys are the valid CODEs, values are all 1
 7315: 
 7316: =cut
 7317: 
 7318: sub get_codes {
 7319:     my ($old_name, $cdom, $cnum) = @_;
 7320:     if (!$old_name) {
 7321: 	$old_name=$env{'form.scantron_CODElist'};
 7322:     }
 7323:     if (!$cdom) {
 7324: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 7325:     }
 7326:     if (!$cnum) {
 7327: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 7328:     }
 7329:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 7330: 				    $cdom,$cnum);
 7331:     my %allcodes;
 7332:     if ($result{"type\0$old_name"} eq 'number') {
 7333: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 7334:     } else {
 7335: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 7336:     }
 7337:     return %allcodes;
 7338: }
 7339: 
 7340: =pod
 7341: 
 7342: =item scantron_validate_CODE
 7343: 
 7344:    Validates all scanlines in the selected file to not have any
 7345:    invalid or underspecified CODEs and that none of the codes are
 7346:    duplicated if this was requested.
 7347: 
 7348: =cut
 7349: 
 7350: sub scantron_validate_CODE {
 7351:     my ($r,$currentphase) = @_;
 7352:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7353:     if ($scantron_config{'CODElocation'} &&
 7354: 	$scantron_config{'CODEstart'} &&
 7355: 	$scantron_config{'CODElength'}) {
 7356: 	if (!defined($env{'form.scantron_CODElist'})) {
 7357: 	    &FIXME_blow_up()
 7358: 	}
 7359:     } else {
 7360: 	return (0,$currentphase+1);
 7361:     }
 7362:     
 7363:     my %usedCODEs;
 7364: 
 7365:     my %allcodes=&get_codes();
 7366: 
 7367:     my $nav_error;
 7368:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
 7369:     if ($nav_error) {
 7370:         $r->print(&navmap_errormsg());
 7371:         return(1,$currentphase);
 7372:     }
 7373: 
 7374:     my ($scanlines,$scan_data)=&scantron_getfile();
 7375:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7376: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7377: 	if ($line=~/^[\s\cz]*$/) { next; }
 7378: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7379: 						 $scan_data);
 7380: 	my $CODE=$$scan_record{'scantron.CODE'};
 7381: 	my $error=0;
 7382: 	if (!&Apache::lonnet::validCODE($CODE)) {
 7383: 	    &scantron_get_correction($r,$i,$scan_record,
 7384: 				     \%scantron_config,
 7385: 				     $line,'incorrectCODE',\%allcodes);
 7386: 	    return(1,$currentphase);
 7387: 	}
 7388: 	if (%allcodes && !exists($allcodes{$CODE}) 
 7389: 	    && !$$scan_record{'scantron.useCODE'}) {
 7390: 	    &scantron_get_correction($r,$i,$scan_record,
 7391: 				     \%scantron_config,
 7392: 				     $line,'incorrectCODE',\%allcodes);
 7393: 	    return(1,$currentphase);
 7394: 	}
 7395: 	if (exists($usedCODEs{$CODE}) 
 7396: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 7397: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 7398: 	    &scantron_get_correction($r,$i,$scan_record,
 7399: 				     \%scantron_config,
 7400: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 7401: 	    return(1,$currentphase);
 7402: 	}
 7403: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 7404:     }
 7405:     return (0,$currentphase+1);
 7406: }
 7407: 
 7408: =pod
 7409: 
 7410: =item scantron_validate_doublebubble
 7411: 
 7412:    Validates all scanlines in the selected file to not have any
 7413:    bubble lines with multiple bubbles marked.
 7414: 
 7415: =cut
 7416: 
 7417: sub scantron_validate_doublebubble {
 7418:     my ($r,$currentphase) = @_;
 7419:     #get student info
 7420:     my $classlist=&Apache::loncoursedata::get_classlist();
 7421:     my %idmap=&username_to_idmap($classlist);
 7422: 
 7423:     #get scantron line setup
 7424:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7425:     my ($scanlines,$scan_data)=&scantron_getfile();
 7426:     my $nav_error;
 7427:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
 7428:     if ($nav_error) {
 7429:         $r->print(&navmap_errormsg());
 7430:         return(1,$currentphase);
 7431:     }
 7432: 
 7433:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7434: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7435: 	if ($line=~/^[\s\cz]*$/) { next; }
 7436: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7437: 						 $scan_data);
 7438: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 7439: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 7440: 				 'doublebubble',
 7441: 				 $$scan_record{'scantron.doubleerror'});
 7442:     	return (1,$currentphase);
 7443:     }
 7444:     return (0,$currentphase+1);
 7445: }
 7446: 
 7447: 
 7448: sub scantron_get_maxbubble {
 7449:     my ($nav_error,$scantron_config) = @_;
 7450:     if (defined($env{'form.scantron_maxbubble'}) &&
 7451: 	$env{'form.scantron_maxbubble'}) {
 7452: 	&restore_bubble_lines();
 7453: 	return $env{'form.scantron_maxbubble'};
 7454:     }
 7455: 
 7456:     my (undef, undef, $sequence) =
 7457: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7458: 
 7459:     my $navmap=Apache::lonnavmaps::navmap->new();
 7460:     unless (ref($navmap)) {
 7461:         if (ref($nav_error)) {
 7462:             $$nav_error = 1;
 7463:         }
 7464:         return;
 7465:     }
 7466:     my $map=$navmap->getResourceByUrl($sequence);
 7467:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7468:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
 7469: 
 7470:     &Apache::lonxml::clear_problem_counter();
 7471: 
 7472:     my $uname       = $env{'user.name'};
 7473:     my $udom        = $env{'user.domain'};
 7474:     my $cid         = $env{'request.course.id'};
 7475:     my $total_lines = 0;
 7476:     %bubble_lines_per_response = ();
 7477:     %first_bubble_line         = ();
 7478:     %subdivided_bubble_lines   = ();
 7479:     %responsetype_per_response = ();
 7480: 
 7481:     my $response_number = 0;
 7482:     my $bubble_line     = 0;
 7483:     foreach my $resource (@resources) {
 7484:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom,undef,$bubbles_per_row);
 7485:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 7486: 	    foreach my $part_id (@{$parts}) {
 7487:                 my $lines;
 7488: 
 7489: 	        # TODO - make this a persistent hash not an array.
 7490: 
 7491:                 # optionresponse, matchresponse and rankresponse type items 
 7492:                 # render as separate sub-questions in exam mode.
 7493:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 7494:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 7495:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 7496:                     my ($numbub,$numshown);
 7497:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 7498:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 7499:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 7500:                         }
 7501:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 7502:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 7503:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 7504:                         }
 7505:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 7506:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 7507:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 7508:                         }
 7509:                     }
 7510:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 7511:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 7512:                     }
 7513:                     my $bubbles_per_row =
 7514:                         &bubblesheet_bubbles_per_row($scantron_config);
 7515:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
 7516:                     if (($numbub % $bubbles_per_row) != 0) {
 7517:                         $inner_bubble_lines++;
 7518:                     }
 7519:                     for (my $i=0; $i<$numshown; $i++) {
 7520:                         $subdivided_bubble_lines{$response_number} .= 
 7521:                             $inner_bubble_lines.',';
 7522:                     }
 7523:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 7524:                     $lines = $numshown * $inner_bubble_lines;
 7525:                 } else {
 7526:                     $lines = $analysis->{"$part_id.bubble_lines"};
 7527:                 }
 7528: 
 7529:                 $first_bubble_line{$response_number} = $bubble_line;
 7530: 	        $bubble_lines_per_response{$response_number} = $lines;
 7531:                 $responsetype_per_response{$response_number} = 
 7532:                     $analysis->{$part_id.'.type'};
 7533: 	        $response_number++;
 7534: 
 7535: 	        $bubble_line +=  $lines;
 7536: 	        $total_lines +=  $lines;
 7537: 	    }
 7538:         }
 7539:     }
 7540:     &Apache::lonnet::delenv('scantron.');
 7541: 
 7542:     &save_bubble_lines();
 7543:     $env{'form.scantron_maxbubble'} =
 7544: 	$total_lines;
 7545:     return $env{'form.scantron_maxbubble'};
 7546: }
 7547: 
 7548: sub bubblesheet_bubbles_per_row {
 7549:     my ($scantron_config) = @_;
 7550:     my $bubbles_per_row;
 7551:     if (ref($scantron_config) eq 'HASH') {
 7552:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
 7553:     }
 7554:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
 7555:         $bubbles_per_row = 10;
 7556:     }
 7557:     return $bubbles_per_row;
 7558: }
 7559: 
 7560: sub scantron_validate_missingbubbles {
 7561:     my ($r,$currentphase) = @_;
 7562:     #get student info
 7563:     my $classlist=&Apache::loncoursedata::get_classlist();
 7564:     my %idmap=&username_to_idmap($classlist);
 7565: 
 7566:     #get scantron line setup
 7567:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7568:     my ($scanlines,$scan_data)=&scantron_getfile();
 7569:     my $nav_error;
 7570:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 7571:     if ($nav_error) {
 7572:         return(1,$currentphase);
 7573:     }
 7574:     if (!$max_bubble) { $max_bubble=2**31; }
 7575:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7576: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7577: 	if ($line=~/^[\s\cz]*$/) { next; }
 7578: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7579: 						 $scan_data);
 7580: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 7581: 	my @to_correct;
 7582: 	
 7583: 	# Probably here's where the error is...
 7584: 
 7585: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 7586:             my $lastbubble;
 7587:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 7588:                my $question = $1;
 7589:                my $subquestion = $2;
 7590:                if (!defined($first_bubble_line{$question -1})) { next; }
 7591:                my $first = $first_bubble_line{$question-1};
 7592:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7593:                my $subcount = 1;
 7594:                while ($subcount<$subquestion) {
 7595:                    $first += $subans[$subcount-1];
 7596:                    $subcount ++;
 7597:                }
 7598:                my $count = $subans[$subquestion-1];
 7599:                $lastbubble = $first + $count;
 7600:             } else {
 7601:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
 7602:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
 7603:             }
 7604:             if ($lastbubble > $max_bubble) { next; }
 7605: 	    push(@to_correct,$missing);
 7606: 	}
 7607: 	if (@to_correct) {
 7608: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7609: 				     $line,'missingbubble',\@to_correct);
 7610: 	    return (1,$currentphase);
 7611: 	}
 7612: 
 7613:     }
 7614:     return (0,$currentphase+1);
 7615: }
 7616: 
 7617: 
 7618: sub scantron_process_students {
 7619:     my ($r,$symb) = @_;
 7620: 
 7621:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7622:     if (!$symb) {
 7623: 	return '';
 7624:     }
 7625:     my $default_form_data=&defaultFormData($symb);
 7626: 
 7627:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7628:     my $bubbles_per_row =
 7629:         &bubblesheet_bubbles_per_row(\%scantron_config);
 7630:     my ($scanlines,$scan_data)=&scantron_getfile();
 7631:     my $classlist=&Apache::loncoursedata::get_classlist();
 7632:     my %idmap=&username_to_idmap($classlist);
 7633:     my $navmap=Apache::lonnavmaps::navmap->new();
 7634:     unless (ref($navmap)) {
 7635:         $r->print(&navmap_errormsg());
 7636:         return '';
 7637:     }  
 7638:     my $map=$navmap->getResourceByUrl($sequence);
 7639:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7640:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
 7641:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 7642:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 7643:     my $resource_error;
 7644:     foreach my $resource (@resources) {
 7645:         my $ressymb;
 7646:         if (ref($resource)) {
 7647:             $ressymb = $resource->symb();
 7648:         } else {
 7649:             $resource_error = 1;
 7650:             last;
 7651:         }
 7652:         my ($analysis,$parts) =
 7653:             &scantron_partids_tograde($resource,$env{'request.course.id'},
 7654:                                       $env{'user.name'},$env{'user.domain'},1,$bubbles_per_row);
 7655:         $grader_partids_by_symb{$ressymb} = $parts;
 7656:         if (ref($analysis) eq 'HASH') {
 7657:             if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 7658:                 $grader_randomlists_by_symb{$ressymb} = 
 7659:                     $analysis->{'parts_withrandomlist'};
 7660:             }
 7661:         }
 7662:     }
 7663:     if ($resource_error) {
 7664:         $r->print(&navmap_errormsg());
 7665:         return '';
 7666:     }
 7667: 
 7668:     my ($uname,$udom);
 7669:     my $result= <<SCANTRONFORM;
 7670: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 7671:   <input type="hidden" name="command" value="scantron_configphase" />
 7672:   $default_form_data
 7673: SCANTRONFORM
 7674:     $r->print($result);
 7675: 
 7676:     my @delayqueue;
 7677:     my (%completedstudents,%scandata);
 7678:     
 7679:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 7680:     my $count=&get_todo_count($scanlines,$scan_data);
 7681:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet Status',
 7682:  				    'Bubblesheet Progress',$count,
 7683: 				    'inline',undef,'scantronupload');
 7684:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 7685: 					  'Processing first student');
 7686:     $r->print('<br />');
 7687:     my $start=&Time::HiRes::time();
 7688:     my $i=-1;
 7689:     my $started;
 7690: 
 7691:     my $nav_error;
 7692:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 7693:     if ($nav_error) {
 7694:         $r->print(&navmap_errormsg());
 7695:         return '';
 7696:     }
 7697: 
 7698:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 7699:     # the user and return.
 7700: 
 7701:     if ($ssi_error) {
 7702: 	$r->print("</form>");
 7703: 	&ssi_print_error($r);
 7704:         &Apache::lonnet::remove_lock($lock);
 7705: 	return '';		# Dunno why the other returns return '' rather than just returning.
 7706:     }
 7707: 
 7708:     my %lettdig = &letter_to_digits();
 7709:     my $numletts = scalar(keys(%lettdig));
 7710: 
 7711:     while ($i<$scanlines->{'count'}) {
 7712:  	($uname,$udom)=('','');
 7713:  	$i++;
 7714:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7715:  	if ($line=~/^[\s\cz]*$/) { next; }
 7716: 	if ($started) {
 7717: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 7718: 						     'last student');
 7719: 	}
 7720: 	$started=1;
 7721:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7722:  						 $scan_data);
 7723:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 7724:  					      \%idmap,$i)) {
 7725:   	    &scantron_add_delay(\@delayqueue,$line,
 7726:  				'Unable to find a student that matches',1);
 7727:  	    next;
 7728:   	}
 7729:  	if (exists $completedstudents{$uname}) {
 7730:  	    &scantron_add_delay(\@delayqueue,$line,
 7731:  				'Student '.$uname.' has multiple sheets',2);
 7732:  	    next;
 7733:  	}
 7734:   	($uname,$udom)=split(/:/,$uname);
 7735: 
 7736:         my (%partids_by_symb,$res_error);
 7737:         foreach my $resource (@resources) {
 7738:             my $ressymb;
 7739:             if (ref($resource)) {
 7740:                 $ressymb = $resource->symb();
 7741:             } else {
 7742:                 $res_error = 1;
 7743:                 last;
 7744:             }
 7745:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 7746:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 7747:                 my ($analysis,$parts) =
 7748:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom,undef,$bubbles_per_row);
 7749:                 $partids_by_symb{$ressymb} = $parts;
 7750:             } else {
 7751:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
 7752:             }
 7753:         }
 7754: 
 7755:         if ($res_error) {
 7756:             &scantron_add_delay(\@delayqueue,$line,
 7757:                                 'An error occurred while grading student '.$uname,2);
 7758:             next;
 7759:         }
 7760: 
 7761: 	&Apache::lonxml::clear_problem_counter();
 7762:   	&Apache::lonnet::appenv($scan_record);
 7763: 
 7764: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 7765: 	    &scantron_putfile($scanlines,$scan_data);
 7766: 	}
 7767: 	
 7768:         my $scancode;
 7769:         if ((exists($scan_record->{'scantron.CODE'})) &&
 7770:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 7771:             $scancode = $scan_record->{'scantron.CODE'};
 7772:         } else {
 7773:             $scancode = '';
 7774:         }
 7775: 
 7776:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 7777:                                    \@resources,\%partids_by_symb,
 7778:                                    $bubbles_per_row) eq 'ssi_error') {
 7779:             $ssi_error = 0; # So end of handler error message does not trigger.
 7780:             $r->print("</form>");
 7781:             &ssi_print_error($r);
 7782:             &Apache::lonnet::remove_lock($lock);
 7783:             return '';      # Why return ''?  Beats me.
 7784:         }
 7785: 
 7786: 	$completedstudents{$uname}={'line'=>$line};
 7787:         if ($env{'form.verifyrecord'}) {
 7788:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 7789:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 7790:             chomp($studentdata);
 7791:             $studentdata =~ s/\r$//;
 7792:             my $studentrecord = '';
 7793:             my $counter = -1;
 7794:             foreach my $resource (@resources) {
 7795:                 my $ressymb = $resource->symb();
 7796:                 ($counter,my $recording) =
 7797:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 7798:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
 7799:                                              \%scantron_config,\%lettdig,$numletts);
 7800:                 $studentrecord .= $recording;
 7801:             }
 7802:             if ($studentrecord ne $studentdata) {
 7803:                 &Apache::lonxml::clear_problem_counter();
 7804:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 7805:                                            \@resources,\%partids_by_symb,
 7806:                                            $bubbles_per_row) eq 'ssi_error') {
 7807:                     $ssi_error = 0; # So end of handler error message does not trigger.
 7808:                     $r->print("</form>");
 7809:                     &ssi_print_error($r);
 7810:                     &Apache::lonnet::remove_lock($lock);
 7811:                     delete($completedstudents{$uname});
 7812:                     return '';
 7813:                 }
 7814:                 $counter = -1;
 7815:                 $studentrecord = '';
 7816:                 foreach my $resource (@resources) {
 7817:                     my $ressymb = $resource->symb();
 7818:                     ($counter,my $recording) =
 7819:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 7820:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 7821:                                                  \%scantron_config,\%lettdig,$numletts);
 7822:                     $studentrecord .= $recording;
 7823:                 }
 7824:                 if ($studentrecord ne $studentdata) {
 7825:                     $r->print('<p><span class="LC_error">');
 7826:                     if ($scancode eq '') {
 7827:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2].',
 7828:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 7829:                     } else {
 7830:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2] and CODE: [_3].',
 7831:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 7832:                     }
 7833:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 7834:                               &Apache::loncommon::start_data_table_header_row()."\n".
 7835:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 7836:                               &Apache::loncommon::end_data_table_header_row()."\n".
 7837:                               &Apache::loncommon::start_data_table_row().
 7838:                               '<td>'.&mt('Bubble Sheet').'</td>'.
 7839:                               '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
 7840:                               &Apache::loncommon::end_data_table_row().
 7841:                               &Apache::loncommon::start_data_table_row().
 7842:                               '<td>Stored submissions</td>'.
 7843:                               '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
 7844:                               &Apache::loncommon::end_data_table_row().
 7845:                               &Apache::loncommon::end_data_table().'</p>');
 7846:                 } else {
 7847:                     $r->print('<br /><span class="LC_warning">'.
 7848:                              &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 />'.
 7849:                              &mt("As a consequence, this user's submission history records two tries.").
 7850:                                  '</span><br />');
 7851:                 }
 7852:             }
 7853:         }
 7854:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 7855:     } continue {
 7856: 	&Apache::lonxml::clear_problem_counter();
 7857: 	&Apache::lonnet::delenv('scantron.');
 7858:     }
 7859:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 7860:     &Apache::lonnet::remove_lock($lock);
 7861: #    my $lasttime = &Time::HiRes::time()-$start;
 7862: #    $r->print("<p>took $lasttime</p>");
 7863: 
 7864:     $r->print("</form>");
 7865:     return '';
 7866: }
 7867: 
 7868: sub graders_resources_pass {
 7869:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
 7870:         $bubbles_per_row) = @_;
 7871:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
 7872:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
 7873:         foreach my $resource (@{$resources}) {
 7874:             my $ressymb = $resource->symb();
 7875:             my ($analysis,$parts) =
 7876:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
 7877:                                           $env{'user.name'},$env{'user.domain'},1,$bubbles_per_row);
 7878:             $grader_partids_by_symb->{$ressymb} = $parts;
 7879:             if (ref($analysis) eq 'HASH') {
 7880:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 7881:                     $grader_randomlists_by_symb->{$ressymb} =
 7882:                         $analysis->{'parts_withrandomlist'};
 7883:                 }
 7884:             }
 7885:         }
 7886:     }
 7887:     return;
 7888: }
 7889: 
 7890: sub grade_student_bubbles {
 7891:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row) = @_;
 7892: # Walk folder as student here to get resources in order student sees.
 7893:     if (ref($resources) eq 'ARRAY') {
 7894:         my $count = 0;
 7895:         foreach my $resource (@{$resources}) {
 7896:             my $ressymb = $resource->symb();
 7897:             my %form = ('submitted'      => 'scantron',
 7898:                         'grade_target'   => 'grade',
 7899:                         'grade_username' => $uname,
 7900:                         'grade_domain'   => $udom,
 7901:                         'grade_courseid' => $env{'request.course.id'},
 7902:                         'grade_symb'     => $ressymb,
 7903:                         'CODE'           => $scancode
 7904:                        );
 7905:             if ($bubbles_per_row ne '') {
 7906:                 $form{'bubbles_per_row'} = $bubbles_per_row;
 7907:             }
 7908:             if (ref($parts) eq 'HASH') {
 7909:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 7910:                     foreach my $part (@{$parts->{$ressymb}}) {
 7911:                         $form{'scantron_questnum_start.'.$part} =
 7912:                             1+$env{'form.scantron.first_bubble_line.'.$count};
 7913:                         $count++;
 7914:                     }
 7915:                 }
 7916:             }
 7917:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 7918:             return 'ssi_error' if ($ssi_error);
 7919:             last if (&Apache::loncommon::connection_aborted($r));
 7920:         }
 7921:     }
 7922:     return;
 7923: }
 7924: 
 7925: sub scantron_upload_scantron_data {
 7926:     my ($r,$symb)=@_;
 7927:     my $dom = $env{'request.role.domain'};
 7928:     my $domdesc = &Apache::lonnet::domain($dom,'description');
 7929:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
 7930:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 7931: 							  'domainid',
 7932: 							  'coursename',$dom);
 7933:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
 7934:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
 7935:     my $default_form_data=&defaultFormData($symb);
 7936:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
 7937:     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.");
 7938:     $r->print(&Apache::lonhtmlcommon::scripttag('
 7939:     function checkUpload(formname) {
 7940: 	if (formname.upfile.value == "") {
 7941: 	    alert("'.$nofile_alert.'");
 7942: 	    return false;
 7943: 	}
 7944:         if (formname.courseid.value == "") {
 7945:             alert("'.$nocourseid_alert.'");
 7946:             return false;
 7947:         }
 7948: 	formname.submit();
 7949:     }
 7950: 
 7951:     function ToSyllabus() {
 7952:         var cdom = '."'$dom'".';
 7953:         var cnum = document.rules.courseid.value;
 7954:         if (cdom == "" || cdom == null) {
 7955:             return;
 7956:         }
 7957:         if (cnum == "" || cnum == null) {
 7958:            return;
 7959:         }
 7960:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
 7961:                             "height=350,width=350,scrollbars=yes,menubar=no");
 7962:         return;
 7963:     }
 7964: 
 7965: '));
 7966:     $r->print('
 7967: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
 7968: 
 7969: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 7970: '.$default_form_data.
 7971:   &Apache::lonhtmlcommon::start_pick_box().
 7972:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
 7973:   '<input name="courseid" type="text" size="30" />'.$select_link.
 7974:   &Apache::lonhtmlcommon::row_closure().
 7975:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
 7976:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
 7977:   &Apache::lonhtmlcommon::row_closure().
 7978:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
 7979:   '<input name="domainid" type="hidden" />'.$domdesc.
 7980:   &Apache::lonhtmlcommon::row_closure().
 7981:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
 7982:   '<input type="file" name="upfile" size="50" />'.
 7983:   &Apache::lonhtmlcommon::row_closure(1).
 7984:   &Apache::lonhtmlcommon::end_pick_box().'<br />
 7985: 
 7986: <input name="command" value="scantronupload_save" type="hidden" />
 7987: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 7988: </form>
 7989: ');
 7990:     return '';
 7991: }
 7992: 
 7993: 
 7994: sub scantron_upload_scantron_data_save {
 7995:     my($r,$symb)=@_;
 7996:     my $doanotherupload=
 7997: 	'<br /><form action="/adm/grades" method="post">'."\n".
 7998: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 7999: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 8000: 	'</form>'."\n";
 8001:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 8002: 	!&Apache::lonnet::allowed('usc',
 8003: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 8004: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
 8005: 	unless ($symb) {
 8006: 	    $r->print($doanotherupload);
 8007: 	}
 8008: 	return '';
 8009:     }
 8010:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 8011:     my $uploadedfile;
 8012:     $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
 8013:     if (length($env{'form.upfile'}) < 2) {
 8014:         $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>'));
 8015:     } else {
 8016:         my $result = 
 8017:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
 8018:                                             $env{'form.courseid'},$env{'form.domainid'});
 8019: 	if ($result =~ m{^/uploaded/}) {
 8020: 	    $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
 8021:                           '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
 8022: 			  '<span class="LC_filename">'.$result.'</span>'));
 8023:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
 8024:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
 8025:                                                        $env{'form.courseid'},$uploadedfile));
 8026: 	} else {
 8027: 	    $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
 8028:                           '<span class="LC_error">','</span>',$result,
 8029: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 8030: 	}
 8031:     }
 8032:     if ($symb) {
 8033: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
 8034:     } else {
 8035: 	$r->print($doanotherupload);
 8036:     }
 8037:     return '';
 8038: }
 8039: 
 8040: sub validate_uploaded_scantron_file {
 8041:     my ($cdom,$cname,$fname) = @_;
 8042:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
 8043:     my @lines;
 8044:     if ($scanlines ne '-1') {
 8045:         @lines=split("\n",$scanlines,-1);
 8046:     }
 8047:     my $output;
 8048:     if (@lines) {
 8049:         my (%counts,$max_match_format);
 8050:         my ($max_match_count,$max_match_pct) = (0,0);
 8051:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
 8052:         my %idmap = &username_to_idmap($classlist);
 8053:         foreach my $key (keys(%idmap)) {
 8054:             my $lckey = lc($key);
 8055:             $idmap{$lckey} = $idmap{$key};
 8056:         }
 8057:         my %unique_formats;
 8058:         my @formatlines = &get_scantronformat_file();
 8059:         foreach my $line (@formatlines) {
 8060:             chomp($line);
 8061:             my @config = split(/:/,$line);
 8062:             my $idstart = $config[5];
 8063:             my $idlength = $config[6];
 8064:             if (($idstart ne '') && ($idlength > 0)) {
 8065:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
 8066:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
 8067:                 } else {
 8068:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
 8069:                 }
 8070:             }
 8071:         }
 8072:         foreach my $key (keys(%unique_formats)) {
 8073:             my ($idstart,$idlength) = split(':',$key);
 8074:             %{$counts{$key}} = (
 8075:                                'found'   => 0,
 8076:                                'total'   => 0,
 8077:                               );
 8078:             foreach my $line (@lines) {
 8079:                 next if ($line =~ /^#/);
 8080:                 next if ($line =~ /^[\s\cz]*$/);
 8081:                 my $id = substr($line,$idstart-1,$idlength);
 8082:                 $id = lc($id);
 8083:                 if (exists($idmap{$id})) {
 8084:                     $counts{$key}{'found'} ++;
 8085:                 }
 8086:                 $counts{$key}{'total'} ++;
 8087:             }
 8088:             if ($counts{$key}{'total'}) {
 8089:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
 8090:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
 8091:                     $max_match_pct = $percent_match;
 8092:                     $max_match_format = $key;
 8093:                     $max_match_count = $counts{$key}{'total'};
 8094:                 }
 8095:             }
 8096:         }
 8097:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
 8098:             my $format_descs;
 8099:             my $numwithformat = @{$unique_formats{$max_match_format}};
 8100:             for (my $i=0; $i<$numwithformat; $i++) {
 8101:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
 8102:                 if ($i<$numwithformat-2) {
 8103:                     $format_descs .= '"<i>'.$desc.'</i>", ';
 8104:                 } elsif ($i==$numwithformat-2) {
 8105:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
 8106:                 } elsif ($i==$numwithformat-1) {
 8107:                     $format_descs .= '"<i>'.$desc.'</i>"';
 8108:                 }
 8109:             }
 8110:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
 8111:             $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).
 8112:                        '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
 8113:                        '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
 8114:                        '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
 8115:                                   '<i>'.$cdom.'</i>').'</li>'.
 8116:                        '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
 8117:                        '<li>'.&mt('The course roster is not up to date').'</li>'.
 8118:                        '</ul>';
 8119:         }
 8120:     } else {
 8121:         $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
 8122:     }
 8123:     return $output;
 8124: }
 8125: 
 8126: sub valid_file {
 8127:     my ($requested_file)=@_;
 8128:     foreach my $filename (sort(&scantron_filenames())) {
 8129: 	if ($requested_file eq $filename) { return 1; }
 8130:     }
 8131:     return 0;
 8132: }
 8133: 
 8134: sub scantron_download_scantron_data {
 8135:     my ($r,$symb)=@_;
 8136:     my $default_form_data=&defaultFormData($symb);
 8137:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 8138:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8139:     my $file=$env{'form.scantron_selectfile'};
 8140:     if (! &valid_file($file)) {
 8141: 	$r->print('
 8142: 	<p>
 8143: 	    '.&mt('The requested file name was invalid.').'
 8144:         </p>
 8145: ');
 8146: 	return;
 8147:     }
 8148:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 8149:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 8150:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 8151:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 8152:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 8153:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 8154:     $r->print('
 8155:     <p>
 8156: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
 8157: 	      '<a href="'.$orig.'">','</a>').'
 8158:     </p>
 8159:     <p>
 8160: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 8161: 	      '<a href="'.$corrected.'">','</a>').'
 8162:     </p>
 8163:     <p>
 8164: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 8165: 	      '<a href="'.$skipped.'">','</a>').'
 8166:     </p>
 8167: ');
 8168:     return '';
 8169: }
 8170: 
 8171: sub checkscantron_results {
 8172:     my ($r,$symb) = @_;
 8173:     if (!$symb) {return '';}
 8174:     my $cid = $env{'request.course.id'};
 8175:     my %lettdig = &letter_to_digits();
 8176:     my $numletts = scalar(keys(%lettdig));
 8177:     my $cnum = $env{'course.'.$cid.'.num'};
 8178:     my $cdom = $env{'course.'.$cid.'.domain'};
 8179:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8180:     my %record;
 8181:     my %scantron_config =
 8182:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
 8183:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8184:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
 8185:     my $classlist=&Apache::loncoursedata::get_classlist();
 8186:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 8187:     my $navmap=Apache::lonnavmaps::navmap->new();
 8188:     unless (ref($navmap)) {
 8189:         $r->print(&navmap_errormsg());
 8190:         return '';
 8191:     }
 8192:     my $map=$navmap->getResourceByUrl($sequence);
 8193:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8194:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
 8195:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,                             \%grader_randomlists_by_symb);
 8196: 
 8197:     my ($uname,$udom);
 8198:     my (%scandata,%lastname,%bylast);
 8199:     $r->print('
 8200: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 8201: 
 8202:     my @delayqueue;
 8203:     my %completedstudents;
 8204: 
 8205:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
 8206:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet/Submissions Comparison Status',
 8207:                                     'Progress of Bubblesheet Data/Submission Records Comparison',$count,
 8208:                                     'inline',undef,'checkscantron');
 8209:     my ($username,$domain,$started);
 8210:     my $nav_error;
 8211:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 8212:     if ($nav_error) {
 8213:         $r->print(&navmap_errormsg());
 8214:         return '';
 8215:     }
 8216: 
 8217:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 8218:                                           'Processing first student');
 8219:     my $start=&Time::HiRes::time();
 8220:     my $i=-1;
 8221: 
 8222:     while ($i<$scanlines->{'count'}) {
 8223:         ($username,$domain,$uname)=('','','');
 8224:         $i++;
 8225:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 8226:         if ($line=~/^[\s\cz]*$/) { next; }
 8227:         if ($started) {
 8228:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 8229:                                                      'last student');
 8230:         }
 8231:         $started=1;
 8232:         my $scan_record=
 8233:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 8234:                                                      $scan_data);
 8235:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
 8236:                                                               \%idmap,$i)) {
 8237:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 8238:                                 'Unable to find a student that matches',1);
 8239:             next;
 8240:         }
 8241:         if (exists $completedstudents{$uname}) {
 8242:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 8243:                                 'Student '.$uname.' has multiple sheets',2);
 8244:             next;
 8245:         }
 8246:         my $pid = $scan_record->{'scantron.ID'};
 8247:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 8248:         push(@{$bylast{$lastname{$pid}}},$pid);
 8249:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 8250:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 8251:         chomp($scandata{$pid});
 8252:         $scandata{$pid} =~ s/\r$//;
 8253:         ($username,$domain)=split(/:/,$uname);
 8254:         my $counter = -1;
 8255:         foreach my $resource (@resources) {
 8256:             my $parts;
 8257:             my $ressymb = $resource->symb();
 8258:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 8259:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 8260:                 (my $analysis,$parts) =
 8261:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$username,$domain,undef,$bubbles_per_row);
 8262:             } else {
 8263:                 $parts = $grader_partids_by_symb{$ressymb};
 8264:             }
 8265:             ($counter,my $recording) =
 8266:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
 8267:                                          $scandata{$pid},$parts,
 8268:                                          \%scantron_config,\%lettdig,$numletts);
 8269:             $record{$pid} .= $recording;
 8270:         }
 8271:     }
 8272:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 8273:     $r->print('<br />');
 8274:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 8275:     $passed = 0;
 8276:     $failed = 0;
 8277:     $numstudents = 0;
 8278:     foreach my $last (sort(keys(%bylast))) {
 8279:         if (ref($bylast{$last}) eq 'ARRAY') {
 8280:             foreach my $pid (sort(@{$bylast{$last}})) {
 8281:                 my $showscandata = $scandata{$pid};
 8282:                 my $showrecord = $record{$pid};
 8283:                 $showscandata =~ s/\s/&nbsp;/g;
 8284:                 $showrecord =~ s/\s/&nbsp;/g;
 8285:                 if ($scandata{$pid} eq $record{$pid}) {
 8286:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 8287:                     $okstudents .= '<tr class="'.$css_class.'">'.
 8288: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 8289: '</tr>'."\n".
 8290: '<tr class="'.$css_class.'">'."\n".
 8291: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
 8292:                     $passed ++;
 8293:                 } else {
 8294:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
 8295:                     $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".
 8296: '</tr>'."\n".
 8297: '<tr class="'.$css_class.'">'."\n".
 8298: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
 8299: '</tr>'."\n";
 8300:                     $failed ++;
 8301:                 }
 8302:                 $numstudents ++;
 8303:             }
 8304:         }
 8305:     }
 8306:     $r->print(
 8307:         '<p>'
 8308:        .&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).',
 8309:             '<b>',
 8310:             $numstudents,
 8311:             '</b>',
 8312:             $env{'form.scantron_maxbubble'})
 8313:        .'</p>'
 8314:     );
 8315:     $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>');
 8316:     if ($passed) {
 8317:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
 8318:         $r->print(&Apache::loncommon::start_data_table()."\n".
 8319:                  &Apache::loncommon::start_data_table_header_row()."\n".
 8320:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 8321:                  &Apache::loncommon::end_data_table_header_row()."\n".
 8322:                  $okstudents."\n".
 8323:                  &Apache::loncommon::end_data_table().'<br />');
 8324:     }
 8325:     if ($failed) {
 8326:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
 8327:         $r->print(&Apache::loncommon::start_data_table()."\n".
 8328:                  &Apache::loncommon::start_data_table_header_row()."\n".
 8329:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 8330:                  &Apache::loncommon::end_data_table_header_row()."\n".
 8331:                  $badstudents."\n".
 8332:                  &Apache::loncommon::end_data_table()).'<br />'.
 8333:                  &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.');  
 8334:     }
 8335:     $r->print('</form><br />');
 8336:     return;
 8337: }
 8338: 
 8339: sub verify_scantron_grading {
 8340:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
 8341:         $scantron_config,$lettdig,$numletts) = @_;
 8342:     my ($record,%expected,%startpos);
 8343:     return ($counter,$record) if (!ref($resource));
 8344:     return ($counter,$record) if (!$resource->is_problem());
 8345:     my $symb = $resource->symb();
 8346:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
 8347:     foreach my $part_id (@{$partids}) {
 8348:         $counter ++;
 8349:         $expected{$part_id} = 0;
 8350:         if ($env{"form.scantron.sub_bubblelines.$counter"}) {
 8351:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
 8352:             foreach my $item (@sub_lines) {
 8353:                 $expected{$part_id} += $item;
 8354:             }
 8355:         } else {
 8356:             $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
 8357:         }
 8358:         $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
 8359:     }
 8360:     if ($symb) {
 8361:         my %recorded;
 8362:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
 8363:         if ($returnhash{'version'}) {
 8364:             my %lasthash=();
 8365:             my $version;
 8366:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 8367:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 8368:                     $lasthash{$key}=$returnhash{$version.':'.$key};
 8369:                 }
 8370:             }
 8371:             foreach my $key (keys(%lasthash)) {
 8372:                 if ($key =~ /\.scantron$/) {
 8373:                     my $value = &unescape($lasthash{$key});
 8374:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
 8375:                     if ($value eq '') {
 8376:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
 8377:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
 8378:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8379:                             }
 8380:                         }
 8381:                     } else {
 8382:                         my @tocheck;
 8383:                         my @items = split(//,$value);
 8384:                         if (($scantron_config->{'Qon'} eq 'letter') ||
 8385:                             ($scantron_config->{'Qon'} eq 'number')) {
 8386:                             if (@items < $expected{$part_id}) {
 8387:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
 8388:                                 my @singles = split(//,$fragment);
 8389:                                 foreach my $pos (@singles) {
 8390:                                     if ($pos eq ' ') {
 8391:                                         push(@tocheck,$pos);
 8392:                                     } else {
 8393:                                         my $next = shift(@items);
 8394:                                         push(@tocheck,$next);
 8395:                                     }
 8396:                                 }
 8397:                             } else {
 8398:                                 @tocheck = @items;
 8399:                             }
 8400:                             foreach my $letter (@tocheck) {
 8401:                                 if ($scantron_config->{'Qon'} eq 'letter') {
 8402:                                     if ($letter !~ /^[A-J]$/) {
 8403:                                         $letter = $scantron_config->{'Qoff'};
 8404:                                     }
 8405:                                     $recorded{$part_id} .= $letter;
 8406:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
 8407:                                     my $digit;
 8408:                                     if ($letter !~ /^[A-J]$/) {
 8409:                                         $digit = $scantron_config->{'Qoff'};
 8410:                                     } else {
 8411:                                         $digit = $lettdig->{$letter};
 8412:                                     }
 8413:                                     $recorded{$part_id} .= $digit;
 8414:                                 }
 8415:                             }
 8416:                         } else {
 8417:                             @tocheck = @items;
 8418:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
 8419:                                 my $curr_sub = shift(@tocheck);
 8420:                                 my $digit;
 8421:                                 if ($curr_sub =~ /^[A-J]$/) {
 8422:                                     $digit = $lettdig->{$curr_sub}-1;
 8423:                                 }
 8424:                                 if ($curr_sub eq 'J') {
 8425:                                     $digit += scalar($numletts);
 8426:                                 }
 8427:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 8428:                                     if ($j == $digit) {
 8429:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
 8430:                                     } else {
 8431:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8432:                                     }
 8433:                                 }
 8434:                             }
 8435:                         }
 8436:                     }
 8437:                 }
 8438:             }
 8439:         }
 8440:         foreach my $part_id (@{$partids}) {
 8441:             if ($recorded{$part_id} eq '') {
 8442:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
 8443:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 8444:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8445:                     }
 8446:                 }
 8447:             }
 8448:             $record .= $recorded{$part_id};
 8449:         }
 8450:     }
 8451:     return ($counter,$record);
 8452: }
 8453: 
 8454: sub letter_to_digits { 
 8455:     my %lettdig = (
 8456:                     A => 1,
 8457:                     B => 2,
 8458:                     C => 3,
 8459:                     D => 4,
 8460:                     E => 5,
 8461:                     F => 6,
 8462:                     G => 7,
 8463:                     H => 8,
 8464:                     I => 9,
 8465:                     J => 0,
 8466:                   );
 8467:     return %lettdig;
 8468: }
 8469: 
 8470: 
 8471: #-------- end of section for handling grading scantron forms -------
 8472: #
 8473: #-------------------------------------------------------------------
 8474: 
 8475: #-------------------------- Menu interface -------------------------
 8476: #
 8477: #--- Href with symb and command ---
 8478: 
 8479: sub href_symb_cmd {
 8480:     my ($symb,$cmd)=@_;
 8481:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&command='.$cmd;
 8482: }
 8483: 
 8484: sub grading_menu {
 8485:     my ($request,$symb) = @_;
 8486:     if (!$symb) {return '';}
 8487: 
 8488:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 8489:                   'command'=>'individual');
 8490:     
 8491:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8492: 
 8493:     $fields{'command'}='ungraded';
 8494:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8495: 
 8496:     $fields{'command'}='table';
 8497:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8498: 
 8499:     $fields{'command'}='all_for_one';
 8500:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8501: 
 8502:     $fields{'command'}='downloadfilesselect';
 8503:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8504: 
 8505:     $fields{'command'} = 'csvform';
 8506:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8507:     
 8508:     $fields{'command'} = 'processclicker';
 8509:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8510:     
 8511:     $fields{'command'} = 'scantron_selectphase';
 8512:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8513: 
 8514:     $fields{'command'} = 'initialverifyreceipt';
 8515:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8516:     
 8517:     my @menu = ({	categorytitle=>'Hand Grading',
 8518:             items =>[
 8519:                         {	linktext => 'Select individual students to grade',
 8520:                     		url => $url1a,
 8521:                     		permission => 'F',
 8522:                     		icon => 'grade_students.png',
 8523:                     		linktitle => 'Grade current resource for a selection of students.'
 8524:                         }, 
 8525:                         {       linktext => 'Grade ungraded submissions.',
 8526:                                 url => $url1b,
 8527:                                 permission => 'F',
 8528:                                 icon => 'ungrade_sub.png',
 8529:                                 linktitle => 'Grade all submissions that have not been graded yet.'
 8530:                         },
 8531: 
 8532:                         {       linktext => 'Grading table',
 8533:                                 url => $url1c,
 8534:                                 permission => 'F',
 8535:                                 icon => 'grading_table.png',
 8536:                                 linktitle => 'Grade current resource for all students.'
 8537:                         },
 8538:                         {       linktext => 'Grade page/folder for one student',
 8539:                                 url => $url1d,
 8540:                                 permission => 'F',
 8541:                                 icon => 'grade_PageFolder.png',
 8542:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
 8543:                         },
 8544:                         {       linktext => 'Download submissions',
 8545:                                 url => $url1e,
 8546:                                 permission => 'F',
 8547:                                 icon => 'download_sub.png',
 8548:                                 linktitle => 'Download all students submissions.'
 8549:                         }]},
 8550:                          { categorytitle=>'Automated Grading',
 8551:                items =>[
 8552: 
 8553:                 	    {	linktext => 'Upload Scores',
 8554:                     		url => $url2,
 8555:                     		permission => 'F',
 8556:                     		icon => 'uploadscores.png',
 8557:                     		linktitle => 'Specify a file containing the class scores for current resource.'
 8558:                 	    },
 8559:                 	    {	linktext => 'Process Clicker',
 8560:                     		url => $url3,
 8561:                     		permission => 'F',
 8562:                     		icon => 'addClickerInfoFile.png',
 8563:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
 8564:                 	    },
 8565:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
 8566:                     		url => $url4,
 8567:                     		permission => 'F',
 8568:                     		icon => 'bubblesheet.png',
 8569:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
 8570:                 	    },
 8571:                             {   linktext => 'Verify Receipt Number',
 8572:                                 url => $url5,
 8573:                                 permission => 'F',
 8574:                                 icon => 'receipt_number.png',
 8575:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
 8576:                             }
 8577: 
 8578:                     ]
 8579:             });
 8580: 
 8581:     # Create the menu
 8582:     my $Str;
 8583:     $Str .= '<form method="post" action="" name="gradingMenu">';
 8584:     $Str .= '<input type="hidden" name="command" value="" />'.
 8585:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 8586: 
 8587:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
 8588:     return $Str;    
 8589: }
 8590: 
 8591: 
 8592: sub ungraded {
 8593:     my ($request)=@_;
 8594:     &submit_options($request);
 8595: }
 8596: 
 8597: sub submit_options_sequence {
 8598:     my ($request,$symb) = @_;
 8599:     if (!$symb) {return '';}
 8600:     &commonJSfunctions($request);
 8601:     my $result;
 8602: 
 8603:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8604:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 8605:     $result.=&selectfield(0).
 8606:             '<input type="hidden" name="command" value="pickStudentPage" />
 8607:             <div>
 8608:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 8609:             </div>
 8610:         </div>
 8611:   </form>';
 8612:     return $result;
 8613: }
 8614: 
 8615: sub submit_options_table {
 8616:     my ($request,$symb) = @_;
 8617:     if (!$symb) {return '';}
 8618:     &commonJSfunctions($request);
 8619:     my $result;
 8620: 
 8621:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8622:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 8623: 
 8624:     $result.=&selectfield(0).
 8625:             '<input type="hidden" name="command" value="viewgrades" />
 8626:             <div>
 8627:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 8628:             </div>
 8629:         </div>
 8630:   </form>';
 8631:     return $result;
 8632: }
 8633: 
 8634: sub submit_options_download {
 8635:     my ($request,$symb) = @_;
 8636:     if (!$symb) {return '';}
 8637: 
 8638:     &commonJSfunctions($request);
 8639: 
 8640:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8641:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 8642:     $result.='
 8643: <h2>
 8644:   '.&mt('Select Students for Which to Download Submissions').'
 8645: </h2>'.&selectfield(1).'
 8646:                 <input type="hidden" name="command" value="downloadfileslink" /> 
 8647:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 8648:             </div>
 8649:           </div>
 8650: 
 8651: 
 8652:   </form>';
 8653:     return $result;
 8654: }
 8655: 
 8656: #--- Displays the submissions first page -------
 8657: sub submit_options {
 8658:     my ($request,$symb) = @_;
 8659:     if (!$symb) {return '';}
 8660: 
 8661:     &commonJSfunctions($request);
 8662:     my $result;
 8663: 
 8664:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8665: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 8666:     $result.=&selectfield(1).'
 8667:                 <input type="hidden" name="command" value="submission" /> 
 8668: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
 8669:             </div>
 8670:           </div>
 8671: 
 8672: 
 8673:   </form>';
 8674:     return $result;
 8675: }
 8676: 
 8677: sub selectfield {
 8678:    my ($full)=@_;
 8679:    my %options = 
 8680:           (&Apache::lonlocal::texthash(
 8681:              'yes'       => 'with submissions',
 8682:              'queued'    => 'in grading queue',
 8683:              'graded'    => 'with ungraded submissions',
 8684:              'incorrect' => 'with incorrect submissions',
 8685:              'all'       => 'with any status'),
 8686:              'select_form_order' => ['yes','queued','graded','incorrect','all']);
 8687:    my $result='<div class="LC_columnSection">
 8688:   
 8689:     <fieldset>
 8690:       <legend>
 8691:        '.&mt('Sections').'
 8692:       </legend>
 8693:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
 8694:     </fieldset>
 8695:   
 8696:     <fieldset>
 8697:       <legend>
 8698:         '.&mt('Groups').'
 8699:       </legend>
 8700:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
 8701:     </fieldset>
 8702:   
 8703:     <fieldset>
 8704:       <legend>
 8705:         '.&mt('Access Status').'
 8706:       </legend>
 8707:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
 8708:     </fieldset>';
 8709:     if ($full) {
 8710:        $result.='
 8711:     <fieldset>
 8712:       <legend>
 8713:         '.&mt('Submission Status').'
 8714:       </legend>'.
 8715:        &Apache::loncommon::select_form('all','submitonly',\%options).
 8716:    '</fieldset>';
 8717:     }
 8718:     $result.='</div><br />';
 8719:     return $result;
 8720: }
 8721: 
 8722: sub reset_perm {
 8723:     undef(%perm);
 8724: }
 8725: 
 8726: sub init_perm {
 8727:     &reset_perm();
 8728:     foreach my $test_perm ('vgr','mgr','opa') {
 8729: 
 8730: 	my $scope = $env{'request.course.id'};
 8731: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
 8732: 
 8733: 	    $scope .= '/'.$env{'request.course.sec'};
 8734: 	    if ( $perm{$test_perm}=
 8735: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
 8736: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
 8737: 	    } else {
 8738: 		delete($perm{$test_perm});
 8739: 	    }
 8740: 	}
 8741:     }
 8742: }
 8743: 
 8744: sub gather_clicker_ids {
 8745:     my %clicker_ids;
 8746: 
 8747:     my $classlist = &Apache::loncoursedata::get_classlist();
 8748: 
 8749:     # Set up a couple variables.
 8750:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
 8751:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
 8752:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
 8753: 
 8754:     foreach my $student (keys(%$classlist)) {
 8755:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
 8756:         my $username = $classlist->{$student}->[$username_idx];
 8757:         my $domain   = $classlist->{$student}->[$domain_idx];
 8758:         my $clickers =
 8759: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
 8760:         foreach my $id (split(/\,/,$clickers)) {
 8761:             $id=~s/^[\#0]+//;
 8762:             $id=~s/[\-\:]//g;
 8763:             if (exists($clicker_ids{$id})) {
 8764: 		$clicker_ids{$id}.=','.$username.':'.$domain;
 8765:             } else {
 8766: 		$clicker_ids{$id}=$username.':'.$domain;
 8767:             }
 8768:         }
 8769:     }
 8770:     return %clicker_ids;
 8771: }
 8772: 
 8773: sub gather_adv_clicker_ids {
 8774:     my %clicker_ids;
 8775:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 8776:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8777:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
 8778:     foreach my $element (sort(keys(%coursepersonnel))) {
 8779:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
 8780:             my ($puname,$pudom)=split(/\:/,$person);
 8781:             my $clickers =
 8782: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
 8783:             foreach my $id (split(/\,/,$clickers)) {
 8784: 		$id=~s/^[\#0]+//;
 8785:                 $id=~s/[\-\:]//g;
 8786: 		if (exists($clicker_ids{$id})) {
 8787: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
 8788: 		} else {
 8789: 		    $clicker_ids{$id}=$puname.':'.$pudom;
 8790: 		}
 8791:             }
 8792:         }
 8793:     }
 8794:     return %clicker_ids;
 8795: }
 8796: 
 8797: sub clicker_grading_parameters {
 8798:     return ('gradingmechanism' => 'scalar',
 8799:             'upfiletype' => 'scalar',
 8800:             'specificid' => 'scalar',
 8801:             'pcorrect' => 'scalar',
 8802:             'pincorrect' => 'scalar');
 8803: }
 8804: 
 8805: sub process_clicker {
 8806:     my ($r,$symb)=@_;
 8807:     if (!$symb) {return '';}
 8808:     my $result=&checkforfile_js();
 8809:     $result.=&Apache::loncommon::start_data_table().
 8810:              &Apache::loncommon::start_data_table_header_row().
 8811:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
 8812:              &Apache::loncommon::end_data_table_header_row().
 8813:              &Apache::loncommon::start_data_table_row()."<td>\n";
 8814: # Attempt to restore parameters from last session, set defaults if not present
 8815:     my %Saveable_Parameters=&clicker_grading_parameters();
 8816:     &Apache::loncommon::restore_course_settings('grades_clicker',
 8817:                                                  \%Saveable_Parameters);
 8818:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
 8819:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
 8820:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
 8821:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
 8822: 
 8823:     my %checked;
 8824:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
 8825:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
 8826:           $checked{$gradingmechanism}=' checked="checked"';
 8827:        }
 8828:     }
 8829: 
 8830:     my $upload=&mt("Evaluate File");
 8831:     my $type=&mt("Type");
 8832:     my $attendance=&mt("Award points just for participation");
 8833:     my $personnel=&mt("Correctness determined from response by course personnel");
 8834:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
 8835:     my $given=&mt("Correctness determined from given list of answers").' '.
 8836:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
 8837:     my $pcorrect=&mt("Percentage points for correct solution");
 8838:     my $pincorrect=&mt("Percentage points for incorrect solution");
 8839:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
 8840: 						   {'iclicker' => 'i>clicker',
 8841:                                                     'interwrite' => 'interwrite PRS'});
 8842:     $symb = &Apache::lonenc::check_encrypt($symb);
 8843:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
 8844: function sanitycheck() {
 8845: // Accept only integer percentages
 8846:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
 8847:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
 8848: // Find out grading choice
 8849:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8850:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
 8851:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
 8852:       }
 8853:    }
 8854: // By default, new choice equals user selection
 8855:    newgradingchoice=gradingchoice;
 8856: // Not good to give more points for false answers than correct ones
 8857:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
 8858:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
 8859:    }
 8860: // If new choice is attendance only, and old choice was correctness-based, restore defaults
 8861:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
 8862:       document.forms.gradesupload.pcorrect.value=100;
 8863:       document.forms.gradesupload.pincorrect.value=100;
 8864:    }
 8865: // If the values are different, cannot be attendance only
 8866:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
 8867:        (gradingchoice=='attendance')) {
 8868:        newgradingchoice='personnel';
 8869:    }
 8870: // Change grading choice to new one
 8871:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8872:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
 8873:          document.forms.gradesupload.gradingmechanism[i].checked=true;
 8874:       } else {
 8875:          document.forms.gradesupload.gradingmechanism[i].checked=false;
 8876:       }
 8877:    }
 8878: // Remember the old state
 8879:    document.forms.gradesupload.waschecked.value=newgradingchoice;
 8880: }
 8881: ENDUPFORM
 8882:     $result.= <<ENDUPFORM;
 8883: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 8884: <input type="hidden" name="symb" value="$symb" />
 8885: <input type="hidden" name="command" value="processclickerfile" />
 8886: <input type="file" name="upfile" size="50" />
 8887: <br /><label>$type: $selectform</label>
 8888: ENDUPFORM
 8889:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
 8890:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
 8891:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
 8892: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
 8893: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
 8894: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
 8895: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
 8896: <br />&nbsp;&nbsp;&nbsp;
 8897: <input type="text" name="givenanswer" size="50" />
 8898: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
 8899: ENDGRADINGFORM
 8900:          $result.='</td>'.&Apache::loncommon::end_data_table_row().
 8901:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
 8902:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
 8903: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
 8904: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 8905: </form>'
 8906: ENDPERCFORM
 8907:     $result.='</td>'.
 8908:              &Apache::loncommon::end_data_table_row().
 8909:              &Apache::loncommon::end_data_table();
 8910:     return $result;
 8911: }
 8912: 
 8913: sub process_clicker_file {
 8914:     my ($r,$symb)=@_;
 8915:     if (!$symb) {return '';}
 8916: 
 8917:     my %Saveable_Parameters=&clicker_grading_parameters();
 8918:     &Apache::loncommon::store_course_settings('grades_clicker',
 8919:                                               \%Saveable_Parameters);
 8920:     my $result='';
 8921:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
 8922: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
 8923: 	return $result;
 8924:     }
 8925:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
 8926:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
 8927:         return $result;
 8928:     }
 8929:     my $foundgiven=0;
 8930:     if ($env{'form.gradingmechanism'} eq 'given') {
 8931:         $env{'form.givenanswer'}=~s/^\s*//gs;
 8932:         $env{'form.givenanswer'}=~s/\s*$//gs;
 8933:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
 8934:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
 8935:         my @answers=split(/\,/,$env{'form.givenanswer'});
 8936:         $foundgiven=$#answers+1;
 8937:     }
 8938:     my %clicker_ids=&gather_clicker_ids();
 8939:     my %correct_ids;
 8940:     if ($env{'form.gradingmechanism'} eq 'personnel') {
 8941: 	%correct_ids=&gather_adv_clicker_ids();
 8942:     }
 8943:     if ($env{'form.gradingmechanism'} eq 'specific') {
 8944: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
 8945: 	   $correct_id=~tr/a-z/A-Z/;
 8946: 	   $correct_id=~s/\s//gs;
 8947: 	   $correct_id=~s/^[\#0]+//;
 8948:            $correct_id=~s/[\-\:]//g;
 8949:            if ($correct_id) {
 8950: 	      $correct_ids{$correct_id}='specified';
 8951:            }
 8952:         }
 8953:     }
 8954:     if ($env{'form.gradingmechanism'} eq 'attendance') {
 8955: 	$result.=&mt('Score based on attendance only');
 8956:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
 8957:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
 8958:     } else {
 8959: 	my $number=0;
 8960: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
 8961: 	foreach my $id (sort(keys(%correct_ids))) {
 8962: 	    $result.='<br /><tt>'.$id.'</tt> - ';
 8963: 	    if ($correct_ids{$id} eq 'specified') {
 8964: 		$result.=&mt('specified');
 8965: 	    } else {
 8966: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
 8967: 		$result.=&Apache::loncommon::plainname($uname,$udom);
 8968: 	    }
 8969: 	    $number++;
 8970: 	}
 8971:         $result.="</p>\n";
 8972: 	if ($number==0) {
 8973: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
 8974: 	    return $result;
 8975: 	}
 8976:     }
 8977:     if (length($env{'form.upfile'}) < 2) {
 8978:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
 8979: 		     '<span class="LC_error">',
 8980: 		     '</span>',
 8981: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
 8982:         return $result;
 8983:     }
 8984: 
 8985: # Were able to get all the info needed, now analyze the file
 8986: 
 8987:     $result.=&Apache::loncommon::studentbrowser_javascript();
 8988:     $symb = &Apache::lonenc::check_encrypt($symb);
 8989:     $result.=&Apache::loncommon::start_data_table().
 8990:              &Apache::loncommon::start_data_table_header_row().
 8991:              '<th>'.&mt('Evaluate clicker file').'</th>'.
 8992:              &Apache::loncommon::end_data_table_header_row().
 8993:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
 8994: <td>
 8995: <form method="post" action="/adm/grades" name="clickeranalysis">
 8996: <input type="hidden" name="symb" value="$symb" />
 8997: <input type="hidden" name="command" value="assignclickergrades" />
 8998: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
 8999: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
 9000: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
 9001: ENDHEADER
 9002:     if ($env{'form.gradingmechanism'} eq 'given') {
 9003:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
 9004:     } 
 9005:     my %responses;
 9006:     my @questiontitles;
 9007:     my $errormsg='';
 9008:     my $number=0;
 9009:     if ($env{'form.upfiletype'} eq 'iclicker') {
 9010: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
 9011:     }
 9012:     if ($env{'form.upfiletype'} eq 'interwrite') {
 9013:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
 9014:     }
 9015:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
 9016:              '<input type="hidden" name="number" value="'.$number.'" />'.
 9017:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
 9018:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
 9019:              '<br />';
 9020:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
 9021:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
 9022:        return $result;
 9023:     } 
 9024: # Remember Question Titles
 9025: # FIXME: Possibly need delimiter other than ":"
 9026:     for (my $i=0;$i<$number;$i++) {
 9027:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
 9028:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
 9029:     }
 9030:     my $correct_count=0;
 9031:     my $student_count=0;
 9032:     my $unknown_count=0;
 9033: # Match answers with usernames
 9034: # FIXME: Possibly need delimiter other than ":"
 9035:     foreach my $id (keys(%responses)) {
 9036:        if ($correct_ids{$id}) {
 9037:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
 9038:           $correct_count++;
 9039:        } elsif ($clicker_ids{$id}) {
 9040:           if ($clicker_ids{$id}=~/\,/) {
 9041: # More than one user with the same clicker!
 9042:              $result.="</td>".&Apache::loncommon::end_data_table_row().
 9043:                            &Apache::loncommon::start_data_table_row()."<td>".
 9044:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
 9045:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 9046:                            "<select name='multi".$id."'>";
 9047:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
 9048:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
 9049:              }
 9050:              $result.='</select>';
 9051:              $unknown_count++;
 9052:           } else {
 9053: # Good: found one and only one user with the right clicker
 9054:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
 9055:              $student_count++;
 9056:           }
 9057:        } else {
 9058:           $result.="</td>".&Apache::loncommon::end_data_table_row().
 9059:                            &Apache::loncommon::start_data_table_row()."<td>".
 9060:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
 9061:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 9062:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
 9063:                    "\n".&mt("Domain").": ".
 9064:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
 9065:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,0,$id);
 9066:           $unknown_count++;
 9067:        }
 9068:     }
 9069:     $result.='<hr />'.
 9070:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
 9071:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
 9072:        if ($correct_count==0) {
 9073:           $errormsg.="Found no correct answers answers for grading!";
 9074:        } elsif ($correct_count>1) {
 9075:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
 9076:        }
 9077:     }
 9078:     if ($number<1) {
 9079:        $errormsg.="Found no questions.";
 9080:     }
 9081:     if ($errormsg) {
 9082:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
 9083:     } else {
 9084:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
 9085:     }
 9086:     $result.='</form></td>'.
 9087:              &Apache::loncommon::end_data_table_row().
 9088:              &Apache::loncommon::end_data_table();
 9089:     return $result;
 9090: }
 9091: 
 9092: sub iclicker_eval {
 9093:     my ($questiontitles,$responses)=@_;
 9094:     my $number=0;
 9095:     my $errormsg='';
 9096:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 9097:         my %components=&Apache::loncommon::record_sep($line);
 9098:         my @entries=map {$components{$_}} (sort(keys(%components)));
 9099: 	if ($entries[0] eq 'Question') {
 9100: 	    for (my $i=3;$i<$#entries;$i+=6) {
 9101: 		$$questiontitles[$number]=$entries[$i];
 9102: 		$number++;
 9103: 	    }
 9104: 	}
 9105: 	if ($entries[0]=~/^\#/) {
 9106: 	    my $id=$entries[0];
 9107: 	    my @idresponses;
 9108: 	    $id=~s/^[\#0]+//;
 9109: 	    for (my $i=0;$i<$number;$i++) {
 9110: 		my $idx=3+$i*6;
 9111:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
 9112: 		push(@idresponses,$entries[$idx]);
 9113: 	    }
 9114: 	    $$responses{$id}=join(',',@idresponses);
 9115: 	}
 9116:     }
 9117:     return ($errormsg,$number);
 9118: }
 9119: 
 9120: sub interwrite_eval {
 9121:     my ($questiontitles,$responses)=@_;
 9122:     my $number=0;
 9123:     my $errormsg='';
 9124:     my $skipline=1;
 9125:     my $questionnumber=0;
 9126:     my %idresponses=();
 9127:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 9128:         my %components=&Apache::loncommon::record_sep($line);
 9129:         my @entries=map {$components{$_}} (sort(keys(%components)));
 9130:         if ($entries[1] eq 'Time') { $skipline=0; next; }
 9131:         if ($entries[1] eq 'Response') { $skipline=1; }
 9132:         next if $skipline;
 9133:         if ($entries[0]!=$questionnumber) {
 9134:            $questionnumber=$entries[0];
 9135:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
 9136:            $number++;
 9137:         }
 9138:         my $id=$entries[4];
 9139:         $id=~s/^[\#0]+//;
 9140:         $id=~s/^v\d*\://i;
 9141:         $id=~s/[\-\:]//g;
 9142:         $idresponses{$id}[$number]=$entries[6];
 9143:     }
 9144:     foreach my $id (keys(%idresponses)) {
 9145:        $$responses{$id}=join(',',@{$idresponses{$id}});
 9146:        $$responses{$id}=~s/^\s*\,//;
 9147:     }
 9148:     return ($errormsg,$number);
 9149: }
 9150: 
 9151: sub assign_clicker_grades {
 9152:     my ($r,$symb)=@_;
 9153:     if (!$symb) {return '';}
 9154: # See which part we are saving to
 9155:     my $res_error;
 9156:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 9157:     if ($res_error) {
 9158:         return &navmap_errormsg();
 9159:     }
 9160: # FIXME: This should probably look for the first handgradeable part
 9161:     my $part=$$partlist[0];
 9162: # Start screen output
 9163:     my $result=&Apache::loncommon::start_data_table().
 9164:              &Apache::loncommon::start_data_table_header_row().
 9165:              '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
 9166:              &Apache::loncommon::end_data_table_header_row().
 9167:              &Apache::loncommon::start_data_table_row().'<td>';
 9168: # Get correct result
 9169: # FIXME: Possibly need delimiter other than ":"
 9170:     my @correct=();
 9171:     my $gradingmechanism=$env{'form.gradingmechanism'};
 9172:     my $number=$env{'form.number'};
 9173:     if ($gradingmechanism ne 'attendance') {
 9174:        foreach my $key (keys(%env)) {
 9175:           if ($key=~/^form\.correct\:/) {
 9176:              my @input=split(/\,/,$env{$key});
 9177:              for (my $i=0;$i<=$#input;$i++) {
 9178:                  if (($correct[$i]) && ($input[$i]) &&
 9179:                      ($correct[$i] ne $input[$i])) {
 9180:                     $result.='<br /><span class="LC_warning">'.
 9181:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
 9182:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
 9183:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
 9184:                     $correct[$i]=$input[$i];
 9185:                  }
 9186:              }
 9187:           }
 9188:        }
 9189:        for (my $i=0;$i<$number;$i++) {
 9190:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
 9191:              $result.='<br /><span class="LC_error">'.
 9192:                       &mt('No correct result given for question "[_1]"!',
 9193:                           $env{'form.question:'.$i}).'</span>';
 9194:           }
 9195:        }
 9196:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
 9197:     }
 9198: # Start grading
 9199:     my $pcorrect=$env{'form.pcorrect'};
 9200:     my $pincorrect=$env{'form.pincorrect'};
 9201:     my $storecount=0;
 9202:     my %users=();
 9203:     foreach my $key (keys(%env)) {
 9204:        my $user='';
 9205:        if ($key=~/^form\.student\:(.*)$/) {
 9206:           $user=$1;
 9207:        }
 9208:        if ($key=~/^form\.unknown\:(.*)$/) {
 9209:           my $id=$1;
 9210:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
 9211:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
 9212:           } elsif ($env{'form.multi'.$id}) {
 9213:              $user=$env{'form.multi'.$id};
 9214:           }
 9215:        }
 9216:        if ($user) {
 9217:           if ($users{$user}) {
 9218:              $result.='<br /><span class="LC_warning">'.
 9219:                       &mt("More than one entry found for <tt>[_1]</tt>!",$user).
 9220:                       '</span><br />';
 9221:           }
 9222:           $users{$user}=1; 
 9223:           my @answer=split(/\,/,$env{$key});
 9224:           my $sum=0;
 9225:           my $realnumber=$number;
 9226:           for (my $i=0;$i<$number;$i++) {
 9227:              if  ($correct[$i] eq '-') {
 9228:                 $realnumber--;
 9229:              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/))  {
 9230:                 if ($gradingmechanism eq 'attendance') {
 9231:                    $sum+=$pcorrect;
 9232:                 } elsif ($correct[$i] eq '*') {
 9233:                    $sum+=$pcorrect;
 9234:                 } else {
 9235: # We actually grade if correct or not
 9236:                    my $increment=$pincorrect;
 9237: # Special case: numerical answer "0"
 9238:                    if ($correct[$i] eq '0') {
 9239:                       if ($answer[$i]=~/^[0\.]+$/) {
 9240:                          $increment=$pcorrect;
 9241:                       }
 9242: # General numerical answer, both evaluate to something non-zero
 9243:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
 9244:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
 9245:                          $increment=$pcorrect;
 9246:                       }
 9247: # Must be just alphanumeric
 9248:                    } elsif ($answer[$i] eq $correct[$i]) {
 9249:                       $increment=$pcorrect;
 9250:                    }
 9251:                    $sum+=$increment;
 9252:                 }
 9253:              }
 9254:           }
 9255:           my $ave=$sum/(100*$realnumber);
 9256: # Store
 9257:           my ($username,$domain)=split(/\:/,$user);
 9258:           my %grades=();
 9259:           $grades{"resource.$part.solved"}='correct_by_override';
 9260:           $grades{"resource.$part.awarded"}=$ave;
 9261:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 9262:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
 9263:                                                  $env{'request.course.id'},
 9264:                                                  $domain,$username);
 9265:           if ($returncode ne 'ok') {
 9266:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
 9267:           } else {
 9268:              $storecount++;
 9269:           }
 9270:        }
 9271:     }
 9272: # We are done
 9273:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
 9274:              '</td>'.
 9275:              &Apache::loncommon::end_data_table_row().
 9276:              &Apache::loncommon::end_data_table();
 9277:     return $result;
 9278: }
 9279: 
 9280: sub navmap_errormsg {
 9281:     return '<div class="LC_error">'.
 9282:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
 9283:            &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>').
 9284:            '</div>';
 9285: }
 9286: 
 9287: sub startpage {
 9288:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag) = @_;
 9289:     unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
 9290:     $r->print(&Apache::loncommon::start_page('Grading',undef,
 9291:                                           {'bread_crumbs' => $crumbs}));
 9292:     &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
 9293:     unless ($nodisplayflag) {
 9294:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag));
 9295:     }
 9296: }
 9297: 
 9298: sub select_problem {
 9299:     my ($r)=@_;
 9300:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
 9301:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1));
 9302:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
 9303:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
 9304: }
 9305: 
 9306: sub handler {
 9307:     my $request=$_[0];
 9308:     &reset_caches();
 9309:     if ($request->header_only) {
 9310:         &Apache::loncommon::content_type($request,'text/html');
 9311:         $request->send_http_header;
 9312:         return OK;
 9313:     }
 9314:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
 9315: 
 9316:     &init_perm();
 9317:     if (!$env{'request.course.id'}) {
 9318:         # Not in a course.
 9319:         $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
 9320:         return HTTP_NOT_ACCEPTABLE;
 9321:     } elsif (!%perm) {
 9322:         $request->internal_redirect('/adm/quickgrades');
 9323:     }
 9324:     &Apache::loncommon::content_type($request,'text/html');
 9325:     $request->send_http_header;
 9326: 
 9327: 
 9328: # see what command we need to execute
 9329: 
 9330:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
 9331:     my $command=$commands[0];
 9332: 
 9333:     if ($#commands > 0) {
 9334: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
 9335:     }
 9336: 
 9337: # see what the symb is
 9338: 
 9339:     my $symb=$env{'form.symb'};
 9340:     unless ($symb) {
 9341:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
 9342:        $symb=&Apache::lonnet::symbread($url);
 9343:     }
 9344:     &Apache::lonenc::check_decrypt(\$symb);
 9345: 
 9346:     $ssi_error = 0;
 9347:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
 9348: #
 9349: # Not called from a resource, but inside a course
 9350: #    
 9351:         &startpage($request,undef,[],1,1);
 9352:         &select_problem($request);
 9353:     } else {
 9354: 	if ($command eq 'submission' && $perm{'vgr'}) {
 9355:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}]);
 9356: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
 9357: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
 9358:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
 9359:                                        {href=>'',text=>'Select student'}],1,1);
 9360: 	    &pickStudentPage($request,$symb);
 9361: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
 9362:             &startpage($request,$symb,
 9363:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
 9364:                                        {href=>'',text=>'Select student'},
 9365:                                        {href=>'',text=>'Grade student'}],1,1);
 9366: 	    &displayPage($request,$symb);
 9367: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
 9368:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
 9369:                                        {href=>'',text=>'Select student'},
 9370:                                        {href=>'',text=>'Grade student'},
 9371:                                        {href=>'',text=>'Store grades'}],1,1);
 9372: 	    &updateGradeByPage($request,$symb);
 9373: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
 9374:             &startpage($request,$symb,[{href=>'',text=>'...'},
 9375:                                        {href=>'',text=>'Modify grades'}]);
 9376: 	    &processGroup($request,$symb);
 9377: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
 9378:             &startpage($request,$symb);
 9379: 	    $request->print(&grading_menu($request,$symb));
 9380: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
 9381:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
 9382: 	    $request->print(&submit_options($request,$symb));
 9383:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
 9384:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}]);
 9385:             $request->print(&listStudents($request,$symb,'graded'));
 9386:         } elsif ($command eq 'table' && $perm{'vgr'}) {
 9387:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
 9388:             $request->print(&submit_options_table($request,$symb));
 9389:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
 9390:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
 9391:             $request->print(&submit_options_sequence($request,$symb));
 9392: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
 9393:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
 9394: 	    $request->print(&viewgrades($request,$symb));
 9395: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
 9396:             &startpage($request,$symb,[{href=>'',text=>'...'},
 9397:                                        {href=>'',text=>'Store grades'}]);
 9398: 	    $request->print(&processHandGrade($request,$symb));
 9399: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
 9400:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
 9401:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
 9402:                                                                              text=>"Modify grades"},
 9403:                                        {href=>'', text=>"Store grades"}]);
 9404: 	    $request->print(&editgrades($request,$symb));
 9405:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
 9406:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
 9407:             $request->print(&initialverifyreceipt($request,$symb));
 9408: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
 9409:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
 9410:                                        {href=>'',text=>'Verification Result'}]);
 9411: 	    $request->print(&verifyreceipt($request,$symb));
 9412:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
 9413:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
 9414:             $request->print(&process_clicker($request,$symb));
 9415:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
 9416:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
 9417:                                        {href=>'', text=>'Process clicker file'}]);
 9418:             $request->print(&process_clicker_file($request,$symb));
 9419:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
 9420:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
 9421:                                        {href=>'', text=>'Process clicker file'},
 9422:                                        {href=>'', text=>'Store grades'}]);
 9423:             $request->print(&assign_clicker_grades($request,$symb));
 9424: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
 9425:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
 9426: 	    $request->print(&upcsvScores_form($request,$symb));
 9427: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
 9428:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
 9429: 	    $request->print(&csvupload($request,$symb));
 9430: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
 9431:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
 9432: 	    $request->print(&csvuploadmap($request,$symb));
 9433: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
 9434: 	    if ($env{'form.associate'} ne 'Reverse Association') {
 9435:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
 9436: 		$request->print(&csvuploadoptions($request,$symb));
 9437: 	    } else {
 9438: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
 9439: 		    $env{'form.upfile_associate'} = 'reverse';
 9440: 		} else {
 9441: 		    $env{'form.upfile_associate'} = 'forward';
 9442: 		}
 9443:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
 9444: 		$request->print(&csvuploadmap($request,$symb));
 9445: 	    }
 9446: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
 9447:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
 9448: 	    $request->print(&csvuploadassign($request,$symb));
 9449: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
 9450:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9451: 	    $request->print(&scantron_selectphase($request,undef,$symb));
 9452:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
 9453:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9454:  	    $request->print(&scantron_do_warning($request,$symb));
 9455: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
 9456:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9457: 	    $request->print(&scantron_validate_file($request,$symb));
 9458: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
 9459:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9460: 	    $request->print(&scantron_process_students($request,$symb));
 9461:  	} elsif ($command eq 'scantronupload' && 
 9462:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9463: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9464:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9465:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
 9466:  	} elsif ($command eq 'scantronupload_save' &&
 9467:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9468: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9469:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9470:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
 9471:  	} elsif ($command eq 'scantron_download' &&
 9472: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 9473:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9474:  	    $request->print(&scantron_download_scantron_data($request,$symb));
 9475:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
 9476:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9477:             $request->print(&checkscantron_results($request,$symb));
 9478:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
 9479:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}]);
 9480:             $request->print(&submit_options_download($request,$symb));
 9481:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
 9482:             &startpage($request,$symb,
 9483:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
 9484:     {href=>'', text=>'Download submissions'}]);
 9485:             &submit_download_link($request,$symb);
 9486: 	} elsif ($command) {
 9487:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
 9488: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
 9489: 	}
 9490:     }
 9491:     if ($ssi_error) {
 9492: 	&ssi_print_error($request);
 9493:     }
 9494:     &Apache::lonquickgrades::endGradeScreen($request);
 9495:     $request->print(&Apache::loncommon::end_page());
 9496:     &reset_caches();
 9497:     return OK;
 9498: }
 9499: 
 9500: 1;
 9501: 
 9502: __END__;
 9503: 
 9504: 
 9505: =head1 NAME
 9506: 
 9507: Apache::grades
 9508: 
 9509: =head1 SYNOPSIS
 9510: 
 9511: Handles the viewing of grades.
 9512: 
 9513: This is part of the LearningOnline Network with CAPA project
 9514: described at http://www.lon-capa.org.
 9515: 
 9516: =head1 OVERVIEW
 9517: 
 9518: Do an ssi with retries:
 9519: While I'd love to factor out this with the vesrion in lonprintout,
 9520: 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
 9521: I'm not quite ready to invent (e.g. an ssi_with_retry object).
 9522: 
 9523: At least the logic that drives this has been pulled out into loncommon.
 9524: 
 9525: 
 9526: 
 9527: ssi_with_retries - Does the server side include of a resource.
 9528:                      if the ssi call returns an error we'll retry it up to
 9529:                      the number of times requested by the caller.
 9530:                      If we still have a proble, no text is appended to the
 9531:                      output and we set some global variables.
 9532:                      to indicate to the caller an SSI error occurred.  
 9533:                      All of this is supposed to deal with the issues described
 9534:                      in LonCAPA BZ 5631 see:
 9535:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
 9536:                      by informing the user that this happened.
 9537: 
 9538: Parameters:
 9539:   resource   - The resource to include.  This is passed directly, without
 9540:                interpretation to lonnet::ssi.
 9541:   form       - The form hash parameters that guide the interpretation of the resource
 9542:                
 9543:   retries    - Number of retries allowed before giving up completely.
 9544: Returns:
 9545:   On success, returns the rendered resource identified by the resource parameter.
 9546: Side Effects:
 9547:   The following global variables can be set:
 9548:    ssi_error                - If an unrecoverable error occurred this becomes true.
 9549:                               It is up to the caller to initialize this to false
 9550:                               if desired.
 9551:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
 9552:                               of the resource that could not be rendered by the ssi
 9553:                               call.
 9554:    ssi_error_message   - The error string fetched from the ssi response
 9555:                               in the event of an error.
 9556: 
 9557: 
 9558: =head1 HANDLER SUBROUTINE
 9559: 
 9560: ssi_with_retries()
 9561: 
 9562: =head1 SUBROUTINES
 9563: 
 9564: =over
 9565: 
 9566: =item scantron_get_correction() : 
 9567: 
 9568:    Builds the interface screen to interact with the operator to fix a
 9569:    specific error condition in a specific scanline
 9570: 
 9571:  Arguments:
 9572:     $r           - Apache request object
 9573:     $i           - number of the current scanline
 9574:     $scan_record - hash ref as returned from &scantron_parse_scanline()
 9575:     $scan_config - hash ref as returned from &get_scantron_config()
 9576:     $line        - full contents of the current scanline
 9577:     $error       - error condition, valid values are
 9578:                    'incorrectCODE', 'duplicateCODE',
 9579:                    'doublebubble', 'missingbubble',
 9580:                    'duplicateID', 'incorrectID'
 9581:     $arg         - extra information needed
 9582:        For errors:
 9583:          - duplicateID   - paper number that this studentID was seen before on
 9584:          - duplicateCODE - array ref of the paper numbers this CODE was
 9585:                            seen on before
 9586:          - incorrectCODE - current incorrect CODE 
 9587:          - doublebubble  - array ref of the bubble lines that have double
 9588:                            bubble errors
 9589:          - missingbubble - array ref of the bubble lines that have missing
 9590:                            bubble errors
 9591: 
 9592: =item  scantron_get_maxbubble() : 
 9593: 
 9594:    Arguments:
 9595:        $nav_error  - Reference to scalar which is a flag to indicate a
 9596:                       failure to retrieve a navmap object.
 9597:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
 9598:        calling routine should trap the error condition and display the warning
 9599:        found in &navmap_errormsg().
 9600: 
 9601:        $scantron_config - Reference to bubblesheet format configuration hash.
 9602: 
 9603:    Returns the maximum number of bubble lines that are expected to
 9604:    occur. Does this by walking the selected sequence rendering the
 9605:    resource and then checking &Apache::lonxml::get_problem_counter()
 9606:    for what the current value of the problem counter is.
 9607: 
 9608:    Caches the results to $env{'form.scantron_maxbubble'},
 9609:    $env{'form.scantron.bubble_lines.n'}, 
 9610:    $env{'form.scantron.first_bubble_line.n'} and
 9611:    $env{"form.scantron.sub_bubblelines.n"}
 9612:    which are the total number of bubble, lines, the number of bubble
 9613:    lines for response n and number of the first bubble line for response n,
 9614:    and a comma separated list of numbers of bubble lines for sub-questions
 9615:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
 9616: 
 9617: 
 9618: =item  scantron_validate_missingbubbles() : 
 9619: 
 9620:    Validates all scanlines in the selected file to not have any
 9621:     answers that don't have bubbles that have not been verified
 9622:     to be bubble free.
 9623: 
 9624: =item  scantron_process_students() : 
 9625: 
 9626:    Routine that does the actual grading of the bubble sheet information.
 9627: 
 9628:    The parsed scanline hash is added to %env 
 9629: 
 9630:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
 9631:    foreach resource , with the form data of
 9632: 
 9633: 	'submitted'     =>'scantron' 
 9634: 	'grade_target'  =>'grade',
 9635: 	'grade_username'=> username of student
 9636: 	'grade_domain'  => domain of student
 9637: 	'grade_courseid'=> of course
 9638: 	'grade_symb'    => symb of resource to grade
 9639: 
 9640:     This triggers a grading pass. The problem grading code takes care
 9641:     of converting the bubbled letter information (now in %env) into a
 9642:     valid submission.
 9643: 
 9644: =item  scantron_upload_scantron_data() :
 9645: 
 9646:     Creates the screen for adding a new bubble sheet data file to a course.
 9647: 
 9648: =item  scantron_upload_scantron_data_save() : 
 9649: 
 9650:    Adds a provided bubble information data file to the course if user
 9651:    has the correct privileges to do so. 
 9652: 
 9653: =item  valid_file() :
 9654: 
 9655:    Validates that the requested bubble data file exists in the course.
 9656: 
 9657: =item  scantron_download_scantron_data() : 
 9658: 
 9659:    Shows a list of the three internal files (original, corrected,
 9660:    skipped) for a specific bubble sheet data file that exists in the
 9661:    course.
 9662: 
 9663: =item  scantron_validate_ID() : 
 9664: 
 9665:    Validates all scanlines in the selected file to not have any
 9666:    invalid or underspecified student/employee IDs
 9667: 
 9668: =item navmap_errormsg() :
 9669: 
 9670:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
 9671:    Should be called whenever the request to instantiate a navmap object fails.  
 9672: 
 9673: =back
 9674: 
 9675: =cut

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