File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.656: download - view: text, annotated - select for diffs
Sun Oct 9 16:23:34 2011 UTC (12 years, 6 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.656 2011/10/09 16:23:34 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:                 type => 'Type',
 1418:                 subj => 'Subject',
 1419:                 mesa => 'Message',
 1420:                 new  => 'New',
 1421:                 save => 'Save',
 1422:                 canc => 'Cancel',
 1423:                 kehi => 'Keyword Highlight Options',
 1424:                 txtc => 'Text Color',
 1425:                 font => 'Font Size',
 1426:                 fnst => 'Font Style',
 1427:              );
 1428:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1429: 
 1430: //===================== Show list of keywords ====================
 1431:   function keywords(formname) {
 1432:     var nret = prompt("$lt{'keyw'}",formname.keywords.value);
 1433:     if (nret==null) return;
 1434:     formname.keywords.value = nret;
 1435: 
 1436:     if (formname.keywords.value != "") {
 1437: 	formname.refresh.value = "on";
 1438: 	formname.submit();
 1439:     }
 1440:     return;
 1441:   }
 1442: 
 1443: //===================== Script to view submitted by ==================
 1444:   function viewSubmitter(submitter) {
 1445:     document.SCORE.refresh.value = "on";
 1446:     document.SCORE.NCT.value = "1";
 1447:     document.SCORE.unamedom0.value = submitter;
 1448:     document.SCORE.submit();
 1449:     return;
 1450:   }
 1451: 
 1452: //===================== Script to add keyword(s) ==================
 1453:   function getSel() {
 1454:     if (document.getSelection) txt = document.getSelection();
 1455:     else if (document.selection) txt = document.selection.createRange().text;
 1456:     else return;
 1457:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1458:     if (cleantxt=="") {
 1459: 	alert("$lt{'plse'}");
 1460: 	return;
 1461:     }
 1462:     var nret = prompt("$lt{'adds'}",cleantxt);
 1463:     if (nret==null) return;
 1464:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1465:     if (document.SCORE.keywords.value != "") {
 1466: 	document.SCORE.refresh.value = "on";
 1467: 	document.SCORE.submit();
 1468:     }
 1469:     return;
 1470:   }
 1471: 
 1472: //====================== Script for composing message ==============
 1473:    // preload images
 1474:    img1 = new Image();
 1475:    img1.src = "$iconpath/mailbkgrd.gif";
 1476:    img2 = new Image();
 1477:    img2.src = "$iconpath/mailto.gif";
 1478: 
 1479:   function msgCenter(msgform,usrctr,fullname) {
 1480:     var Nmsg  = msgform.savemsgN.value;
 1481:     savedMsgHeader(Nmsg,usrctr,fullname);
 1482:     var subject = msgform.msgsub.value;
 1483:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1484:     re = /msgsub/;
 1485:     var shwsel = "";
 1486:     if (re.test(msgchk)) { shwsel = "checked" }
 1487:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1488:     displaySubject(checkEntities(subject),shwsel);
 1489:     for (var i=1; i<=Nmsg; i++) {
 1490: 	var testmsg = "savemsg"+i+",";
 1491: 	re = new RegExp(testmsg,"g");
 1492: 	shwsel = "";
 1493: 	if (re.test(msgchk)) { shwsel = "checked" }
 1494: 	var message = document.SCORE["savemsg"+i].value;
 1495: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1496: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1497: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1498:     }
 1499:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1500:     shwsel = "";
 1501:     re = /newmsg/;
 1502:     if (re.test(msgchk)) { shwsel = "checked" }
 1503:     newMsg(newmsg,shwsel);
 1504:     msgTail(); 
 1505:     return;
 1506:   }
 1507: 
 1508:   function checkEntities(strx) {
 1509:     if (strx.length == 0) return strx;
 1510:     var orgStr = ["&", "<", ">", '"']; 
 1511:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1512:     var counter = 0;
 1513:     while (counter < 4) {
 1514: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1515: 	counter++;
 1516:     }
 1517:     return strx;
 1518:   }
 1519: 
 1520:   function strReplace(strx, orgStr, newStr) {
 1521:     return strx.split(orgStr).join(newStr);
 1522:   }
 1523: 
 1524:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1525:     var height = 70*Nmsg+250;
 1526:     var scrollbar = "no";
 1527:     if (height > 600) {
 1528: 	height = 600;
 1529: 	scrollbar = "yes";
 1530:     }
 1531:     var xpos = (screen.width-600)/2;
 1532:     xpos = (xpos < 0) ? '0' : xpos;
 1533:     var ypos = (screen.height-height)/2-30;
 1534:     ypos = (ypos < 0) ? '0' : ypos;
 1535: 
 1536:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
 1537:     pWin.focus();
 1538:     pDoc = pWin.document;
 1539:     pDoc.$docopen;
 1540:     pDoc.write('$start_page_msg_central');
 1541: 
 1542:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1543:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1544:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;$lt{'comp'}\"+fullname+\"<\\/span><\\/h3><br /><br />");
 1545: 
 1546:     pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
 1547:     pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
 1548:     pDoc.write("<td><b>$lt{'type'}<\\/b><\\/td><td><b>$lt{'incl'}<\\/b><\\/td><td><b>$lt{'mesa'}<\\/td><\\/tr>");
 1549: }
 1550:     function displaySubject(msg,shwsel) {
 1551:     pDoc = pWin.document;
 1552:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1553:     pDoc.write("<td>$lt{'subj'}<\\/td>");
 1554:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1555:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
 1556: }
 1557: 
 1558:   function displaySavedMsg(ctr,msg,shwsel) {
 1559:     pDoc = pWin.document;
 1560:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1561:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
 1562:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1563:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
 1564: }
 1565: 
 1566:   function newMsg(newmsg,shwsel) {
 1567:     pDoc = pWin.document;
 1568:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1569:     pDoc.write("<td align=\\"center\\">$lt{'new'}<\\/td>");
 1570:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1571:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
 1572: }
 1573: 
 1574:   function msgTail() {
 1575:     pDoc = pWin.document;
 1576:     pDoc.write("<\\/table>");
 1577:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1578:     pDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1579:     pDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
 1580:     pDoc.write("<\\/form>");
 1581:     pDoc.write('$end_page_msg_central');
 1582:     pDoc.close();
 1583: }
 1584: 
 1585: //====================== Script for keyword highlight options ==============
 1586:   function kwhighlight() {
 1587:     var kwclr    = document.SCORE.kwclr.value;
 1588:     var kwsize   = document.SCORE.kwsize.value;
 1589:     var kwstyle  = document.SCORE.kwstyle.value;
 1590:     var redsel = "";
 1591:     var grnsel = "";
 1592:     var blusel = "";
 1593:     if (kwclr=="red")   {var redsel="checked"};
 1594:     if (kwclr=="green") {var grnsel="checked"};
 1595:     if (kwclr=="blue")  {var blusel="checked"};
 1596:     var sznsel = "";
 1597:     var sz1sel = "";
 1598:     var sz2sel = "";
 1599:     if (kwsize=="0")  {var sznsel="checked"};
 1600:     if (kwsize=="+1") {var sz1sel="checked"};
 1601:     if (kwsize=="+2") {var sz2sel="checked"};
 1602:     var synsel = "";
 1603:     var syisel = "";
 1604:     var sybsel = "";
 1605:     if (kwstyle=="")    {var synsel="checked"};
 1606:     if (kwstyle=="<i>") {var syisel="checked"};
 1607:     if (kwstyle=="<b>") {var sybsel="checked"};
 1608:     highlightCentral();
 1609:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
 1610:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
 1611:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
 1612:     highlightend();
 1613:     return;
 1614:   }
 1615: 
 1616:   function highlightCentral() {
 1617: //    if (window.hwdWin) window.hwdWin.close();
 1618:     var xpos = (screen.width-400)/2;
 1619:     xpos = (xpos < 0) ? '0' : xpos;
 1620:     var ypos = (screen.height-330)/2-30;
 1621:     ypos = (ypos < 0) ? '0' : ypos;
 1622: 
 1623:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1624:     hwdWin.focus();
 1625:     var hDoc = hwdWin.document;
 1626:     hDoc.$docopen;
 1627:     hDoc.write('$start_page_highlight_central');
 1628:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1629:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;$lt{'kehi'}<\\/span><\\/h3><br /><br />");
 1630: 
 1631:     hDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
 1632:     hDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
 1633:     hDoc.write("<td><b>$lt{'txtc'}<\\/b><\\/td><td><b>$lt{'font'}<\\/b><\\/td><td><b>$lt{'fnst'}<\\/td><\\/tr>");
 1634:   }
 1635: 
 1636:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1637:     var hDoc = hwdWin.document;
 1638:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1639:     hDoc.write("<td align=\\"left\\">");
 1640:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
 1641:     hDoc.write("<td align=\\"left\\">");
 1642:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
 1643:     hDoc.write("<td align=\\"left\\">");
 1644:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
 1645:     hDoc.write("<\\/tr>");
 1646:   }
 1647: 
 1648:   function highlightend() { 
 1649:     var hDoc = hwdWin.document;
 1650:     hDoc.write("<\\/table>");
 1651:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1652:     hDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
 1653:     hDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
 1654:     hDoc.write("<\\/form>");
 1655:     hDoc.write('$end_page_highlight_central');
 1656:     hDoc.close();
 1657:   }
 1658: 
 1659: SUBJAVASCRIPT
 1660: }
 1661: 
 1662: sub get_increment {
 1663:     my $increment = $env{'form.increment'};
 1664:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1665:         $increment != .1) {
 1666:         $increment = 1;
 1667:     }
 1668:     return $increment;
 1669: }
 1670: 
 1671: sub gradeBox_start {
 1672:     return (
 1673:         &Apache::loncommon::start_data_table()
 1674:        .&Apache::loncommon::start_data_table_header_row()
 1675:        .'<th>'.&mt('Part').'</th>'
 1676:        .'<th>'.&mt('Points').'</th>'
 1677:        .'<th>&nbsp;</th>'
 1678:        .'<th>'.&mt('Assign Grade').'</th>'
 1679:        .'<th>'.&mt('Weight').'</th>'
 1680:        .'<th>'.&mt('Grade Status').'</th>'
 1681:        .&Apache::loncommon::end_data_table_header_row()
 1682:     );
 1683: }
 1684: 
 1685: sub gradeBox_end {
 1686:     return (
 1687:         &Apache::loncommon::end_data_table()
 1688:     );
 1689: }
 1690: #--- displays the grading box, used in essay type problem and grading by page/sequence
 1691: sub gradeBox {
 1692:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 1693:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1694: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 1695:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 1696:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
 1697:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
 1698:     $wgt       = ($wgt > 0 ? $wgt : '1');
 1699:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 1700: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 1701:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 1702:     my $display_part= &get_display_part($partid,$symb);
 1703:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 1704: 				       [$partid]);
 1705:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 1706:     if ($last_resets{$partid}) {
 1707:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 1708:     }
 1709:     $result.=&Apache::loncommon::start_data_table_row();
 1710:     my $ctr = 0;
 1711:     my $thisweight = 0;
 1712:     my $increment = &get_increment();
 1713: 
 1714:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 1715:     while ($thisweight<=$wgt) {
 1716: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 1717:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 1718: 	    $thisweight.')" value="'.$thisweight.'" '.
 1719: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 1720: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 1721:         $thisweight += $increment;
 1722: 	$ctr++;
 1723:     }
 1724:     $radio.='</tr></table>';
 1725: 
 1726:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 1727: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 1728: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 1729: 	$wgt.')" /></td>'."\n";
 1730:     $line.='<td>/'.$wgt.' '.$wgtmsg.
 1731: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 1732: 	' </td>'."\n";
 1733:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
 1734: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 1735:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 1736: 	$line.='<option></option>'.
 1737: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
 1738:     } else {
 1739: 	$line.='<option selected="selected"></option>'.
 1740: 	    '<option value="excused" >'.&mt('excused').'</option>';
 1741:     }
 1742:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
 1743: 
 1744: 
 1745:     $result .= 
 1746: 	    '<td>'.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
 1747:     $result.=&Apache::loncommon::end_data_table_row();
 1748:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 1749: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 1750: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 1751: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 1752:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 1753:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 1754:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 1755:         $aggtries.'" />'."\n";
 1756:     my $res_error;
 1757:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
 1758:     if ($res_error) {
 1759:         return &navmap_errormsg();
 1760:     }
 1761:     return $result;
 1762: }
 1763: 
 1764: sub handback_box {
 1765:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
 1766:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error_pointer);
 1767:     my (@respids);
 1768:     my @part_response_id = &flatten_responseType($responseType);
 1769:     foreach my $part_response_id (@part_response_id) {
 1770:     	my ($part,$resp) = @{ $part_response_id };
 1771:         if ($part eq $partid) {
 1772:             push(@respids,$resp);
 1773:         }
 1774:     }
 1775:     my $result;
 1776:     foreach my $respid (@respids) {
 1777: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 1778: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 1779: 	next if (!@$files);
 1780: 	my $file_counter = 0;
 1781: 	foreach my $file (@$files) {
 1782: 	    if ($file =~ /\/portfolio\//) {
 1783:                 $file_counter++;
 1784:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 1785:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
 1786:     	        $file_disp = "$name.$ext";
 1787:     	        $file = $file_path.$file_disp;
 1788:     	        $result.=&mt('Return commented version of [_1] to student.',
 1789:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 1790:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 1791:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
 1792: 	    }
 1793: 	}
 1794:         if ($file_counter) {
 1795:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
 1796:                        '<span class="LC_info">'.
 1797:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
 1798:         }
 1799:     }
 1800:     return $result;    
 1801: }
 1802: 
 1803: sub show_problem {
 1804:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 1805:     my $rendered;
 1806:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 1807:     &Apache::lonxml::remember_problem_counter();
 1808:     if ($mode eq 'both' or $mode eq 'text') {
 1809: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 1810: 						       $env{'request.course.id'},
 1811: 						       undef,\%form);
 1812:     }
 1813:     if ($removeform) {
 1814: 	$rendered=~s|<form(.*?)>||g;
 1815: 	$rendered=~s|</form>||g;
 1816: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 1817:     }
 1818:     my $companswer;
 1819:     if ($mode eq 'both' or $mode eq 'answer') {
 1820: 	&Apache::lonxml::restore_problem_counter();
 1821: 	$companswer=
 1822: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 1823: 						    $env{'request.course.id'},
 1824: 						    %form);
 1825:     }
 1826:     if ($removeform) {
 1827: 	$companswer=~s|<form(.*?)>||g;
 1828: 	$companswer=~s|</form>||g;
 1829: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 1830:     }
 1831:     $rendered=
 1832:         '<div class="LC_Box">'
 1833:        .'<h3 class="LC_hcell">'.&mt('View of the problem').'</h3>'
 1834:        .$rendered
 1835:        .'</div>';
 1836:     $companswer=
 1837:         '<div class="LC_Box">'
 1838:        .'<h3 class="LC_hcell">'.&mt('Correct answer').'</h3>'
 1839:        .$companswer
 1840:        .'</div>';
 1841:     my $result;
 1842:     if ($mode eq 'both') {
 1843:         $result=$rendered.$companswer;
 1844:     } elsif ($mode eq 'text') {
 1845:         $result=$rendered;
 1846:     } elsif ($mode eq 'answer') {
 1847:         $result=$companswer;
 1848:     }
 1849:     return $result;
 1850: }
 1851: 
 1852: sub files_exist {
 1853:     my ($r, $symb) = @_;
 1854:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1855: 
 1856:     foreach my $student (@students) {
 1857:         my ($uname,$udom,$fullname) = split(/:/,$student);
 1858:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 1859: 					      $udom,$uname);
 1860:         my ($string,$timestamp)= &get_last_submission(\%record);
 1861:         foreach my $submission (@$string) {
 1862:             my ($partid,$respid) =
 1863: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 1864:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 1865: 					   \%record);
 1866:             return 1 if (@$files);
 1867:         }
 1868:     }
 1869:     return 0;
 1870: }
 1871: 
 1872: sub download_all_link {
 1873:     my ($r,$symb) = @_;
 1874:     unless (&files_exist($r, $symb)) {
 1875:        $r->print(&mt('There are currently no submitted documents.'));
 1876:        return;
 1877:     }
 1878: 
 1879:     my $all_students = 
 1880: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 1881: 
 1882:     my $parts =
 1883: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 1884: 
 1885:     my $identifier = &Apache::loncommon::get_cgi_id();
 1886:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 1887:                              'cgi.'.$identifier.'.symb' => $symb,
 1888:                              'cgi.'.$identifier.'.parts' => $parts,});
 1889:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 1890: 	      &mt('Download All Submitted Documents').'</a>');
 1891:     return;
 1892: }
 1893: 
 1894: sub submit_download_link {
 1895:     my ($request,$symb) = @_;
 1896:     if (!$symb) { return ''; }
 1897: #FIXME: Figure out which type of problem this is and provide appropriate download
 1898:     &download_all_link($request,$symb);
 1899: }
 1900: 
 1901: sub build_section_inputs {
 1902:     my $section_inputs;
 1903:     if ($env{'form.section'} eq '') {
 1904:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 1905:     } else {
 1906:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 1907:         foreach my $section (@sections) {
 1908:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 1909:         }
 1910:     }
 1911:     return $section_inputs;
 1912: }
 1913: 
 1914: # --------------------------- show submissions of a student, option to grade 
 1915: sub submission {
 1916:     my ($request,$counter,$total,$symb) = @_;
 1917:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 1918:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 1919:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 1920:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 1921: 
 1922:     my $probtitle=&Apache::lonnet::gettitle($symb); 
 1923:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 1924: 
 1925:     if (!&canview($usec)) {
 1926: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
 1927: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
 1928: 			$env{'request.course.id'}.')</span>');
 1929: 	return;
 1930:     }
 1931: 
 1932:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 1933:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 1934:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 1935:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 1936:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1937: 	'" src="'.$request->dir_config('lonIconsURL').
 1938: 	'/check.gif" height="16" border="0" />';
 1939: 
 1940:     my %old_essays;
 1941:     # header info
 1942:     if ($counter == 0) {
 1943: 	&sub_page_js($request);
 1944: 	&sub_page_kw_js($request);
 1945: 
 1946: 	# option to display problem, only once else it cause problems 
 1947:         # with the form later since the problem has a form.
 1948: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 1949: 	    my $mode;
 1950: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 1951: 		$mode='both';
 1952: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 1953: 		$mode='text';
 1954: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 1955: 		$mode='answer';
 1956: 	    }
 1957: 	    &Apache::lonxml::clear_problem_counter();
 1958: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 1959: 	}
 1960: 
 1961: 	# kwclr is the only variable that is guaranteed to be non blank 
 1962:         # if this subroutine has been called once.
 1963: 	my %keyhash = ();
 1964: #	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
 1965:         if (1) {
 1966: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 1967: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 1968: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 1969: 
 1970: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 1971: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 1972: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 1973: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 1974: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 1975: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
 1976: 		$keyhash{$symb.'_subject'} : $probtitle;
 1977: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 1978: 	}
 1979: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 1980: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 1981: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 1982: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 1983: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 1984: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 1985: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 1986: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 1987: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 1988: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 1989: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 1990: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 1991: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 1992: 			&build_section_inputs().
 1993: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 1994: 			'<input type="hidden" name="NCT"'.
 1995: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 1996: #	if ($env{'form.handgrade'} eq 'yes') {
 1997:         if (1) {
 1998: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 1999: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 2000: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 2001: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
 2002: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 2003: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 2004: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 2005: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
 2006: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
 2007: 	    }
 2008: 	}
 2009: 	
 2010: 	my ($cts,$prnmsg) = (1,'');
 2011: 	while ($cts <= $env{'form.savemsgN'}) {
 2012: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 2013: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 2014: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 2015: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 2016: 		'" />'."\n".
 2017: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 2018: 	    $cts++;
 2019: 	}
 2020: 	$request->print($prnmsg);
 2021: 
 2022: #	if ($env{'form.handgrade'} eq 'yes') {
 2023:         if (1) {
 2024: 
 2025:             my %lt = &Apache::lonlocal::texthash(
 2026:                           keyw => 'Keyword Options',
 2027:                           list => 'List',
 2028:                           past => 'Paste Selection to List',
 2029:                           high => 'Hightlight Attribute',
 2030:                      );    
 2031: #
 2032: # Print out the keyword options line
 2033: #
 2034: 	    $request->print(<<KEYWORDS);
 2035: <br /><b>$lt{'keyw'}:</b>&nbsp;
 2036: <a href="javascript:keywords(document.SCORE);" target="_self">$lt{'list'}</a>&nbsp; &nbsp;
 2037: <a href="#" onmousedown="javascript:getSel(); return false"
 2038:  CLASS="page">$lt{'past'}</a>&nbsp; &nbsp;
 2039: <a href="javascript:kwhighlight();" target="_self">$lt{'high'}</a><br /><br />
 2040: KEYWORDS
 2041: #
 2042: # Load the other essays for similarity check
 2043: #
 2044:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 2045: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 2046: 	    $apath=&escape($apath);
 2047: 	    $apath=~s/\W/\_/gs;
 2048: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
 2049:         }
 2050:     }
 2051: 
 2052: # This is where output for one specific student would start
 2053:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
 2054:     $request->print(
 2055:         "\n\n"
 2056:        .'<div class="LC_grade_show_user'.$add_class.'">'
 2057:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
 2058:        ."\n"
 2059:     );
 2060: 
 2061:     # Show additional functions if allowed
 2062:     if ($perm{'vgr'}) {
 2063:         $request->print(
 2064:             &Apache::loncommon::track_student_link(
 2065:                 &mt('View recent activity'),
 2066:                 $uname,$udom,'check')
 2067:            .' '
 2068:         );
 2069:     }
 2070:     if ($perm{'opa'}) {
 2071:         $request->print(
 2072:             &Apache::loncommon::pprmlink(
 2073:                 &mt('Set/Change parameters'),
 2074:                 $uname,$udom,$symb,'check'));
 2075:     }
 2076: 
 2077:     # Show Problem
 2078:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2079: 	my $mode;
 2080: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2081: 	    $mode='both';
 2082: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2083: 	    $mode='text';
 2084: 	} elsif ($env{'form.vAns'} eq 'all') {
 2085: 	    $mode='answer';
 2086: 	}
 2087: 	&Apache::lonxml::clear_problem_counter();
 2088: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2089:     }
 2090: 
 2091:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2092:     my $res_error;
 2093:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2094:     if ($res_error) {
 2095:         $request->print(&navmap_errormsg());
 2096:         return;
 2097:     }
 2098: 
 2099:     # Display student info
 2100:     $request->print(($counter == 0 ? '' : '<br />'));
 2101: 
 2102:     my $result='<div class="LC_Box">'
 2103:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
 2104:     $result.='<input type="hidden" name="name'.$counter.
 2105:              '" value="'.$env{'form.fullname'}.'" />'."\n";
 2106: #    if ($env{'form.handgrade'} eq 'no') {
 2107:     if (1) {
 2108:         $result.='<p class="LC_info">'
 2109:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
 2110:                 ."</p>\n";
 2111:     }
 2112: 
 2113:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
 2114:     my $fullname;
 2115:     my $col_fullnames = [];
 2116: #    if ($env{'form.handgrade'} eq 'yes') {
 2117:     if (1) {
 2118: 	(my $sub_result,$fullname,$col_fullnames)=
 2119: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2120: 				 $counter);
 2121: 	$result.=$sub_result;
 2122:     }
 2123:     $request->print($result."\n");
 2124: 
 2125:     # print student answer/submission
 2126:     # Options are (1) Handgraded submission only
 2127:     #             (2) Last submission, includes submission that is not handgraded 
 2128:     #                  (for multi-response type part)
 2129:     #             (3) Last submission plus the parts info
 2130:     #             (4) The whole record for this student
 2131:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
 2132: 	my ($string,$timestamp)= &get_last_submission(\%record);
 2133: 	
 2134: 	my $lastsubonly;
 2135: 
 2136:         if ($$timestamp eq '') {
 2137:             $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
 2138:         } else {
 2139:             $lastsubonly =
 2140:                 '<div class="LC_grade_submissions_body">'
 2141:                .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
 2142: 
 2143: 	    my %seenparts;
 2144: 	    my @part_response_id = &flatten_responseType($responseType);
 2145: 	    foreach my $part (@part_response_id) {
 2146: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
 2147: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
 2148: 
 2149: 		my ($partid,$respid) = @{ $part };
 2150: 		my $display_part=&get_display_part($partid,$symb);
 2151: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2152: 		    if (exists($seenparts{$partid})) { next; }
 2153: 		    $seenparts{$partid}=1;
 2154: 		    my $submitby='<b>Part:</b> '.$display_part.
 2155: 			' <b>Collaborative submission by:</b> '.
 2156: 			'<a href="javascript:viewSubmitter(\''.
 2157: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
 2158: 			'\');" target="_self">'.
 2159: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
 2160: 		    $request->print($submitby);
 2161: 		    next;
 2162: 		}
 2163: 		my $responsetype = $responseType->{$partid}->{$respid};
 2164: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
 2165:                     $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
 2166:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2167:                         ' <span class="LC_internal_info">'.
 2168:                         '('.&mt('Response ID: [_1]',$respid).')'.
 2169:                         '</span>&nbsp; &nbsp;'.
 2170: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
 2171: 		    next;
 2172: 		}
 2173: 		foreach my $submission (@$string) {
 2174: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2175: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2176: 		    my ($ressub,$hide,$subval) = split(/:/,$submission,3);
 2177: 		    # Similarity check
 2178: 		    my $similar='';
 2179:                     my ($type,$trial,$rndseed);
 2180:                     if ($hide eq 'rand') {
 2181:                         $type = 'randomizetry';
 2182:                         $trial = $record{"resource.$partid.tries"};
 2183:                         $rndseed = $record{"resource.$partid.rndseed"};
 2184:                     }
 2185: 		    if($env{'form.checkPlag'}){
 2186: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2187: 			    &most_similar($uname,$udom,$subval,\%old_essays);
 2188: 			if ($osim) {
 2189: 			    $osim=int($osim*100.0);
 2190: 			    my %old_course_desc = 
 2191: 				&Apache::lonnet::coursedescription($ocrsid,
 2192: 								   {'one_time' => 1});
 2193: 
 2194:                             if ($hide eq 'anon') {
 2195:                                 $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
 2196:                                          &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
 2197:                             } else {
 2198: 			        $similar="<hr /><h3><span class=\"LC_warning\">".
 2199: 				    &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
 2200: 				        $osim,
 2201: 				        &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
 2202: 				        $old_course_desc{'description'},
 2203: 				        $old_course_desc{'num'},
 2204: 				        $old_course_desc{'domain'}).
 2205: 				    '</span></h3><blockquote><i>'.
 2206: 				    &keywords_highlight($oessay).
 2207: 				    '</i></blockquote><hr />';
 2208:                             }
 2209: 			}
 2210: 		    }
 2211: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom,
 2212:                                          undef,$type,$trial,$rndseed);
 2213: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
 2214: 			($env{'form.lastSub'} eq 'hdgrade' && 
 2215: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
 2216: 			my $display_part=&get_display_part($partid,$symb);
 2217:                         $lastsubonly.='<div class="LC_grade_submission_part">'.
 2218:                             '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2219:                             ' <span class="LC_internal_info">'.
 2220:                             '('.&mt('Response ID: [_1]',$respid).')'.
 2221:                             '</span>&nbsp; &nbsp;';
 2222: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2223: 			if (@$files) {
 2224:                             if ($hide eq 'anon') {
 2225:                                 $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
 2226:                             } else {
 2227:                                 $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
 2228:                                 foreach my $file (@$files) {
 2229:                                     &Apache::lonnet::allowuploaded('/adm/grades',$file);
 2230:                                     $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" /> '.$file.'</a>';
 2231:                                 }
 2232:                             }
 2233: 			    $lastsubonly.='<br />';
 2234: 			}
 2235:                         if ($hide eq 'anon') {
 2236:                             $lastsubonly.='<b>'.&mt('Anonymous Survey').'</b>'; 
 2237:                         } else {
 2238: 			    $lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
 2239: 			        &cleanRecord($subval,$responsetype,$symb,$partid,
 2240: 					     $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
 2241:                         }
 2242: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2243: 			$lastsubonly.='</div>';
 2244: 		    }
 2245: 		}
 2246: 	    }
 2247: 	    $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
 2248: 	}
 2249: 	$request->print($lastsubonly);
 2250:    } elsif ($env{'form.lastSub'} eq 'datesub') {
 2251:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2252: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2253:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2254: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2255: 								 $env{'request.course.id'},
 2256: 								 $last,'.submission',
 2257: 								 'Apache::grades::keywords_highlight'));
 2258:     }
 2259:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2260: 	.$udom.'" />'."\n");
 2261:     # return if view submission with no grading option
 2262:     if (!&canmodify($usec)) {
 2263: 	$request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
 2264: 	return;
 2265:     } else {
 2266: 	$request->print('</div>'."\n");
 2267:     }
 2268: 
 2269:     # essay grading message center
 2270: #    if ($env{'form.handgrade'} eq 'yes') {
 2271:     if (1) {
 2272: 	my $result='<div class="LC_grade_message_center">';
 2273:     
 2274: 	$result.='<div class="LC_grade_message_center_header">'.
 2275: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
 2276: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2277: 	my $msgfor = $givenn.' '.$lastname;
 2278: 	if (scalar(@$col_fullnames) > 0) {
 2279: 	    my $lastone = pop(@$col_fullnames);
 2280: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2281: 	}
 2282: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2283: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2284: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
 2285: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2286: 	    ',\''.$msgfor.'\');" target="_self">'.
 2287: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
 2288: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2289: 	    '<img src="'.$request->dir_config('lonIconsURL').
 2290: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
 2291: 	    '<br />&nbsp;('.
 2292: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
 2293: 	$result.='</div></div>';
 2294: 	$request->print($result);
 2295:     }
 2296: 
 2297:     my %seen = ();
 2298:     my @partlist;
 2299:     my @gradePartRespid;
 2300:     my @part_response_id = &flatten_responseType($responseType);
 2301:     $request->print(
 2302:         '<div class="LC_Box">'
 2303:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
 2304:     );
 2305:     $request->print(&gradeBox_start());
 2306:     foreach my $part_response_id (@part_response_id) {
 2307:     	my ($partid,$respid) = @{ $part_response_id };
 2308: 	my $part_resp = join('_',@{ $part_response_id });
 2309: 	next if ($seen{$partid} > 0);
 2310: 	$seen{$partid}++;
 2311: 	next if ($$handgrade{$part_resp} ne 'yes' 
 2312: 		 && $env{'form.lastSub'} eq 'hdgrade');
 2313: 	push(@partlist,$partid);
 2314: 	push(@gradePartRespid,$partid.'.'.$respid);
 2315: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2316:     }
 2317:     $request->print(&gradeBox_end()); # </div>
 2318:     $request->print('</div>');
 2319: 
 2320:     $request->print('<div class="LC_grade_info_links">');
 2321:     $request->print('</div>');
 2322: 
 2323:     $result='<input type="hidden" name="partlist'.$counter.
 2324: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2325:     $result.='<input type="hidden" name="gradePartRespid'.
 2326: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2327:     my $ctr = 0;
 2328:     while ($ctr < scalar(@partlist)) {
 2329: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2330: 	    $partlist[$ctr].'" />'."\n";
 2331: 	$ctr++;
 2332:     }
 2333:     $request->print($result.''."\n");
 2334: 
 2335: # Done with printing info for one student
 2336: 
 2337:     $request->print('</div>');#LC_grade_show_user
 2338: 
 2339: 
 2340:     # print end of form
 2341:     if ($counter == $total) {
 2342:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
 2343: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2344: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
 2345: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2346: 	my $ntstu ='<select name="NTSTU">'.
 2347: 	    '<option>1</option><option>2</option>'.
 2348: 	    '<option>3</option><option>5</option>'.
 2349: 	    '<option>7</option><option>10</option></select>'."\n";
 2350: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2351: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2352:         $endform.=&mt('[_1]student(s)',$ntstu);
 2353: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2354: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2355: 	    '<input type="button" value="'.&mt('Next').'" '.
 2356: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2357:         $endform.='<span class="LC_warning">'.
 2358:                   &mt('(Next and Previous (student) do not save the scores.)').
 2359:                   '</span>'."\n" ;
 2360:         $endform.="<input type='hidden' value='".&get_increment().
 2361:             "' name='increment' />";
 2362: 	$endform.='</td></tr></table></form>';
 2363: 	$request->print($endform);
 2364:     }
 2365:     return '';
 2366: }
 2367: 
 2368: sub check_collaborators {
 2369:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2370:     my ($result,@col_fullnames);
 2371:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2372:     foreach my $part (keys(%$handgrade)) {
 2373: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2374: 					'.maxcollaborators',
 2375: 					$symb,$udom,$uname);
 2376: 	next if ($ncol <= 0);
 2377: 	$part =~ s/\_/\./g;
 2378: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2379: 	my (@good_collaborators, @bad_collaborators);
 2380: 	foreach my $possible_collaborator
 2381: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2382: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2383: 	    next if ($possible_collaborator eq '');
 2384: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
 2385: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2386: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2387: 	    # Doing this grep allows 'fuzzy' specification
 2388: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2389: 			       keys(%$classlist));
 2390: 	    if (! scalar(@matches)) {
 2391: 		push(@bad_collaborators, $possible_collaborator);
 2392: 	    } else {
 2393: 		push(@good_collaborators, @matches);
 2394: 	    }
 2395: 	}
 2396: 	if (scalar(@good_collaborators) != 0) {
 2397: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
 2398: 	    foreach my $name (@good_collaborators) {
 2399: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2400: 		push(@col_fullnames, $givenn.' '.$lastname);
 2401: 		$result.='<li>'.$fullname->{$name}.'</li>';
 2402: 	    }
 2403: 	    $result.='</ol><br />'."\n";
 2404: 	    my ($part)=split(/\./,$part);
 2405: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2406: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2407: 		"\n";
 2408: 	}
 2409: 	if (scalar(@bad_collaborators) > 0) {
 2410: 	    $result.='<div class="LC_warning">';
 2411: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2412: 	    $result .= '</div>';
 2413: 	}         
 2414: 	if (scalar(@bad_collaborators > $ncol)) {
 2415: 	    $result .= '<div class="LC_warning">';
 2416: 	    $result .= &mt('This student has submitted too many '.
 2417: 		'collaborators.  Maximum is [_1].',$ncol);
 2418: 	    $result .= '</div>';
 2419: 	}
 2420:     }
 2421:     return ($result,$fullname,\@col_fullnames);
 2422: }
 2423: 
 2424: #--- Retrieve the last submission for all the parts
 2425: sub get_last_submission {
 2426:     my ($returnhash)=@_;
 2427:     my (@string,$timestamp,%lasthidden);
 2428:     if ($$returnhash{'version'}) {
 2429: 	my %lasthash=();
 2430: 	my ($version);
 2431: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2432: 	    foreach my $key (sort(split(/\:/,
 2433: 					$$returnhash{$version.':keys'}))) {
 2434: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2435: 		$timestamp = 
 2436: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2437: 	    }
 2438: 	}
 2439:         my (%typeparts,%randombytry);
 2440:         my $showsurv = 
 2441:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
 2442:         foreach my $key (sort(keys(%lasthash))) {
 2443:             if ($key =~ /\.type$/) {
 2444:                 if (($lasthash{$key} eq 'anonsurvey') || 
 2445:                     ($lasthash{$key} eq 'anonsurveycred') ||
 2446:                     ($lasthash{$key} eq 'randomizetry')) {
 2447:                     my ($ign,@parts) = split(/\./,$key);
 2448:                     pop(@parts);
 2449:                     my $id = join('.',@parts);
 2450:                     if ($lasthash{$key} eq 'randomizetry') {
 2451:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
 2452:                     } else {
 2453:                         unless ($showsurv) {
 2454:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
 2455:                         }
 2456:                     }
 2457:                     delete($lasthash{$key});
 2458:                 }
 2459:             }
 2460:         }
 2461:         my @hidden = keys(%typeparts);
 2462:         my @randomize = keys(%randombytry);
 2463: 	foreach my $key (keys(%lasthash)) {
 2464: 	    next if ($key !~ /\.submission$/);
 2465:             my $hide;
 2466:             if (@hidden) {
 2467:                 foreach my $id (@hidden) {
 2468:                     if ($key =~ /^\Q$id\E/) {
 2469:                         $hide = 'anon';
 2470:                         last;
 2471:                     }
 2472:                 }
 2473:             }
 2474:             unless ($hide) {
 2475:                 if (@randomize) {
 2476:                     foreach my $id (@hidden) {
 2477:                         if ($key =~ /^\Q$id\E/) {
 2478:                             $hide = 'rand';
 2479:                             last;
 2480:                         }
 2481:                     }
 2482:                 }
 2483:             }
 2484: 	    my ($partid,$foo) = split(/submission$/,$key);
 2485: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
 2486: 		'<span class="LC_warning">Draft Copy</span> ' : '';
 2487: 	    push(@string, join(':', $key, $hide, $draft.$lasthash{$key}));
 2488: 	}
 2489:     }
 2490:     if (!@string) {
 2491: 	$string[0] =
 2492: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
 2493:     }
 2494:     return (\@string,\$timestamp);
 2495: }
 2496: 
 2497: #--- High light keywords, with style choosen by user.
 2498: sub keywords_highlight {
 2499:     my $string    = shift;
 2500:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2501:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2502:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2503:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2504:     foreach my $keyword (@keylist) {
 2505: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2506:     }
 2507:     return $string;
 2508: }
 2509: 
 2510: #--- Called from submission routine
 2511: sub processHandGrade {
 2512:     my ($request,$symb) = @_;
 2513:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2514:     my $button = $env{'form.gradeOpt'};
 2515:     my $ngrade = $env{'form.NCT'};
 2516:     my $ntstu  = $env{'form.NTSTU'};
 2517:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2518:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 2519: 
 2520:     if ($button eq 'Save & Next') {
 2521: 	my $ctr = 0;
 2522: 	while ($ctr < $ngrade) {
 2523: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 2524: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 2525: 	    if ($errorflag eq 'no_score') {
 2526: 		$ctr++;
 2527: 		next;
 2528: 	    }
 2529: 	    if ($errorflag eq 'not_allowed') {
 2530: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
 2531: 		$ctr++;
 2532: 		next;
 2533: 	    }
 2534: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 2535: 	    my ($subject,$message,$msgstatus) = ('','','');
 2536: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 2537:             my ($feedurl,$showsymb) =
 2538: 		&get_feedurl_and_symb($symb,$uname,$udom);
 2539: 	    my $messagetail;
 2540: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 2541: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 2542: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 2543: 		$subject.=' ['.$restitle.']';
 2544: 		my (@msgnum) = split(/,/,$includemsg);
 2545: 		foreach (@msgnum) {
 2546: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 2547: 		}
 2548: 		$message =&Apache::lonfeedback::clear_out_html($message);
 2549: 		if ($env{'form.withgrades'.$ctr}) {
 2550: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 2551: 		    $messagetail = " for <a href=\"".
 2552: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
 2553: 		}
 2554: 		$msgstatus = 
 2555:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 2556: 						     $message.$messagetail,
 2557:                                                      undef,$feedurl,undef,
 2558:                                                      undef,undef,$showsymb,
 2559:                                                      $restitle);
 2560: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
 2561: 				$msgstatus.'<br />');
 2562: 	    }
 2563: 	    if ($env{'form.collaborator'.$ctr}) {
 2564: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 2565: 		foreach my $collabstr (@collabstrs) {
 2566: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 2567: 		    foreach my $collaborator (@collaborators) {
 2568: 			my ($errorflag,$pts,$wgt) = 
 2569: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 2570: 					   $env{'form.unamedom'.$ctr},$part);
 2571: 			if ($errorflag eq 'not_allowed') {
 2572: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 2573: 			    next;
 2574: 			} elsif ($message ne '') {
 2575: 			    my ($baseurl,$showsymb) = 
 2576: 				&get_feedurl_and_symb($symb,$collaborator,
 2577: 						      $udom);
 2578: 			    if ($env{'form.withgrades'.$ctr}) {
 2579: 				$messagetail = " for <a href=\"".
 2580:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
 2581: 			    }
 2582: 			    $msgstatus = 
 2583: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 2584: 			}
 2585: 		    }
 2586: 		}
 2587: 	    }
 2588: 	    $ctr++;
 2589: 	}
 2590:     }
 2591: 
 2592: #    if ($env{'form.handgrade'} eq 'yes') {
 2593:     if (1) {
 2594: 	# Keywords sorted in alphabatical order
 2595: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2596: 	my %keyhash = ();
 2597: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 2598: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 2599: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 2600: 	$env{'form.keywords'} = join(' ',@keywords);
 2601: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 2602: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 2603: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 2604: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 2605: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 2606: 
 2607: 	# message center - Order of message gets changed. Blank line is eliminated.
 2608: 	# New messages are saved in env for the next student.
 2609: 	# All messages are saved in nohist_handgrade.db
 2610: 	my ($ctr,$idx) = (1,1);
 2611: 	while ($ctr <= $env{'form.savemsgN'}) {
 2612: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 2613: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 2614: 		$idx++;
 2615: 	    }
 2616: 	    $ctr++;
 2617: 	}
 2618: 	$ctr = 0;
 2619: 	while ($ctr < $ngrade) {
 2620: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 2621: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2622: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2623: 		$idx++;
 2624: 	    }
 2625: 	    $ctr++;
 2626: 	}
 2627: 	$env{'form.savemsgN'} = --$idx;
 2628: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 2629: 	my $putresult = &Apache::lonnet::put
 2630: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 2631:     }
 2632:     # Called by Save & Refresh from Highlight Attribute Window
 2633:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 2634:     if ($env{'form.refresh'} eq 'on') {
 2635: 	my ($ctr,$total) = (0,0);
 2636: 	while ($ctr < $ngrade) {
 2637: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 2638: 	    $ctr++;
 2639: 	}
 2640: 	$env{'form.NTSTU'}=$ngrade;
 2641: 	$ctr = 0;
 2642: 	while ($ctr < $total) {
 2643: 	    my $processUser = $env{'form.unamedom'.$ctr};
 2644: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2645: 	    $env{'form.fullname'} = $$fullname{$processUser};
 2646: 	    &submission($request,$ctr,$total-1,$symb);
 2647: 	    $ctr++;
 2648: 	}
 2649: 	return '';
 2650:     }
 2651: 
 2652:     # Get the next/previous one or group of students
 2653:     my $firststu = $env{'form.unamedom0'};
 2654:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 2655:     my $ctr = 2;
 2656:     while ($laststu eq '') {
 2657: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 2658: 	$ctr++;
 2659: 	$laststu = $firststu if ($ctr > $ngrade);
 2660:     }
 2661: 
 2662:     my (@parsedlist,@nextlist);
 2663:     my ($nextflg) = 0;
 2664:     foreach my $item (sort 
 2665: 	     {
 2666: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 2667: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 2668: 		 }
 2669: 		 return $a cmp $b;
 2670: 	     } (keys(%$fullname))) {
 2671: # FIXME: this is fishy, looks like the button label
 2672: 	if ($nextflg == 1 && $button =~ /Next$/) {
 2673: 	    push(@parsedlist,$item);
 2674: 	}
 2675: 	$nextflg = 1 if ($item eq $laststu);
 2676: 	if ($button eq 'Previous') {
 2677: 	    last if ($item eq $firststu);
 2678: 	    push(@parsedlist,$item);
 2679: 	}
 2680:     }
 2681:     $ctr = 0;
 2682: # FIXME: this is fishy, looks like the button label
 2683:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 2684:     my $res_error;
 2685:     my ($partlist) = &response_type($symb,\$res_error);
 2686:     if ($res_error) {
 2687:         $request->print(&navmap_errormsg());
 2688:         return;
 2689:     }
 2690:     foreach my $student (@parsedlist) {
 2691: 	my $submitonly=$env{'form.submitonly'};
 2692: 	my ($uname,$udom) = split(/:/,$student);
 2693: 	
 2694: 	if ($submitonly eq 'queued') {
 2695: 	    my %queue_status = 
 2696: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 2697: 							$udom,$uname);
 2698: 	    next if (!defined($queue_status{'gradingqueue'}));
 2699: 	}
 2700: 
 2701: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 2702: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2703: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 2704: 	    my $submitted = 0;
 2705: 	    my $ungraded = 0;
 2706: 	    my $incorrect = 0;
 2707: 	    foreach my $item (keys(%status)) {
 2708: 		$submitted = 1 if ($status{$item} ne 'nothing');
 2709: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 2710: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 2711: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 2712: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 2713: 		    $submitted = 0;
 2714: 		}
 2715: 	    }
 2716: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 2717: 				     $submitonly eq 'incorrect' ||
 2718: 				     $submitonly eq 'graded'));
 2719: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 2720: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 2721: 	}
 2722: 	push(@nextlist,$student) if ($ctr < $ntstu);
 2723: 	last if ($ctr == $ntstu);
 2724: 	$ctr++;
 2725:     }
 2726: 
 2727:     $ctr = 0;
 2728:     my $total = scalar(@nextlist)-1;
 2729: 
 2730:     foreach (sort(@nextlist)) {
 2731: 	my ($uname,$udom,$submitter) = split(/:/);
 2732: 	$env{'form.student'}  = $uname;
 2733: 	$env{'form.userdom'}  = $udom;
 2734: 	$env{'form.fullname'} = $$fullname{$_};
 2735: 	&submission($request,$ctr,$total,$symb);
 2736: 	$ctr++;
 2737:     }
 2738:     if ($total < 0) {
 2739: 	my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
 2740: 	$request->print($the_end);
 2741:     }
 2742:     return '';
 2743: }
 2744: 
 2745: #---- Save the score and award for each student, if changed
 2746: sub saveHandGrade {
 2747:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 2748:     my @version_parts;
 2749:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 2750: 					   $env{'request.course.id'});
 2751:     if (!&canmodify($usec)) { return('not_allowed'); }
 2752:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 2753:     my @parts_graded;
 2754:     my %newrecord  = ();
 2755:     my ($pts,$wgt) = ('','');
 2756:     my %aggregate = ();
 2757:     my $aggregateflag = 0;
 2758:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 2759:     foreach my $new_part (@parts) {
 2760: 	#collaborator ($submi may vary for different parts
 2761: 	if ($submitter && $new_part ne $part) { next; }
 2762: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 2763: 	if ($dropMenu eq 'excused') {
 2764: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 2765: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 2766: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 2767: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 2768: 		}
 2769: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 2770: 	    }
 2771: 	} elsif ($dropMenu eq 'reset status'
 2772: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 2773: 	    foreach my $key (keys(%record)) {
 2774: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 2775: 	    }
 2776: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2777: 		"$env{'user.name'}:$env{'user.domain'}";
 2778:             my $totaltries = $record{'resource.'.$part.'.tries'};
 2779: 
 2780:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 2781: 					       [$new_part]);
 2782:             my $aggtries =$totaltries;
 2783:             if ($last_resets{$new_part}) {
 2784:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 2785: 					   $new_part);
 2786:             }
 2787: 
 2788:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 2789:             if ($aggtries > 0) {
 2790:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 2791:                 $aggregateflag = 1;
 2792:             }
 2793: 	} elsif ($dropMenu eq '') {
 2794: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 2795: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 2796: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 2797: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 2798: 		next;
 2799: 	    }
 2800: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 2801: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 2802: 	    my $partial= $pts/$wgt;
 2803: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 2804: 		#do not update score for part if not changed.
 2805:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 2806: 		next;
 2807: 	    } else {
 2808: 	        push(@parts_graded,$new_part);
 2809: 	    }
 2810: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 2811: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 2812: 	    }
 2813: 	    my $reckey = 'resource.'.$new_part.'.solved';
 2814: 	    if ($partial == 0) {
 2815: 		if ($record{$reckey} ne 'incorrect_by_override') {
 2816: 		    $newrecord{$reckey} = 'incorrect_by_override';
 2817: 		}
 2818: 	    } else {
 2819: 		if ($record{$reckey} ne 'correct_by_override') {
 2820: 		    $newrecord{$reckey} = 'correct_by_override';
 2821: 		}
 2822: 	    }	    
 2823: 	    if ($submitter && 
 2824: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 2825: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 2826: 	    }
 2827: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2828: 		"$env{'user.name'}:$env{'user.domain'}";
 2829: 	}
 2830: 	# unless problem has been graded, set flag to version the submitted files
 2831: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 2832: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 2833: 	        $dropMenu eq 'reset status')
 2834: 	   {
 2835: 	    push(@version_parts,$new_part);
 2836: 	}
 2837:     }
 2838:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2839:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2840: 
 2841:     if (%newrecord) {
 2842:         if (@version_parts) {
 2843:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 2844:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 2845: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 2846: 	    foreach my $new_part (@version_parts) {
 2847: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 2848: 				$new_part,\%newrecord);
 2849: 	    }
 2850:         }
 2851: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 2852: 				$env{'request.course.id'},$domain,$stuname);
 2853: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 2854: 				     $cdom,$cnum,$domain,$stuname);
 2855:     }
 2856:     if ($aggregateflag) {
 2857:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 2858: 			      $cdom,$cnum);
 2859:     }
 2860:     return ('',$pts,$wgt);
 2861: }
 2862: 
 2863: sub check_and_remove_from_queue {
 2864:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 2865:     my @ungraded_parts;
 2866:     foreach my $part (@{$parts}) {
 2867: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 2868: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 2869: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 2870: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 2871: 		) {
 2872: 	    push(@ungraded_parts, $part);
 2873: 	}
 2874:     }
 2875:     if ( !@ungraded_parts ) {
 2876: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 2877: 					       $cnum,$domain,$stuname);
 2878:     }
 2879: }
 2880: 
 2881: sub handback_files {
 2882:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 2883:     my $portfolio_root = '/userfiles/portfolio';
 2884:     my $res_error;
 2885:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2886:     if ($res_error) {
 2887:         $request->print('<br />'.&navmap_errormsg().'<br />');
 2888:         return;
 2889:     }
 2890:     my @handedback;
 2891:     my $file_msg;
 2892:     my @part_response_id = &flatten_responseType($responseType);
 2893:     foreach my $part_response_id (@part_response_id) {
 2894:     	my ($part_id,$resp_id) = @{ $part_response_id };
 2895: 	my $part_resp = join('_',@{ $part_response_id });
 2896:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
 2897:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
 2898:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3' 
 2899:                 if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
 2900:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
 2901:                     my ($directory,$answer_file) = 
 2902:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
 2903:                     my ($answer_name,$answer_ver,$answer_ext) =
 2904: 		        &file_name_version_ext($answer_file);
 2905: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 2906:                     my $getpropath = 1;
 2907: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
 2908: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 2909:                     # fix file name
 2910:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 2911:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 2912:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
 2913:             	                                $save_file_name);
 2914:                     if ($result !~ m|^/uploaded/|) {
 2915:                         $request->print('<br /><span class="LC_error">'.
 2916:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 2917:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
 2918:                                         '</span>');
 2919:                     } else {
 2920:                         # mark the file as read only
 2921:                         push(@handedback,$save_file_name);
 2922: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 2923: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 2924: 			}
 2925:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 2926: 			$file_msg.= '<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
 2927:                     }
 2928:                     $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>'));
 2929:                 }
 2930:             }
 2931:         }
 2932:     }
 2933:     if (@handedback > 0) {
 2934:         $request->print('<br />');
 2935:         my @what = ($symb,$env{'request.course.id'},'handback');
 2936:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
 2937:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});    
 2938:         my ($subject,$message);
 2939:         if (scalar(@handedback) == 1) {
 2940:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
 2941:             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
 2942:         } else {
 2943:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
 2944:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
 2945:         }
 2946:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
 2947:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
 2948:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
 2949:         my ($feedurl,$showsymb) =
 2950:             &get_feedurl_and_symb($symb,$domain,$stuname);
 2951:         my $restitle = &Apache::lonnet::gettitle($symb);
 2952:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
 2953:         my $msgstatus =
 2954:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
 2955:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
 2956:                  $restitle);
 2957:         if ($msgstatus) {
 2958:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
 2959:         }
 2960:     }
 2961:     return;
 2962: }
 2963: 
 2964: sub get_feedurl_and_symb {
 2965:     my ($symb,$uname,$udom) = @_;
 2966:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2967:     $url = &Apache::lonnet::clutter($url);
 2968:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 2969: 					$symb,$udom,$uname);
 2970:     if ($encrypturl =~ /^yes$/i) {
 2971: 	&Apache::lonenc::encrypted(\$url,1);
 2972: 	&Apache::lonenc::encrypted(\$symb,1);
 2973:     }
 2974:     return ($url,$symb);
 2975: }
 2976: 
 2977: sub get_submitted_files {
 2978:     my ($udom,$uname,$partid,$respid,$record) = @_;
 2979:     my @files;
 2980:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 2981:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 2982:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 2983:     	    push(@files,$file_url.$file);
 2984:         }
 2985:     }
 2986:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 2987:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 2988:     }
 2989:     return (\@files);
 2990: }
 2991: 
 2992: # ----------- Provides number of tries since last reset.
 2993: sub get_num_tries {
 2994:     my ($record,$last_reset,$part) = @_;
 2995:     my $timestamp = '';
 2996:     my $num_tries = 0;
 2997:     if ($$record{'version'}) {
 2998:         for (my $version=$$record{'version'};$version>=1;$version--) {
 2999:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 3000:                 $timestamp = $$record{$version.':timestamp'};
 3001:                 if ($timestamp > $last_reset) {
 3002:                     $num_tries ++;
 3003:                 } else {
 3004:                     last;
 3005:                 }
 3006:             }
 3007:         }
 3008:     }
 3009:     return $num_tries;
 3010: }
 3011: 
 3012: # ----------- Determine decrements required in aggregate totals 
 3013: sub decrement_aggs {
 3014:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 3015:     my %decrement = (
 3016:                         attempts => 0,
 3017:                         users => 0,
 3018:                         correct => 0
 3019:                     );
 3020:     $decrement{'attempts'} = $aggtries;
 3021:     if ($solvedstatus =~ /^correct/) {
 3022:         $decrement{'correct'} = 1;
 3023:     }
 3024:     if ($aggtries == $totaltries) {
 3025:         $decrement{'users'} = 1;
 3026:     }
 3027:     foreach my $type (keys(%decrement)) {
 3028:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 3029:     }
 3030:     return;
 3031: }
 3032: 
 3033: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 3034: sub get_last_resets {
 3035:     my ($symb,$courseid,$partids) =@_;
 3036:     my %last_resets;
 3037:     my $cdom = $env{'course.'.$courseid.'.domain'};
 3038:     my $cname = $env{'course.'.$courseid.'.num'};
 3039:     my @keys;
 3040:     foreach my $part (@{$partids}) {
 3041: 	push(@keys,"$symb\0$part\0resettime");
 3042:     }
 3043:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 3044: 				     $cdom,$cname);
 3045:     foreach my $part (@{$partids}) {
 3046: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 3047:     }
 3048:     return %last_resets;
 3049: }
 3050: 
 3051: # ----------- Handles creating versions for portfolio files as answers
 3052: sub version_portfiles {
 3053:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 3054:     my $version_parts = join('|',@$v_flag);
 3055:     my @returned_keys;
 3056:     my $parts = join('|', @$parts_graded);
 3057:     my $portfolio_root = '/userfiles/portfolio';
 3058:     foreach my $key (keys(%$record)) {
 3059:         my $new_portfiles;
 3060:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 3061:             my @versioned_portfiles;
 3062:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 3063:             foreach my $file (@portfiles) {
 3064:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 3065:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 3066: 		my ($answer_name,$answer_ver,$answer_ext) =
 3067: 		    &file_name_version_ext($answer_file);
 3068:                 my $getpropath = 1;    
 3069:                 my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
 3070:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 3071:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
 3072:                 if ($new_answer ne 'problem getting file') {
 3073:                     push(@versioned_portfiles, $directory.$new_answer);
 3074:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
 3075:                         [$directory.$new_answer],
 3076:                         [$symb,$env{'request.course.id'},'graded']);
 3077:                 }
 3078:             }
 3079:             $$record{$key} = join(',',@versioned_portfiles);
 3080:             push(@returned_keys,$key);
 3081:         }
 3082:     } 
 3083:     return (@returned_keys);   
 3084: }
 3085: 
 3086: sub get_next_version {
 3087:     my ($answer_name, $answer_ext, $dir_list) = @_;
 3088:     my $version;
 3089:     foreach my $row (@$dir_list) {
 3090:         my ($file) = split(/\&/,$row,2);
 3091:         my ($file_name,$file_version,$file_ext) =
 3092: 	    &file_name_version_ext($file);
 3093:         if (($file_name eq $answer_name) && 
 3094: 	    ($file_ext eq $answer_ext)) {
 3095:                 # gets here if filename and extension match, regardless of version
 3096:                 if ($file_version ne '') {
 3097:                 # a versioned file is found  so save it for later
 3098:                 if ($file_version > $version) {
 3099: 		    $version = $file_version;
 3100: 	        }
 3101:             }
 3102:         }
 3103:     } 
 3104:     $version ++;
 3105:     return($version);
 3106: }
 3107: 
 3108: sub version_selected_portfile {
 3109:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 3110:     my ($answer_name,$answer_ver,$answer_ext) =
 3111:         &file_name_version_ext($file_name);
 3112:     my $new_answer;
 3113:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 3114:     if($env{'form.copy'} eq '-1') {
 3115:         $new_answer = 'problem getting file';
 3116:     } else {
 3117:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 3118:         my $copy_result = &Apache::lonnet::finishuserfileupload(
 3119:                             $stu_name,$domain,'copy',
 3120: 		        '/portfolio'.$directory.$new_answer);
 3121:     }    
 3122:     return ($new_answer);
 3123: }
 3124: 
 3125: sub file_name_version_ext {
 3126:     my ($file)=@_;
 3127:     my @file_parts = split(/\./, $file);
 3128:     my ($name,$version,$ext);
 3129:     if (@file_parts > 1) {
 3130: 	$ext=pop(@file_parts);
 3131: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 3132: 	    $version=pop(@file_parts);
 3133: 	}
 3134: 	$name=join('.',@file_parts);
 3135:     } else {
 3136: 	$name=join('.',@file_parts);
 3137:     }
 3138:     return($name,$version,$ext);
 3139: }
 3140: 
 3141: #--------------------------------------------------------------------------------------
 3142: #
 3143: #-------------------------- Next few routines handles grading by section or whole class
 3144: #
 3145: #--- Javascript to handle grading by section or whole class
 3146: sub viewgrades_js {
 3147:     my ($request) = shift;
 3148: 
 3149:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3150:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
 3151:    function writePoint(partid,weight,point) {
 3152: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3153: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3154: 	if (point == "textval") {
 3155: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3156: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3157: 		alert("$alertmsg"+parseFloat(point));
 3158: 		var resetbox = false;
 3159: 		for (var i=0; i<radioButton.length; i++) {
 3160: 		    if (radioButton[i].checked) {
 3161: 			textbox.value = i;
 3162: 			resetbox = true;
 3163: 		    }
 3164: 		}
 3165: 		if (!resetbox) {
 3166: 		    textbox.value = "";
 3167: 		}
 3168: 		return;
 3169: 	    }
 3170: 	    if (parseFloat(point) > parseFloat(weight)) {
 3171: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3172: 				   ") greater than the weight for the part. Accept?");
 3173: 		if (resp == false) {
 3174: 		    textbox.value = "";
 3175: 		    return;
 3176: 		}
 3177: 	    }
 3178: 	    for (var i=0; i<radioButton.length; i++) {
 3179: 		radioButton[i].checked=false;
 3180: 		if (parseFloat(point) == i) {
 3181: 		    radioButton[i].checked=true;
 3182: 		}
 3183: 	    }
 3184: 
 3185: 	} else {
 3186: 	    textbox.value = parseFloat(point);
 3187: 	}
 3188: 	for (i=0;i<document.classgrade.total.value;i++) {
 3189: 	    var user = document.classgrade["ctr"+i].value;
 3190: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3191: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3192: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3193: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3194: 	    if (saveval != "correct") {
 3195: 		scorename.value = point;
 3196: 		if (selname[0].selected != true) {
 3197: 		    selname[0].selected = true;
 3198: 		}
 3199: 	    }
 3200: 	}
 3201: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3202:     }
 3203: 
 3204:     function writeRadText(partid,weight) {
 3205: 	var selval   = document.classgrade["SELVAL_"+partid];
 3206: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3207:         var override = document.classgrade["FORCE_"+partid].checked;
 3208: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3209: 	if (selval[1].selected || selval[2].selected) {
 3210: 	    for (var i=0; i<radioButton.length; i++) {
 3211: 		radioButton[i].checked=false;
 3212: 
 3213: 	    }
 3214: 	    textbox.value = "";
 3215: 
 3216: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3217: 		var user = document.classgrade["ctr"+i].value;
 3218: 		user = user.replace(new RegExp(':', 'g'),"_");
 3219: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3220: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3221: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3222: 		if ((saveval != "correct") || override) {
 3223: 		    scorename.value = "";
 3224: 		    if (selval[1].selected) {
 3225: 			selname[1].selected = true;
 3226: 		    } else {
 3227: 			selname[2].selected = true;
 3228: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3229: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3230: 		    }
 3231: 		}
 3232: 	    }
 3233: 	} else {
 3234: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3235: 		var user = document.classgrade["ctr"+i].value;
 3236: 		user = user.replace(new RegExp(':', 'g'),"_");
 3237: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3238: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3239: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3240: 		if ((saveval != "correct") || override) {
 3241: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3242: 		    selname[0].selected = true;
 3243: 		}
 3244: 	    }
 3245: 	}	    
 3246:     }
 3247: 
 3248:     function changeSelect(partid,user) {
 3249: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3250: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3251: 	var point  = textbox.value;
 3252: 	var weight = document.classgrade["weight_"+partid].value;
 3253: 
 3254: 	if (isNaN(point) || parseFloat(point) < 0) {
 3255: 	    alert("$alertmsg"+parseFloat(point));
 3256: 	    textbox.value = "";
 3257: 	    return;
 3258: 	}
 3259: 	if (parseFloat(point) > parseFloat(weight)) {
 3260: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3261: 			       ") greater than the weight of the part. Accept?");
 3262: 	    if (resp == false) {
 3263: 		textbox.value = "";
 3264: 		return;
 3265: 	    }
 3266: 	}
 3267: 	selval[0].selected = true;
 3268:     }
 3269: 
 3270:     function changeOneScore(partid,user) {
 3271: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3272: 	if (selval[1].selected || selval[2].selected) {
 3273: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3274: 	    if (selval[2].selected) {
 3275: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3276: 	    }
 3277:         }
 3278:     }
 3279: 
 3280:     function resetEntry(numpart) {
 3281: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3282: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3283: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3284: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3285: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3286: 	    for (var i=0; i<radioButton.length; i++) {
 3287: 		radioButton[i].checked=false;
 3288: 
 3289: 	    }
 3290: 	    textbox.value = "";
 3291: 	    selval[0].selected = true;
 3292: 
 3293: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3294: 		var user = document.classgrade["ctr"+i].value;
 3295: 		user = user.replace(new RegExp(':', 'g'),"_");
 3296: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3297: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3298: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3299: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3300: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3301: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3302: 		if (saveselval == "excused") {
 3303: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3304: 		} else {
 3305: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3306: 		}
 3307: 	    }
 3308: 	}
 3309:     }
 3310: 
 3311: VIEWJAVASCRIPT
 3312: }
 3313: 
 3314: #--- show scores for a section or whole class w/ option to change/update a score
 3315: sub viewgrades {
 3316:     my ($request,$symb) = @_;
 3317:     &viewgrades_js($request);
 3318: 
 3319:     #need to make sure we have the correct data for later EXT calls, 
 3320:     #thus invalidate the cache
 3321:     &Apache::lonnet::devalidatecourseresdata(
 3322:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3323:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3324:     &Apache::lonnet::clear_EXT_cache_status();
 3325: 
 3326:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3327: 
 3328:     #view individual student submission form - called using Javascript viewOneStudent
 3329:     $result.=&jscriptNform($symb);
 3330: 
 3331:     #beginning of class grading form
 3332:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3333:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3334: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3335: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3336: 	&build_section_inputs().
 3337: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3338: 
 3339:     my ($common_header,$specific_header);
 3340:     if ($env{'form.section'} eq 'all') {
 3341: 	$common_header = &mt('Assign Common Grade to Class');
 3342:         $specific_header = &mt('Assign Grade to Specific Students in Class');
 3343:     } elsif ($env{'form.section'} eq 'none') {
 3344:         $common_header = &mt('Assign Common Grade to Students in no Section');
 3345: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
 3346:     } else {
 3347:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3348:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
 3349: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
 3350:     }
 3351:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
 3352:     #radio buttons/text box for assigning points for a section or class.
 3353:     #handles different parts of a problem
 3354:     my $res_error;
 3355:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3356:     if ($res_error) {
 3357:         return &navmap_errormsg();
 3358:     }
 3359:     my %weight = ();
 3360:     my $ctsparts = 0;
 3361:     my %seen = ();
 3362:     my @part_response_id = &flatten_responseType($responseType);
 3363:     foreach my $part_response_id (@part_response_id) {
 3364:     	my ($partid,$respid) = @{ $part_response_id };
 3365: 	my $part_resp = join('_',@{ $part_response_id });
 3366: 	next if $seen{$partid};
 3367: 	$seen{$partid}++;
 3368: 	my $handgrade=$$handgrade{$part_resp};
 3369: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 3370: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 3371: 
 3372: 	my $display_part=&get_display_part($partid,$symb);
 3373: 	my $radio.='<table border="0"><tr>';  
 3374: 	my $ctr = 0;
 3375: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 3376: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 3377: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 3378: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 3379: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 3380: 	    $ctr++;
 3381: 	}
 3382: 	$radio.='</tr></table>';
 3383: 	my $line = '<input type="text" name="TEXTVAL_'.
 3384: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
 3385: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 3386: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 3387: 	$line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
 3388: 	    'onchange="javascript:writeRadText(\''.$partid.'\','.
 3389: 		$weight{$partid}.')"> '.
 3390: 	    '<option selected="selected"> </option>'.
 3391: 	    '<option value="excused">'.&mt('excused').'</option>'.
 3392: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 3393: 	    '</select></td>'.
 3394:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 3395: 	$line.='<input type="hidden" name="partid_'.
 3396: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 3397: 	$line.='<input type="hidden" name="weight_'.
 3398: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 3399: 
 3400: 	$result.=
 3401: 	    &Apache::loncommon::start_data_table_row()."\n".
 3402: 	    '<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>'.
 3403: 	    &Apache::loncommon::end_data_table_row()."\n";
 3404: 	$ctsparts++;
 3405:     }
 3406:     $result.=&Apache::loncommon::end_data_table()."\n".
 3407: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 3408:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 3409: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
 3410: 
 3411:     #table listing all the students in a section/class
 3412:     #header of table
 3413:     $result.= '<h3>'.$specific_header.'</h3>'.
 3414:               &Apache::loncommon::start_data_table().
 3415: 	      &Apache::loncommon::start_data_table_header_row().
 3416: 	      '<th>'.&mt('No.').'</th>'.
 3417: 	      '<th>'.&nameUserString('header')."</th>\n";
 3418:     my $partserror;
 3419:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3420:     if ($partserror) {
 3421:         return &navmap_errormsg();
 3422:     }
 3423:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 3424:     my @partids = ();
 3425:     foreach my $part (@parts) {
 3426: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3427:         my $narrowtext = &mt('Tries');
 3428: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 3429: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 3430: 	my ($partid) = &split_part_type($part);
 3431:         push(@partids,$partid);
 3432: #
 3433: # FIXME: Looks like $display looks at English text
 3434: #
 3435: 	my $display_part=&get_display_part($partid,$symb);
 3436: 	if ($display =~ /^Partial Credit Factor/) {
 3437: 	    $result.='<th>'.
 3438: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
 3439: 		    $display_part,$weight{$partid}).'</th>'."\n";
 3440: 	    next;
 3441: 	    
 3442: 	} else {
 3443: 	    if ($display =~ /Problem Status/) {
 3444: 		my $grade_status_mt = &mt('Grade Status');
 3445: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 3446: 	    }
 3447: 	    my $part_mt = &mt('Part:');
 3448: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 3449: 	}
 3450: 
 3451: 	$result.='<th>'.$display.'</th>'."\n";
 3452:     }
 3453:     $result.=&Apache::loncommon::end_data_table_header_row();
 3454: 
 3455:     my %last_resets = 
 3456: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 3457: 
 3458:     #get info for each student
 3459:     #list all the students - with points and grade status
 3460:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3461:     my $ctr = 0;
 3462:     foreach (sort 
 3463: 	     {
 3464: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3465: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3466: 		 }
 3467: 		 return $a cmp $b;
 3468: 	     } (keys(%$fullname))) {
 3469: 	$ctr++;
 3470: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 3471: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
 3472:     }
 3473:     $result.=&Apache::loncommon::end_data_table();
 3474:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 3475:     $result.='<input type="button" value="'.&mt('Save').'" '.
 3476: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
 3477:     if (scalar(%$fullname) eq 0) {
 3478: 	my $colspan=3+scalar(@parts);
 3479: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3480:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 3481: 	$result='<span class="LC_warning">'.
 3482: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 3483: 	        $section_display, $stu_status).
 3484: 	    '</span>';
 3485:     }
 3486:     return $result;
 3487: }
 3488: 
 3489: #--- call by previous routine to display each student
 3490: sub viewstudentgrade {
 3491:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 3492:     my ($uname,$udom) = split(/:/,$student);
 3493:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 3494:     my %aggregates = (); 
 3495:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 3496: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
 3497: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
 3498: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 3499: 	'\');" target="_self">'.$fullname.'</a> '.
 3500: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 3501:     $student=~s/:/_/; # colon doen't work in javascript for names
 3502:     foreach my $apart (@$parts) {
 3503: 	my ($part,$type) = &split_part_type($apart);
 3504: 	my $score=$record{"resource.$part.$type"};
 3505:         $result.='<td align="center">';
 3506:         my ($aggtries,$totaltries);
 3507:         unless (exists($aggregates{$part})) {
 3508: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 3509: 
 3510: 	    $aggtries = $totaltries;
 3511:             if ($$last_resets{$part}) {  
 3512:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 3513: 					   $part);
 3514:             }
 3515:             $result.='<input type="hidden" name="'.
 3516:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 3517:             $result.='<input type="hidden" name="'.
 3518:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 3519:             $aggregates{$part} = 1;
 3520:         }
 3521: 	if ($type eq 'awarded') {
 3522: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 3523: 	    $result.='<input type="hidden" name="'.
 3524: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 3525: 	    $result.='<input type="text" name="'.
 3526: 		'GD_'.$student.'_'.$part.'_awarded" '.
 3527:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
 3528: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 3529: 	} elsif ($type eq 'solved') {
 3530: 	    my ($status,$foo)=split(/_/,$score,2);
 3531: 	    $status = 'nothing' if ($status eq '');
 3532: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 3533: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 3534: 	    $result.='&nbsp;<select name="'.
 3535: 		'GD_'.$student.'_'.$part.'_solved" '.
 3536:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 3537: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 3538: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 3539: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 3540: 	    $result.="</select>&nbsp;</td>\n";
 3541: 	} else {
 3542: 	    $result.='<input type="hidden" name="'.
 3543: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 3544: 		    "\n";
 3545: 	    $result.='<input type="text" name="'.
 3546: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 3547: 		'value="'.$score.'" size="4" /></td>'."\n";
 3548: 	}
 3549:     }
 3550:     $result.=&Apache::loncommon::end_data_table_row();
 3551:     return $result;
 3552: }
 3553: 
 3554: #--- change scores for all the students in a section/class
 3555: #    record does not get update if unchanged
 3556: sub editgrades {
 3557:     my ($request,$symb) = @_;
 3558: 
 3559:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3560:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 3561:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
 3562: 
 3563:     my $result= &Apache::loncommon::start_data_table().
 3564: 	&Apache::loncommon::start_data_table_header_row().
 3565: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 3566: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 3567:     my %scoreptr = (
 3568: 		    'correct'  =>'correct_by_override',
 3569: 		    'incorrect'=>'incorrect_by_override',
 3570: 		    'excused'  =>'excused',
 3571: 		    'ungraded' =>'ungraded_attempted',
 3572:                     'credited' =>'credit_attempted',
 3573: 		    'nothing'  => '',
 3574: 		    );
 3575:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 3576: 
 3577:     my (@partid);
 3578:     my %weight = ();
 3579:     my %columns = ();
 3580:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 3581: 
 3582:     my $partserror;
 3583:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3584:     if ($partserror) {
 3585:         return &navmap_errormsg();
 3586:     }
 3587:     my $header;
 3588:     while ($ctr < $env{'form.totalparts'}) {
 3589: 	my $partid = $env{'form.partid_'.$ctr};
 3590: 	push(@partid,$partid);
 3591: 	$weight{$partid} = $env{'form.weight_'.$partid};
 3592: 	$ctr++;
 3593:     }
 3594:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3595:     foreach my $partid (@partid) {
 3596: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 3597: 	    '<th align="center">'.&mt('New Score').'</th>';
 3598: 	$columns{$partid}=2;
 3599: 	foreach my $stores (@parts) {
 3600: 	    my ($part,$type) = &split_part_type($stores);
 3601: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 3602: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 3603: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 3604: 	    $display =~ s/\[Part: \Q$part\E\]//;
 3605:             my $narrowtext = &mt('Tries');
 3606: 	    $display =~ s/Number of Attempts/$narrowtext/;
 3607: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 3608: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 3609: 	    $columns{$partid}+=2;
 3610: 	}
 3611:     }
 3612:     foreach my $partid (@partid) {
 3613: 	my $display_part=&get_display_part($partid,$symb);
 3614: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 3615: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 3616: 	    '</th>';
 3617: 
 3618:     }
 3619:     $result .= &Apache::loncommon::end_data_table_header_row().
 3620: 	&Apache::loncommon::start_data_table_header_row().
 3621: 	$header.
 3622: 	&Apache::loncommon::end_data_table_header_row();
 3623:     my @noupdate;
 3624:     my ($updateCtr,$noupdateCtr) = (1,1);
 3625:     for ($i=0; $i<$env{'form.total'}; $i++) {
 3626: 	my $line;
 3627: 	my $user = $env{'form.ctr'.$i};
 3628: 	my ($uname,$udom)=split(/:/,$user);
 3629: 	my %newrecord;
 3630: 	my $updateflag = 0;
 3631: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 3632: 	my $usec=$classlist->{"$uname:$udom"}[5];
 3633: 	if (!&canmodify($usec)) {
 3634: 	    my $numcols=scalar(@partid)*4+2;
 3635: 	    push(@noupdate,
 3636: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
 3637: 		 &mt('Not allowed to modify student')."</span></td></tr>");
 3638: 	    next;
 3639: 	}
 3640:         my %aggregate = ();
 3641:         my $aggregateflag = 0;
 3642: 	$user=~s/:/_/; # colon doen't work in javascript for names
 3643: 	foreach (@partid) {
 3644: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 3645: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 3646: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 3647: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3648: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 3649: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 3650: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 3651: 	    my $score;
 3652: 	    if ($partial eq '') {
 3653: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3654: 	    } elsif ($partial > 0) {
 3655: 		$score = 'correct_by_override';
 3656: 	    } elsif ($partial == 0) {
 3657: 		$score = 'incorrect_by_override';
 3658: 	    }
 3659: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 3660: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 3661: 
 3662: 	    $newrecord{'resource.'.$_.'.regrader'}=
 3663: 		"$env{'user.name'}:$env{'user.domain'}";
 3664: 	    if ($dropMenu eq 'reset status' &&
 3665: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 3666: 		$newrecord{'resource.'.$_.'.tries'} = '';
 3667: 		$newrecord{'resource.'.$_.'.solved'} = '';
 3668: 		$newrecord{'resource.'.$_.'.award'} = '';
 3669: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 3670: 		$updateflag = 1;
 3671:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 3672:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 3673:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 3674:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 3675:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3676:                     $aggregateflag = 1;
 3677:                 }
 3678: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 3679: 		$updateflag = 1;
 3680: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 3681: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 3682: 		$rec_update++;
 3683: 	    }
 3684: 
 3685: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3686: 		'<td align="center">'.$awarded.
 3687: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 3688: 
 3689: 
 3690: 	    my $partid=$_;
 3691: 	    foreach my $stores (@parts) {
 3692: 		my ($part,$type) = &split_part_type($stores);
 3693: 		if ($part !~ m/^\Q$partid\E/) { next;}
 3694: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 3695: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 3696: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 3697: 		if ($awarded ne '' && $awarded ne $old_aw) {
 3698: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 3699: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3700: 		    $updateflag=1;
 3701: 		}
 3702: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3703: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 3704: 	    }
 3705: 	}
 3706: 	$line.="\n";
 3707: 
 3708: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3709: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3710: 
 3711: 	if ($updateflag) {
 3712: 	    $count++;
 3713: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 3714: 				    $udom,$uname);
 3715: 
 3716: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 3717: 					      $cnum,$udom,$uname)) {
 3718: 		# need to figure out if should be in queue.
 3719: 		my %record =  
 3720: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 3721: 					     $udom,$uname);
 3722: 		my $all_graded = 1;
 3723: 		my $none_graded = 1;
 3724: 		foreach my $part (@parts) {
 3725: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 3726: 			$all_graded = 0;
 3727: 		    } else {
 3728: 			$none_graded = 0;
 3729: 		    }
 3730: 		}
 3731: 
 3732: 		if ($all_graded || $none_graded) {
 3733: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 3734: 							   $symb,$cdom,$cnum,
 3735: 							   $udom,$uname);
 3736: 		}
 3737: 	    }
 3738: 
 3739: 	    $result.=&Apache::loncommon::start_data_table_row().
 3740: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 3741: 		&Apache::loncommon::end_data_table_row();
 3742: 	    $updateCtr++;
 3743: 	} else {
 3744: 	    push(@noupdate,
 3745: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 3746: 	    $noupdateCtr++;
 3747: 	}
 3748:         if ($aggregateflag) {
 3749:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3750: 				  $cdom,$cnum);
 3751:         }
 3752:     }
 3753:     if (@noupdate) {
 3754: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
 3755: 	my $numcols=scalar(@partid)*4+2;
 3756: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 3757: 	    '<td align="center" colspan="'.$numcols.'">'.
 3758: 	    &mt('No Changes Occurred For the Students Below').
 3759: 	    '</td>'.
 3760: 	    &Apache::loncommon::end_data_table_row();
 3761: 	foreach my $line (@noupdate) {
 3762: 	    $result.=
 3763: 		&Apache::loncommon::start_data_table_row().
 3764: 		$line.
 3765: 		&Apache::loncommon::end_data_table_row();
 3766: 	}
 3767:     }
 3768:     $result .= &Apache::loncommon::end_data_table();
 3769:     my $msg = '<p><b>'.
 3770: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 3771: 	    $rec_update,$count).'</b><br />'.
 3772: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 3773: 	'</b></p>';
 3774:     return $title.$msg.$result;
 3775: }
 3776: 
 3777: sub split_part_type {
 3778:     my ($partstr) = @_;
 3779:     my ($temp,@allparts)=split(/_/,$partstr);
 3780:     my $type=pop(@allparts);
 3781:     my $part=join('_',@allparts);
 3782:     return ($part,$type);
 3783: }
 3784: 
 3785: #------------- end of section for handling grading by section/class ---------
 3786: #
 3787: #----------------------------------------------------------------------------
 3788: 
 3789: 
 3790: #----------------------------------------------------------------------------
 3791: #
 3792: #-------------------------- Next few routines handles grading by csv upload
 3793: #
 3794: #--- Javascript to handle csv upload
 3795: sub csvupload_javascript_reverse_associate {
 3796:     my $error1=&mt('You need to specify the username or the student/employee ID');
 3797:     my $error2=&mt('You need to specify at least one grading field');
 3798:   return(<<ENDPICK);
 3799:   function verify(vf) {
 3800:     var foundsomething=0;
 3801:     var founduname=0;
 3802:     var foundID=0;
 3803:     for (i=0;i<=vf.nfields.value;i++) {
 3804:       tw=eval('vf.f'+i+'.selectedIndex');
 3805:       if (i==0 && tw!=0) { foundID=1; }
 3806:       if (i==1 && tw!=0) { founduname=1; }
 3807:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 3808:     }
 3809:     if (founduname==0 && foundID==0) {
 3810: 	alert('$error1');
 3811: 	return;
 3812:     }
 3813:     if (foundsomething==0) {
 3814: 	alert('$error2');
 3815: 	return;
 3816:     }
 3817:     vf.submit();
 3818:   }
 3819:   function flip(vf,tf) {
 3820:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3821:     var i;
 3822:     for (i=0;i<=vf.nfields.value;i++) {
 3823:       //can not pick the same destination field for both name and domain
 3824:       if (((i ==0)||(i ==1)) && 
 3825:           ((tf==0)||(tf==1)) && 
 3826:           (i!=tf) &&
 3827:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3828:         eval('vf.f'+i+'.selectedIndex=0;')
 3829:       }
 3830:     }
 3831:   }
 3832: ENDPICK
 3833: }
 3834: 
 3835: sub csvupload_javascript_forward_associate {
 3836:     my $error1=&mt('You need to specify the username or the student/employee ID');
 3837:     my $error2=&mt('You need to specify at least one grading field');
 3838:   return(<<ENDPICK);
 3839:   function verify(vf) {
 3840:     var foundsomething=0;
 3841:     var founduname=0;
 3842:     var foundID=0;
 3843:     for (i=0;i<=vf.nfields.value;i++) {
 3844:       tw=eval('vf.f'+i+'.selectedIndex');
 3845:       if (tw==1) { foundID=1; }
 3846:       if (tw==2) { founduname=1; }
 3847:       if (tw>3) { foundsomething=1; }
 3848:     }
 3849:     if (founduname==0 && foundID==0) {
 3850: 	alert('$error1');
 3851: 	return;
 3852:     }
 3853:     if (foundsomething==0) {
 3854: 	alert('$error2');
 3855: 	return;
 3856:     }
 3857:     vf.submit();
 3858:   }
 3859:   function flip(vf,tf) {
 3860:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3861:     var i;
 3862:     //can not pick the same destination field twice
 3863:     for (i=0;i<=vf.nfields.value;i++) {
 3864:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3865:         eval('vf.f'+i+'.selectedIndex=0;')
 3866:       }
 3867:     }
 3868:   }
 3869: ENDPICK
 3870: }
 3871: 
 3872: sub csvuploadmap_header {
 3873:     my ($request,$symb,$datatoken,$distotal)= @_;
 3874:     my $javascript;
 3875:     if ($env{'form.upfile_associate'} eq 'reverse') {
 3876: 	$javascript=&csvupload_javascript_reverse_associate();
 3877:     } else {
 3878: 	$javascript=&csvupload_javascript_forward_associate();
 3879:     }
 3880: 
 3881:     $symb = &Apache::lonenc::check_encrypt($symb);
 3882:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
 3883:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
 3884:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
 3885:     my $reverse=&mt("Reverse Association");
 3886:     $request->print(<<ENDPICK);
 3887: <br />
 3888: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 3889: <input type="hidden" name="associate"  value="" />
 3890: <input type="hidden" name="phase"      value="three" />
 3891: <input type="hidden" name="datatoken"  value="$datatoken" />
 3892: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 3893: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 3894: <input type="hidden" name="upfile_associate" 
 3895:                                        value="$env{'form.upfile_associate'}" />
 3896: <input type="hidden" name="symb"       value="$symb" />
 3897: <input type="hidden" name="command"    value="csvuploadoptions" />
 3898: <hr />
 3899: ENDPICK
 3900:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
 3901:     return '';
 3902: 
 3903: }
 3904: 
 3905: sub csvupload_fields {
 3906:     my ($symb,$errorref) = @_;
 3907:     my (@parts) = &getpartlist($symb,$errorref);
 3908:     if (ref($errorref)) {
 3909:         if ($$errorref) {
 3910:             return;
 3911:         }
 3912:     }
 3913: 
 3914:     my @fields=(['ID','Student/Employee ID'],
 3915: 		['username','Student Username'],
 3916: 		['domain','Student Domain']);
 3917:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3918:     foreach my $part (sort(@parts)) {
 3919: 	my @datum;
 3920: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3921: 	my $name=$part;
 3922: 	if  (!$display) { $display = $name; }
 3923: 	@datum=($name,$display);
 3924: 	if ($name=~/^stores_(.*)_awarded/) {
 3925: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 3926: 	}
 3927: 	push(@fields,\@datum);
 3928:     }
 3929:     return (@fields);
 3930: }
 3931: 
 3932: sub csvuploadmap_footer {
 3933:     my ($request,$i,$keyfields) =@_;
 3934:     $request->print(<<ENDPICK);
 3935: </table>
 3936: <input type="hidden" name="nfields" value="$i" />
 3937: <input type="hidden" name="keyfields" value="$keyfields" />
 3938: <input type="button" onclick="javascript:verify(this.form)" value="Assign Grades" /><br />
 3939: </form>
 3940: ENDPICK
 3941: }
 3942: 
 3943: sub checkforfile_js {
 3944:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 3945:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
 3946:     function checkUpload(formname) {
 3947: 	if (formname.upfile.value == "") {
 3948: 	    alert("$alertmsg");
 3949: 	    return false;
 3950: 	}
 3951: 	formname.submit();
 3952:     }
 3953: CSVFORMJS
 3954:     return $result;
 3955: }
 3956: 
 3957: sub upcsvScores_form {
 3958:     my ($request,$symb) = @_;
 3959:     if (!$symb) {return '';}
 3960:     my $result=&checkforfile_js();
 3961:     $result.=&Apache::loncommon::start_data_table().
 3962:              &Apache::loncommon::start_data_table_header_row().
 3963:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
 3964:              &Apache::loncommon::end_data_table_header_row().
 3965:              &Apache::loncommon::start_data_table_row().'<td>';
 3966:     my $upload=&mt("Upload Scores");
 3967:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 3968:     my $ignore=&mt('Ignore First Line');
 3969:     $symb = &Apache::lonenc::check_encrypt($symb);
 3970:     $result.=<<ENDUPFORM;
 3971: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3972: <input type="hidden" name="symb" value="$symb" />
 3973: <input type="hidden" name="command" value="csvuploadmap" />
 3974: $upfile_select
 3975: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 3976: </form>
 3977: ENDUPFORM
 3978:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 3979:                            &mt("How do I create a CSV file from a spreadsheet")).
 3980:              '</td>'.
 3981:             &Apache::loncommon::end_data_table_row().
 3982:             &Apache::loncommon::end_data_table();
 3983:     return $result;
 3984: }
 3985: 
 3986: 
 3987: sub csvuploadmap {
 3988:     my ($request,$symb)= @_;
 3989:     if (!$symb) {return '';}
 3990: 
 3991:     my $datatoken;
 3992:     if (!$env{'form.datatoken'}) {
 3993: 	$datatoken=&Apache::loncommon::upfile_store($request);
 3994:     } else {
 3995: 	$datatoken=$env{'form.datatoken'};
 3996: 	&Apache::loncommon::load_tmp_file($request);
 3997:     }
 3998:     my @records=&Apache::loncommon::upfile_record_sep();
 3999:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 4000:     my ($i,$keyfields);
 4001:     if (@records) {
 4002:         my $fieldserror;
 4003: 	my @fields=&csvupload_fields($symb,\$fieldserror);
 4004:         if ($fieldserror) {
 4005:             $request->print(&navmap_errormsg());
 4006:             return;
 4007:         }
 4008: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 4009: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 4010: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 4011: 							  \@fields);
 4012: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 4013: 	    chop($keyfields);
 4014: 	} else {
 4015: 	    unshift(@fields,['none','']);
 4016: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 4017: 							    \@fields);
 4018:             foreach my $rec (@records) {
 4019:                 my %temp = &Apache::loncommon::record_sep($rec);
 4020:                 if (%temp) {
 4021:                     $keyfields=join(',',sort(keys(%temp)));
 4022:                     last;
 4023:                 }
 4024:             }
 4025: 	}
 4026:     }
 4027:     &csvuploadmap_footer($request,$i,$keyfields);
 4028: 
 4029:     return '';
 4030: }
 4031: 
 4032: sub csvuploadoptions {
 4033:     my ($request,$symb)= @_;
 4034:     my $overwrite=&mt('Overwrite any existing score');
 4035:     $request->print(<<ENDPICK);
 4036: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4037: <input type="hidden" name="command"    value="csvuploadassign" />
 4038: <p>
 4039: <label>
 4040:    <input type="checkbox" name="overwite_scores" checked="checked" />
 4041:    $overwrite
 4042: </label>
 4043: </p>
 4044: ENDPICK
 4045:     my %fields=&get_fields();
 4046:     if (!defined($fields{'domain'})) {
 4047: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 4048: 	$request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
 4049:     }
 4050:     foreach my $key (sort(keys(%env))) {
 4051: 	if ($key !~ /^form\.(.*)$/) { next; }
 4052: 	my $cleankey=$1;
 4053: 	if ($cleankey eq 'command') { next; }
 4054: 	$request->print('<input type="hidden" name="'.$cleankey.
 4055: 			'"  value="'.$env{$key}.'" />'."\n");
 4056:     }
 4057:     # FIXME do a check for any duplicated user ids...
 4058:     # FIXME do a check for any invalid user ids?...
 4059:     $request->print('<input type="submit" value="Assign Grades" /><br />
 4060: <hr /></form>'."\n");
 4061:     return '';
 4062: }
 4063: 
 4064: sub get_fields {
 4065:     my %fields;
 4066:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 4067:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 4068: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 4069: 	    if ($env{'form.f'.$i} ne 'none') {
 4070: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 4071: 	    }
 4072: 	} else {
 4073: 	    if ($env{'form.f'.$i} ne 'none') {
 4074: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 4075: 	    }
 4076: 	}
 4077:     }
 4078:     return %fields;
 4079: }
 4080: 
 4081: sub csvuploadassign {
 4082:     my ($request,$symb)= @_;
 4083:     if (!$symb) {return '';}
 4084:     my $error_msg = '';
 4085:     &Apache::loncommon::load_tmp_file($request);
 4086:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 4087:     my %fields=&get_fields();
 4088:     my $courseid=$env{'request.course.id'};
 4089:     my ($classlist) = &getclasslist('all',0);
 4090:     my @notallowed;
 4091:     my @skipped;
 4092:     my $countdone=0;
 4093:     foreach my $grade (@gradedata) {
 4094: 	my %entries=&Apache::loncommon::record_sep($grade);
 4095: 	my $domain;
 4096: 	if ($entries{$fields{'domain'}}) {
 4097: 	    $domain=$entries{$fields{'domain'}};
 4098: 	} else {
 4099: 	    $domain=$env{'form.default_domain'};
 4100: 	}
 4101: 	$domain=~s/\s//g;
 4102: 	my $username=$entries{$fields{'username'}};
 4103: 	$username=~s/\s//g;
 4104: 	if (!$username) {
 4105: 	    my $id=$entries{$fields{'ID'}};
 4106: 	    $id=~s/\s//g;
 4107: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 4108: 	    $username=$ids{$id};
 4109: 	}
 4110: 	if (!exists($$classlist{"$username:$domain"})) {
 4111: 	    my $id=$entries{$fields{'ID'}};
 4112: 	    $id=~s/\s//g;
 4113: 	    if ($id) {
 4114: 		push(@skipped,"$id:$domain");
 4115: 	    } else {
 4116: 		push(@skipped,"$username:$domain");
 4117: 	    }
 4118: 	    next;
 4119: 	}
 4120: 	my $usec=$classlist->{"$username:$domain"}[5];
 4121: 	if (!&canmodify($usec)) {
 4122: 	    push(@notallowed,"$username:$domain");
 4123: 	    next;
 4124: 	}
 4125: 	my %points;
 4126: 	my %grades;
 4127: 	foreach my $dest (keys(%fields)) {
 4128: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 4129: 		$dest eq 'domain') { next; }
 4130: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 4131: 	    if ($dest=~/stores_(.*)_points/) {
 4132: 		my $part=$1;
 4133: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 4134: 					      $symb,$domain,$username);
 4135:                 if ($wgt) {
 4136:                     $entries{$fields{$dest}}=~s/\s//g;
 4137:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 4138:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 4139:                                           : 'correct_by_override';
 4140:                     if ($pcr>1) {
 4141:                        push(@skipped,&mt("[_1]: point value larger than weight","$username:$domain"));
 4142:                     }
 4143:                     $grades{"resource.$part.awarded"}=$pcr;
 4144:                     $grades{"resource.$part.solved"}=$award;
 4145:                     $points{$part}=1;
 4146:                 } else {
 4147:                     $error_msg = "<br />" .
 4148:                         &mt("Some point values were assigned"
 4149:                             ." for problems with a weight "
 4150:                             ."of zero. These values were "
 4151:                             ."ignored.");
 4152:                 }
 4153: 	    } else {
 4154: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 4155: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 4156: 		my $store_key=$dest;
 4157: 		$store_key=~s/^stores/resource/;
 4158: 		$store_key=~s/_/\./g;
 4159: 		$grades{$store_key}=$entries{$fields{$dest}};
 4160: 	    }
 4161: 	}
 4162: 	if (! %grades) { 
 4163:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 4164:         } else {
 4165: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 4166: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 4167: 					   $env{'request.course.id'},
 4168: 					   $domain,$username);
 4169: 	   if ($result eq 'ok') {
 4170: # Successfully stored
 4171: 	      $request->print('.');
 4172: # Remove from grading queue
 4173:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
 4174:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
 4175:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
 4176:                                              $domain,$username);
 4177:               $countdone++;
 4178:            } else {
 4179: 	      $request->print("<p><span class=\"LC_error\">".
 4180:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 4181:                                   "$username:$domain",$result)."</span></p>");
 4182: 	   }
 4183: 	   $request->rflush();
 4184:         }
 4185:     }
 4186:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
 4187:     if (@skipped) {
 4188: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
 4189:         $request->print(join(', ',@skipped));
 4190:     }
 4191:     if (@notallowed) {
 4192: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
 4193: 	$request->print(join(', ',@notallowed));
 4194:     }
 4195:     $request->print("<br />\n");
 4196:     return $error_msg;
 4197: }
 4198: #------------- end of section for handling csv file upload ---------
 4199: #
 4200: #-------------------------------------------------------------------
 4201: #
 4202: #-------------- Next few routines handle grading by page/sequence
 4203: #
 4204: #--- Select a page/sequence and a student to grade
 4205: sub pickStudentPage {
 4206:     my ($request,$symb) = @_;
 4207: 
 4208:     my $alertmsg = &mt('Please select the student you wish to grade.');
 4209:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
 4210: 
 4211: function checkPickOne(formname) {
 4212:     if (radioSelection(formname.student) == null) {
 4213: 	alert("$alertmsg");
 4214: 	return;
 4215:     }
 4216:     ptr = pullDownSelection(formname.selectpage);
 4217:     formname.page.value = formname["page"+ptr].value;
 4218:     formname.title.value = formname["title"+ptr].value;
 4219:     formname.submit();
 4220: }
 4221: 
 4222: LISTJAVASCRIPT
 4223:     &commonJSfunctions($request);
 4224: 
 4225:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4226:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4227:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4228: 
 4229:     my $result='<h3><span class="LC_info">&nbsp;'.
 4230: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 4231: 
 4232:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 4233:     my $map_error;
 4234:     my ($titles,$symbx) = &getSymbMap($map_error);
 4235:     if ($map_error) {
 4236:         $request->print(&navmap_errormsg());
 4237:         return; 
 4238:     }
 4239:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 4240: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 4241: #    my $type=($curpage =~ /\.(page|sequence)/);
 4242:     my $select = '<select name="selectpage">'."\n";
 4243:     my $ctr=0;
 4244:     foreach (@$titles) {
 4245: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4246: 	$select.='<option value="'.$ctr.'" '.
 4247: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4248: 	    '>'.$showtitle.'</option>'."\n";
 4249: 	$ctr++;
 4250:     }
 4251:     $select.= '</select>';
 4252:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
 4253: 
 4254:     $ctr=0;
 4255:     foreach (@$titles) {
 4256: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4257: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 4258: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 4259: 	$ctr++;
 4260:     }
 4261:     $result.='<input type="hidden" name="page" />'."\n".
 4262: 	'<input type="hidden" name="title" />'."\n";
 4263: 
 4264:     my $options =
 4265: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
 4266: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
 4267:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
 4268: 
 4269:     $options =
 4270: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
 4271: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
 4272: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
 4273:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
 4274:     
 4275:     $result.=&build_section_inputs();
 4276:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4277:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 4278: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 4279: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."<br />\n";
 4280: 
 4281:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
 4282: 
 4283:     $result.='&nbsp;<input type="button" '.
 4284:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 4285: 
 4286:     $request->print($result);
 4287: 
 4288:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 4289: 	&Apache::loncommon::start_data_table().
 4290: 	&Apache::loncommon::start_data_table_header_row().
 4291: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4292: 	'<th>'.&nameUserString('header').'</th>'.
 4293: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4294: 	'<th>'.&nameUserString('header').'</th>'.
 4295: 	&Apache::loncommon::end_data_table_header_row();
 4296:  
 4297:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 4298:     my $ptr = 1;
 4299:     foreach my $student (sort 
 4300: 			 {
 4301: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4302: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4303: 			     }
 4304: 			     return $a cmp $b;
 4305: 			 } (keys(%$fullname))) {
 4306: 	my ($uname,$udom) = split(/:/,$student);
 4307: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 4308:                                   : '</td>');
 4309: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 4310: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 4311: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 4312: 	$studentTable.=
 4313: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 4314:                          : '');
 4315: 	$ptr++;
 4316:     }
 4317:     if ($ptr%2 == 0) {
 4318: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 4319: 	    &Apache::loncommon::end_data_table_row();
 4320:     }
 4321:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 4322:     $studentTable.='<input type="button" '.
 4323:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 4324: 
 4325:     $request->print($studentTable);
 4326: 
 4327:     return '';
 4328: }
 4329: 
 4330: sub getSymbMap {
 4331:     my ($map_error) = @_;
 4332:     my $navmap = Apache::lonnavmaps::navmap->new();
 4333:     unless (ref($navmap)) {
 4334:         if (ref($map_error)) {
 4335:             $$map_error = 'navmap';
 4336:         }
 4337:         return;
 4338:     }
 4339:     my %symbx = ();
 4340:     my @titles = ();
 4341:     my $minder = 0;
 4342: 
 4343:     # Gather every sequence that has problems.
 4344:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 4345: 					       1,0,1);
 4346:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 4347: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 4348: 	    my $title = $minder.'.'.
 4349: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 4350: 	    push(@titles, $title); # minder in case two titles are identical
 4351: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 4352: 	    $minder++;
 4353: 	}
 4354:     }
 4355:     return \@titles,\%symbx;
 4356: }
 4357: 
 4358: #
 4359: #--- Displays a page/sequence w/wo problems, w/wo submissions
 4360: sub displayPage {
 4361:     my ($request,$symb) = @_;
 4362:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4363:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4364:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4365:     my $pageTitle = $env{'form.page'};
 4366:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4367:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4368:     my $usec=$classlist->{$env{'form.student'}}[5];
 4369: 
 4370:     #need to make sure we have the correct data for later EXT calls, 
 4371:     #thus invalidate the cache
 4372:     &Apache::lonnet::devalidatecourseresdata(
 4373:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 4374:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 4375:     &Apache::lonnet::clear_EXT_cache_status();
 4376: 
 4377:     if (!&canview($usec)) {
 4378: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
 4379: 	return;
 4380:     }
 4381:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4382:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 4383: 	'</h3>'."\n";
 4384:     $env{'form.CODE'} = uc($env{'form.CODE'});
 4385:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 4386: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 4387:     } else {
 4388: 	delete($env{'form.CODE'});
 4389:     }
 4390:     &sub_page_js($request);
 4391:     $request->print($result);
 4392: 
 4393:     my $navmap = Apache::lonnavmaps::navmap->new();
 4394:     unless (ref($navmap)) {
 4395:         $request->print(&navmap_errormsg());
 4396:         return;
 4397:     }
 4398:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 4399:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4400:     if (!$map) {
 4401: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 4402: 	return; 
 4403:     }
 4404:     my $iterator = $navmap->getIterator($map->map_start(),
 4405: 					$map->map_finish());
 4406: 
 4407:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 4408: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 4409: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 4410: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 4411: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 4412: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 4413: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4414: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
 4415: 
 4416:     if (defined($env{'form.CODE'})) {
 4417: 	$studentTable.=
 4418: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 4419:     }
 4420:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 4421: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 4422: 
 4423:     $studentTable.='&nbsp;<span class="LC_info">'.
 4424:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
 4425:         '</span>'."\n".
 4426: 	&Apache::loncommon::start_data_table().
 4427: 	&Apache::loncommon::start_data_table_header_row().
 4428: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
 4429: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 4430: 	&Apache::loncommon::end_data_table_header_row();
 4431: 
 4432:     &Apache::lonxml::clear_problem_counter();
 4433:     my ($depth,$question,$prob) = (1,1,1);
 4434:     $iterator->next(); # skip the first BEGIN_MAP
 4435:     my $curRes = $iterator->next(); # for "current resource"
 4436:     while ($depth > 0) {
 4437:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4438:         if($curRes == $iterator->END_MAP) { $depth--; }
 4439: 
 4440:         if (ref($curRes) && $curRes->is_problem()) {
 4441: 	    my $parts = $curRes->parts();
 4442:             my $title = $curRes->compTitle();
 4443: 	    my $symbx = $curRes->symb();
 4444: 	    $studentTable.=
 4445: 		&Apache::loncommon::start_data_table_row().
 4446: 		'<td align="center" valign="top" >'.$prob.
 4447: 		(scalar(@{$parts}) == 1 ? '' 
 4448: 		                        : '<br />('.&mt('[_1]parts)',
 4449: 							scalar(@{$parts}).'&nbsp;')
 4450: 		 ).
 4451: 		 '</td>';
 4452: 	    $studentTable.='<td valign="top">';
 4453: 	    my %form = ('CODE' => $env{'form.CODE'},);
 4454: 	    if ($env{'form.vProb'} eq 'yes' ) {
 4455: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 4456: 					     undef,'both',\%form);
 4457: 	    } else {
 4458: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 4459: 		$companswer =~ s|<form(.*?)>||g;
 4460: 		$companswer =~ s|</form>||g;
 4461: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 4462: #		    $companswer =~ s/$1/ /ms;
 4463: #		    $request->print('match='.$1."<br />\n");
 4464: #		}
 4465: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 4466: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 4467: 	    }
 4468: 
 4469: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 4470: 
 4471: 	    if ($env{'form.lastSub'} eq 'datesub') {
 4472: 		if ($record{'version'} eq '') {
 4473: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
 4474: 		} else {
 4475: 		    my %responseType = ();
 4476: 		    foreach my $partid (@{$parts}) {
 4477: 			my @responseIds =$curRes->responseIds($partid);
 4478: 			my @responseType =$curRes->responseType($partid);
 4479: 			my %responseIds;
 4480: 			for (my $i=0;$i<=$#responseIds;$i++) {
 4481: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 4482: 			}
 4483: 			$responseType{$partid} = \%responseIds;
 4484: 		    }
 4485: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 4486: 
 4487: 		}
 4488: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 4489: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 4490: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 4491: 									$env{'request.course.id'},
 4492: 									'','.submission');
 4493:  
 4494: 	    }
 4495: 	    if (&canmodify($usec)) {
 4496:             $studentTable.=&gradeBox_start();
 4497: 		foreach my $partid (@{$parts}) {
 4498: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 4499: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 4500: 		    $question++;
 4501: 		}
 4502:             $studentTable.=&gradeBox_end();
 4503: 		$prob++;
 4504: 	    }
 4505: 	    $studentTable.='</td></tr>';
 4506: 
 4507: 	}
 4508:         $curRes = $iterator->next();
 4509:     }
 4510: 
 4511:     $studentTable.=
 4512:         '</table>'."\n".
 4513:         '<input type="button" value="'.&mt('Save').'" '.
 4514:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 4515:         '</form>'."\n";
 4516:     $request->print($studentTable);
 4517: 
 4518:     return '';
 4519: }
 4520: 
 4521: sub displaySubByDates {
 4522:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 4523:     my $isCODE=0;
 4524:     my $isTask = ($symb =~/\.task$/);
 4525:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 4526:     my $studentTable=&Apache::loncommon::start_data_table().
 4527: 	&Apache::loncommon::start_data_table_header_row().
 4528: 	'<th>'.&mt('Date/Time').'</th>'.
 4529: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 4530: 	'<th>'.&mt('Submission').'</th>'.
 4531: 	'<th>'.&mt('Status').'</th>'.
 4532: 	&Apache::loncommon::end_data_table_header_row();
 4533:     my ($version);
 4534:     my %mark;
 4535:     my %orders;
 4536:     $mark{'correct_by_student'} = $checkIcon;
 4537:     if (!exists($$record{'1:timestamp'})) {
 4538: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 4539:     }
 4540: 
 4541:     my $interaction;
 4542:     my $no_increment = 1;
 4543:     my %lastrndseed;
 4544:     for ($version=1;$version<=$$record{'version'};$version++) {
 4545: 	my $timestamp = 
 4546: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 4547: 	if (exists($$record{$version.':resource.0.version'})) {
 4548: 	    $interaction = $$record{$version.':resource.0.version'};
 4549: 	}
 4550: 
 4551: 	my $where = ($isTask ? "$version:resource.$interaction"
 4552: 		             : "$version:resource");
 4553: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 4554: 	    '<td>'.$timestamp.'</td>';
 4555: 	if ($isCODE) {
 4556: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 4557: 	}
 4558: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 4559: 	my @displaySub = ();
 4560: 	foreach my $partid (@{$parts}) {
 4561:             my ($hidden,$type);
 4562:             $type = $$record{$version.':resource.'.$partid.'.type'};
 4563:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
 4564:                 $hidden = 1;
 4565:             }
 4566: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
 4567: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 4568: 	    
 4569: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 4570: 	    my $display_part=&get_display_part($partid,$symb);
 4571: 	    foreach my $matchKey (@matchKey) {
 4572: 		if (exists($$record{$version.':'.$matchKey}) &&
 4573: 		    $$record{$version.':'.$matchKey} ne '') {
 4574:                     
 4575: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 4576: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 4577:                     $displaySub[0].='<span class="LC_nobreak"';
 4578:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
 4579:                                    .' <span class="LC_internal_info">'
 4580:                                    .'('.&mt('Response ID: [_1]',$responseId).')'
 4581:                                    .'</span>'
 4582:                                    .' <b>';
 4583:                     if ($hidden) {
 4584:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
 4585:                     } else {
 4586:                         my ($trial,$rndseed,$newvariation);
 4587:                         if ($type eq 'randomizetry') {
 4588:                             $trial = $$record{"$where.$partid.tries"};
 4589:                             $rndseed = $$record{"$where.$partid.rndseed"};
 4590:                         }
 4591: 		        if ($$record{"$where.$partid.tries"} eq '') {
 4592: 			    $displaySub[0].=&mt('Trial not counted');
 4593: 		        } else {
 4594: 			    $displaySub[0].=&mt('Trial: [_1]',
 4595: 					    $$record{"$where.$partid.tries"});
 4596:                             if ($rndseed || $lastrndseed{$partid}) {
 4597:                                 if ($rndseed ne $lastrndseed{$partid}) {
 4598:                                     $newvariation = '&nbsp;('.&mt('New variation this try').')';
 4599:                                 }
 4600:                             }
 4601:                             $lastrndseed{$partid} = $rndseed;
 4602: 		        }
 4603: 		        my $responseType=($isTask ? 'Task'
 4604:                                               : $responseType->{$partid}->{$responseId});
 4605: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
 4606: 		        if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
 4607: 			    $orders{$partid}->{$responseId}=
 4608: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
 4609:                                            $no_increment,$type,$trial,$rndseed);
 4610: 		        }
 4611: 		        $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
 4612: 		        $displaySub[0].='&nbsp; '.
 4613: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
 4614:                     }
 4615: 		}
 4616: 	    }
 4617: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 4618: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 4619: 				    $$record{"$where.$partid.checkedin"},
 4620: 				    $$record{"$where.$partid.checkedin.slot"}).
 4621: 					'<br />';
 4622: 	    }
 4623: 	    if (exists $$record{"$where.$partid.award"}) {
 4624: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 4625: 		    lc($$record{"$where.$partid.award"}).' '.
 4626: 		    $mark{$$record{"$where.$partid.solved"}}.
 4627: 		    '<br />';
 4628: 	    }
 4629: 	    if (exists $$record{"$where.$partid.regrader"}) {
 4630: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 4631: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4632: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 4633: 		$displaySub[2].=
 4634: 		    $$record{"$version:resource.$partid.regrader"}.
 4635: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4636: 	    }
 4637: 	}
 4638: 	# needed because old essay regrader has not parts info
 4639: 	if (exists $$record{"$version:resource.regrader"}) {
 4640: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 4641: 	}
 4642: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 4643: 	if ($displaySub[2]) {
 4644: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 4645: 	}
 4646: 	$studentTable.='&nbsp;</td>'.
 4647: 	    &Apache::loncommon::end_data_table_row();
 4648:     }
 4649:     $studentTable.=&Apache::loncommon::end_data_table();
 4650:     return $studentTable;
 4651: }
 4652: 
 4653: sub updateGradeByPage {
 4654:     my ($request,$symb) = @_;
 4655: 
 4656:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4657:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4658:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4659:     my $pageTitle = $env{'form.page'};
 4660:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4661:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4662:     my $usec=$classlist->{$env{'form.student'}}[5];
 4663:     if (!&canmodify($usec)) {
 4664: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 4665: 	return;
 4666:     }
 4667:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4668:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 4669: 	'</h3>'."\n";
 4670: 
 4671:     $request->print($result);
 4672: 
 4673: 
 4674:     my $navmap = Apache::lonnavmaps::navmap->new();
 4675:     unless (ref($navmap)) {
 4676:         $request->print(&navmap_errormsg());
 4677:         return;
 4678:     }
 4679:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 4680:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4681:     if (!$map) {
 4682: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 4683: 	return; 
 4684:     }
 4685:     my $iterator = $navmap->getIterator($map->map_start(),
 4686: 					$map->map_finish());
 4687: 
 4688:     my $studentTable=
 4689: 	&Apache::loncommon::start_data_table().
 4690: 	&Apache::loncommon::start_data_table_header_row().
 4691: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 4692: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 4693: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 4694: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 4695: 	&Apache::loncommon::end_data_table_header_row();
 4696: 
 4697:     $iterator->next(); # skip the first BEGIN_MAP
 4698:     my $curRes = $iterator->next(); # for "current resource"
 4699:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
 4700:     while ($depth > 0) {
 4701:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4702:         if($curRes == $iterator->END_MAP) { $depth--; }
 4703: 
 4704:         if (ref($curRes) && $curRes->is_problem()) {
 4705: 	    my $parts = $curRes->parts();
 4706:             my $title = $curRes->compTitle();
 4707: 	    my $symbx = $curRes->symb();
 4708: 	    $studentTable.=
 4709: 		&Apache::loncommon::start_data_table_row().
 4710: 		'<td align="center" valign="top" >'.$prob.
 4711: 		(scalar(@{$parts}) == 1 ? '' 
 4712:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
 4713: 		.')').'</td>';
 4714: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 4715: 
 4716: 	    my %newrecord=();
 4717: 	    my @displayPts=();
 4718:             my %aggregate = ();
 4719:             my $aggregateflag = 0;
 4720: 	    foreach my $partid (@{$parts}) {
 4721: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 4722: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 4723: 
 4724: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 4725: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 4726: 		my $partial = $newpts/$wgt;
 4727: 		my $score;
 4728: 		if ($partial > 0) {
 4729: 		    $score = 'correct_by_override';
 4730: 		} elsif ($newpts ne '') { #empty is taken as 0
 4731: 		    $score = 'incorrect_by_override';
 4732: 		}
 4733: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 4734: 		if ($dropMenu eq 'excused') {
 4735: 		    $partial = '';
 4736: 		    $score = 'excused';
 4737: 		} elsif ($dropMenu eq 'reset status'
 4738: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 4739: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 4740: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 4741: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 4742: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 4743: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 4744: 		    $changeflag++;
 4745: 		    $newpts = '';
 4746:                     
 4747:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 4748:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 4749:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 4750:                     if ($aggtries > 0) {
 4751:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4752:                         $aggregateflag = 1;
 4753:                     }
 4754: 		}
 4755: 		my $display_part=&get_display_part($partid,$curRes->symb());
 4756: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 4757: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4758: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 4759: 		    '&nbsp;<br />';
 4760: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4761: 		     (($score eq 'excused') ? 'excused' : $newpts).
 4762: 		    '&nbsp;<br />';
 4763: 		$question++;
 4764: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 4765: 
 4766: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 4767: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 4768: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 4769: 		    if (scalar(keys(%newrecord)) > 0);
 4770: 
 4771: 		$changeflag++;
 4772: 	    }
 4773: 	    if (scalar(keys(%newrecord)) > 0) {
 4774: 		my %record = 
 4775: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 4776: 					     $udom,$uname);
 4777: 
 4778: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 4779: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 4780: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 4781: 		    $newrecord{'resource.CODE'} = '';
 4782: 		}
 4783: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 4784: 					$udom,$uname);
 4785: 		%record = &Apache::lonnet::restore($symbx,
 4786: 						   $env{'request.course.id'},
 4787: 						   $udom,$uname);
 4788: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 4789: 					     $cdom,$cnum,$udom,$uname);
 4790: 	    }
 4791: 	    
 4792:             if ($aggregateflag) {
 4793:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4794:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 4795:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 4796:             }
 4797: 
 4798: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 4799: 		'<td valign="top">'.$displayPts[1].'</td>'.
 4800: 		&Apache::loncommon::end_data_table_row();
 4801: 
 4802: 	    $prob++;
 4803: 	}
 4804:         $curRes = $iterator->next();
 4805:     }
 4806: 
 4807:     $studentTable.=&Apache::loncommon::end_data_table();
 4808:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 4809: 		  &mt('The scores were changed for [quant,_1,problem].',
 4810: 		  $changeflag));
 4811:     $request->print($grademsg.$studentTable);
 4812: 
 4813:     return '';
 4814: }
 4815: 
 4816: #-------- end of section for handling grading by page/sequence ---------
 4817: #
 4818: #-------------------------------------------------------------------
 4819: 
 4820: #-------------------- Bubblesheet (Scantron) Grading -------------------
 4821: #
 4822: #------ start of section for handling grading by page/sequence ---------
 4823: 
 4824: =pod
 4825: 
 4826: =head1 Bubble sheet grading routines
 4827: 
 4828:   For this documentation:
 4829: 
 4830:    'scanline' refers to the full line of characters
 4831:    from the file that we are parsing that represents one entire sheet
 4832: 
 4833:    'bubble line' refers to the data
 4834:    representing the line of bubbles that are on the physical bubble sheet
 4835: 
 4836: 
 4837: The overall process is that a scanned in bubble sheet data is uploaded
 4838: into a course. When a user wants to grade, they select a
 4839: sequence/folder of resources, a file of bubble sheet info, and pick
 4840: one of the predefined configurations for what each scanline looks
 4841: like.
 4842: 
 4843: Next each scanline is checked for any errors of either 'missing
 4844: bubbles' (it's an error because it may have been mis-scanned
 4845: because too light bubbling), 'double bubble' (each bubble line should
 4846: have no more that one letter picked), invalid or duplicated CODE,
 4847: invalid student/employee ID
 4848: 
 4849: If the CODE option is used that determines the randomization of the
 4850: homework problems, either way the student/employee ID is looked up into a
 4851: username:domain.
 4852: 
 4853: During the validation phase the instructor can choose to skip scanlines. 
 4854: 
 4855: After the validation phase, there are now 3 bubble sheet files
 4856: 
 4857:   scantron_original_filename (unmodified original file)
 4858:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 4859:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 4860: 
 4861: Also there is a separate hash nohist_scantrondata that contains extra
 4862: correction information that isn't representable in the bubble sheet
 4863: file (see &scantron_getfile() for more information)
 4864: 
 4865: After all scanlines are either valid, marked as valid or skipped, then
 4866: foreach line foreach problem in the picked sequence, an ssi request is
 4867: made that simulates a user submitting their selected letter(s) against
 4868: the homework problem.
 4869: 
 4870: =over 4
 4871: 
 4872: 
 4873: 
 4874: =item defaultFormData
 4875: 
 4876:   Returns html hidden inputs used to hold context/default values.
 4877: 
 4878:  Arguments:
 4879:   $symb - $symb of the current resource 
 4880: 
 4881: =cut
 4882: 
 4883: sub defaultFormData {
 4884:     my ($symb)=@_;
 4885:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />';
 4886: }
 4887: 
 4888: 
 4889: =pod 
 4890: 
 4891: =item getSequenceDropDown
 4892: 
 4893:    Return html dropdown of possible sequences to grade
 4894:  
 4895:  Arguments:
 4896:    $symb - $symb of the current resource
 4897:    $map_error - ref to scalar which will container error if
 4898:                 $navmap object is unavailable in &getSymbMap().
 4899: 
 4900: =cut
 4901: 
 4902: sub getSequenceDropDown {
 4903:     my ($symb,$map_error)=@_;
 4904:     my $result='<select name="selectpage">'."\n";
 4905:     my ($titles,$symbx) = &getSymbMap($map_error);
 4906:     if (ref($map_error)) {
 4907:         return if ($$map_error);
 4908:     }
 4909:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 4910:     my $ctr=0;
 4911:     foreach (@$titles) {
 4912: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4913: 	$result.='<option value="'.$$symbx{$_}.'" '.
 4914: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4915: 	    '>'.$showtitle.'</option>'."\n";
 4916: 	$ctr++;
 4917:     }
 4918:     $result.= '</select>';
 4919:     return $result;
 4920: }
 4921: 
 4922: my %bubble_lines_per_response;     # no. bubble lines for each response.
 4923:                                    # key is zero-based index - 0, 1, 2 ...
 4924: 
 4925: my %first_bubble_line;             # First bubble line no. for each bubble.
 4926: 
 4927: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 4928:                                    # matchresponse or rankresponse, where 
 4929:                                    # an individual response can have multiple 
 4930:                                    # lines
 4931: 
 4932: my %responsetype_per_response;     # responsetype for each response
 4933: 
 4934: # Save and restore the bubble lines array to the form env.
 4935: 
 4936: 
 4937: sub save_bubble_lines {
 4938:     foreach my $line (keys(%bubble_lines_per_response)) {
 4939: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 4940: 	$env{"form.scantron.first_bubble_line.$line"} =
 4941: 	    $first_bubble_line{$line};
 4942:         $env{"form.scantron.sub_bubblelines.$line"} = 
 4943:             $subdivided_bubble_lines{$line};
 4944:         $env{"form.scantron.responsetype.$line"} =
 4945:             $responsetype_per_response{$line};
 4946:     }
 4947: }
 4948: 
 4949: 
 4950: sub restore_bubble_lines {
 4951:     my $line = 0;
 4952:     %bubble_lines_per_response = ();
 4953:     while ($env{"form.scantron.bubblelines.$line"}) {
 4954: 	my $value = $env{"form.scantron.bubblelines.$line"};
 4955: 	$bubble_lines_per_response{$line} = $value;
 4956: 	$first_bubble_line{$line}  =
 4957: 	    $env{"form.scantron.first_bubble_line.$line"};
 4958:         $subdivided_bubble_lines{$line} =
 4959:             $env{"form.scantron.sub_bubblelines.$line"};
 4960:         $responsetype_per_response{$line} =
 4961:             $env{"form.scantron.responsetype.$line"};
 4962: 	$line++;
 4963:     }
 4964: }
 4965: 
 4966: #  Given the parsed scanline, get the response for 
 4967: #  'answer' number n:
 4968: 
 4969: sub get_response_bubbles {
 4970:     my ($parsed_line, $response)  = @_;
 4971: 
 4972:     my $bubble_line = $first_bubble_line{$response-1} +1;
 4973:     my $bubble_lines= $bubble_lines_per_response{$response-1};
 4974:     
 4975:     my $selected = "";
 4976: 
 4977:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
 4978: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
 4979: 	$bubble_line++;
 4980:     }
 4981:     return $selected;
 4982: }
 4983: 
 4984: =pod 
 4985: 
 4986: =item scantron_filenames
 4987: 
 4988:    Returns a list of the scantron files in the current course 
 4989: 
 4990: =cut
 4991: 
 4992: sub scantron_filenames {
 4993:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4994:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4995:     my $getpropath = 1;
 4996:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
 4997:                                        $getpropath);
 4998:     my @possiblenames;
 4999:     foreach my $filename (sort(@files)) {
 5000: 	($filename)=split(/&/,$filename);
 5001: 	if ($filename!~/^scantron_orig_/) { next ; }
 5002: 	$filename=~s/^scantron_orig_//;
 5003: 	push(@possiblenames,$filename);
 5004:     }
 5005:     return @possiblenames;
 5006: }
 5007: 
 5008: =pod 
 5009: 
 5010: =item scantron_uploads
 5011: 
 5012:    Returns  html drop-down list of scantron files in current course.
 5013: 
 5014:  Arguments:
 5015:    $file2grade - filename to set as selected in the dropdown
 5016: 
 5017: =cut
 5018: 
 5019: sub scantron_uploads {
 5020:     my ($file2grade) = @_;
 5021:     my $result=	'<select name="scantron_selectfile">';
 5022:     $result.="<option></option>";
 5023:     foreach my $filename (sort(&scantron_filenames())) {
 5024: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 5025:     }
 5026:     $result.="</select>";
 5027:     return $result;
 5028: }
 5029: 
 5030: =pod 
 5031: 
 5032: =item scantron_scantab
 5033: 
 5034:   Returns html drop down of the scantron formats in the scantronformat.tab
 5035:   file.
 5036: 
 5037: =cut
 5038: 
 5039: sub scantron_scantab {
 5040:     my $result='<select name="scantron_format">'."\n";
 5041:     $result.='<option></option>'."\n";
 5042:     my @lines = &get_scantronformat_file();
 5043:     if (@lines > 0) {
 5044:         foreach my $line (@lines) {
 5045:             next if (($line =~ /^\#/) || ($line eq ''));
 5046: 	    my ($name,$descrip)=split(/:/,$line);
 5047: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 5048:         }
 5049:     }
 5050:     $result.='</select>'."\n";
 5051:     return $result;
 5052: }
 5053: 
 5054: =pod
 5055: 
 5056: =item get_scantronformat_file
 5057: 
 5058:   Returns an array containing lines from the scantron format file for
 5059:   the domain of the course.
 5060: 
 5061:   If a url for a custom.tab file is listed in domain's configuration.db, 
 5062:   lines are from this file.
 5063: 
 5064:   Otherwise, if a default.tab has been published in RES space by the 
 5065:   domainconfig user, lines are from this file.
 5066: 
 5067:   Otherwise, fall back to getting lines from the legacy file on the
 5068:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
 5069: 
 5070: =cut
 5071: 
 5072: sub get_scantronformat_file {
 5073:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5074:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
 5075:     my $gottab = 0;
 5076:     my @lines;
 5077:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 5078:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 5079:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 5080:             if ($formatfile ne '-1') {
 5081:                 @lines = split("\n",$formatfile,-1);
 5082:                 $gottab = 1;
 5083:             }
 5084:         }
 5085:     }
 5086:     if (!$gottab) {
 5087:         my $confname = $cdom.'-domainconfig';
 5088:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 5089:         my $formatfile =  &Apache::lonnet::getfile($default);
 5090:         if ($formatfile ne '-1') {
 5091:             @lines = split("\n",$formatfile,-1);
 5092:             $gottab = 1;
 5093:         }
 5094:     }
 5095:     if (!$gottab) {
 5096:         my @domains = &Apache::lonnet::current_machine_domains();
 5097:         if (grep(/^\Q$cdom\E$/,@domains)) {
 5098:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 5099:             @lines = <$fh>;
 5100:             close($fh);
 5101:         } else {
 5102:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
 5103:             @lines = <$fh>;
 5104:             close($fh);
 5105:         }
 5106:     }
 5107:     return @lines;
 5108: }
 5109: 
 5110: =pod 
 5111: 
 5112: =item scantron_CODElist
 5113: 
 5114:   Returns html drop down of the saved CODE lists from current course,
 5115:   generated from earlier printings.
 5116: 
 5117: =cut
 5118: 
 5119: sub scantron_CODElist {
 5120:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5121:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5122:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 5123:     my $namechoice='<option></option>';
 5124:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 5125: 	if ($name =~ /^error: 2 /) { next; }
 5126: 	if ($name =~ /^type\0/) { next; }
 5127: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 5128:     }
 5129:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 5130:     return $namechoice;
 5131: }
 5132: 
 5133: =pod 
 5134: 
 5135: =item scantron_CODEunique
 5136: 
 5137:   Returns the html for "Each CODE to be used once" radio.
 5138: 
 5139: =cut
 5140: 
 5141: sub scantron_CODEunique {
 5142:     my $result='<span class="LC_nobreak">
 5143:                  <label><input type="radio" name="scantron_CODEunique"
 5144:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 5145:                 </span>
 5146:                 <span class="LC_nobreak">
 5147:                  <label><input type="radio" name="scantron_CODEunique"
 5148:                         value="no" />'.&mt('No').' </label>
 5149:                 </span>';
 5150:     return $result;
 5151: }
 5152: 
 5153: =pod 
 5154: 
 5155: =item scantron_selectphase
 5156: 
 5157:   Generates the initial screen to start the bubble sheet process.
 5158:   Allows for - starting a grading run.
 5159:              - downloading existing scan data (original, corrected
 5160:                                                 or skipped info)
 5161: 
 5162:              - uploading new scan data
 5163: 
 5164:  Arguments:
 5165:   $r          - The Apache request object
 5166:   $file2grade - name of the file that contain the scanned data to score
 5167: 
 5168: =cut
 5169: 
 5170: sub scantron_selectphase {
 5171:     my ($r,$file2grade,$symb) = @_;
 5172:     if (!$symb) {return '';}
 5173:     my $map_error;
 5174:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
 5175:     if ($map_error) {
 5176:         $r->print('<br />'.&navmap_errormsg().'<br />');
 5177:         return;
 5178:     }
 5179:     my $default_form_data=&defaultFormData($symb);
 5180:     my $file_selector=&scantron_uploads($file2grade);
 5181:     my $format_selector=&scantron_scantab();
 5182:     my $CODE_selector=&scantron_CODElist();
 5183:     my $CODE_unique=&scantron_CODEunique();
 5184:     my $result;
 5185: 
 5186:     $ssi_error = 0;
 5187: 
 5188:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 5189:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 5190: 
 5191: 	# Chunk of form to prompt for a scantron file upload.
 5192: 
 5193:         $r->print('
 5194:     <br />
 5195:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5196:        '.&Apache::loncommon::start_data_table_header_row().'
 5197:             <th>
 5198:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
 5199:             </th>
 5200:        '.&Apache::loncommon::end_data_table_header_row().'
 5201:        '.&Apache::loncommon::start_data_table_row().'
 5202:             <td>
 5203: ');
 5204:     my $default_form_data=&defaultFormData($symb);
 5205:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5206:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 5207:     $r->print(&Apache::lonhtmlcommon::scripttag('
 5208:     function checkUpload(formname) {
 5209: 	if (formname.upfile.value == "") {
 5210: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
 5211: 	    return false;
 5212: 	}
 5213: 	formname.submit();
 5214:     }'));
 5215:     $r->print('
 5216:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 5217:                 '.$default_form_data.'
 5218:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 5219:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 5220:                 <input name="command" value="scantronupload_save" type="hidden" />
 5221:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
 5222:                 <br />
 5223:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 5224:               </form>
 5225: ');
 5226: 
 5227:         $r->print('
 5228:             </td>
 5229:        '.&Apache::loncommon::end_data_table_row().'
 5230:        '.&Apache::loncommon::end_data_table().'
 5231: ');
 5232:     }
 5233: 
 5234:     # Chunk of form to prompt for a file to grade and how:
 5235: 
 5236:     $result.= '
 5237:     <br />
 5238:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 5239:     <input type="hidden" name="command" value="scantron_warning" />
 5240:     '.$default_form_data.'
 5241:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5242:        '.&Apache::loncommon::start_data_table_header_row().'
 5243:             <th colspan="2">
 5244:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 5245:             </th>
 5246:        '.&Apache::loncommon::end_data_table_header_row().'
 5247:        '.&Apache::loncommon::start_data_table_row().'
 5248:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 5249:        '.&Apache::loncommon::end_data_table_row().'
 5250:        '.&Apache::loncommon::start_data_table_row().'
 5251:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
 5252:        '.&Apache::loncommon::end_data_table_row().'
 5253:        '.&Apache::loncommon::start_data_table_row().'
 5254:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
 5255:        '.&Apache::loncommon::end_data_table_row().'
 5256:        '.&Apache::loncommon::start_data_table_row().'
 5257:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 5258:        '.&Apache::loncommon::end_data_table_row().'
 5259:        '.&Apache::loncommon::start_data_table_row().'
 5260:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 5261:        '.&Apache::loncommon::end_data_table_row().'
 5262:        '.&Apache::loncommon::start_data_table_row().'
 5263: 	    <td> '.&mt('Options:').' </td>
 5264:             <td>
 5265: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 5266:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 5267:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 5268: 	    </td>
 5269:        '.&Apache::loncommon::end_data_table_row().'
 5270:        '.&Apache::loncommon::start_data_table_row().'
 5271:             <td colspan="2">
 5272:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
 5273:             </td>
 5274:        '.&Apache::loncommon::end_data_table_row().'
 5275:     '.&Apache::loncommon::end_data_table().'
 5276:     </form>
 5277: ';
 5278:    
 5279:     $r->print($result);
 5280: 
 5281: 
 5282: 
 5283:     # Chunk of the form that prompts to view a scoring office file,
 5284:     # corrected file, skipped records in a file.
 5285: 
 5286:     $r->print('
 5287:    <br />
 5288:    <form action="/adm/grades" name="scantron_download">
 5289:      '.$default_form_data.'
 5290:      <input type="hidden" name="command" value="scantron_download" />
 5291:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5292:        '.&Apache::loncommon::start_data_table_header_row().'
 5293:               <th>
 5294:                 &nbsp;'.&mt('Download a scoring office file').'
 5295:               </th>
 5296:        '.&Apache::loncommon::end_data_table_header_row().'
 5297:        '.&Apache::loncommon::start_data_table_row().'
 5298:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 5299:                 <br />
 5300:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 5301:        '.&Apache::loncommon::end_data_table_row().'
 5302:      '.&Apache::loncommon::end_data_table().'
 5303:    </form>
 5304:    <br />
 5305: ');
 5306: 
 5307:     &Apache::lonpickcode::code_list($r,2);
 5308: 
 5309:     $r->print('<br /><form method="post" name="checkscantron">'.
 5310:              $default_form_data."\n".
 5311:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 5312:              &Apache::loncommon::start_data_table_header_row()."\n".
 5313:              '<th colspan="2">
 5314:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
 5315:              '</th>'."\n".
 5316:               &Apache::loncommon::end_data_table_header_row()."\n".
 5317:               &Apache::loncommon::start_data_table_row()."\n".
 5318:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 5319:               '<td> '.$sequence_selector.' </td>'.
 5320:               &Apache::loncommon::end_data_table_row()."\n".
 5321:               &Apache::loncommon::start_data_table_row()."\n".
 5322:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 5323:               '<td> '.$file_selector.' </td>'."\n".
 5324:               &Apache::loncommon::end_data_table_row()."\n".
 5325:               &Apache::loncommon::start_data_table_row()."\n".
 5326:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 5327:               '<td> '.$format_selector.' </td>'."\n".
 5328:               &Apache::loncommon::end_data_table_row()."\n".
 5329:               &Apache::loncommon::start_data_table_row()."\n".
 5330:               '<td> '.&mt('Options').' </td>'."\n".
 5331:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
 5332:               &Apache::loncommon::end_data_table_row()."\n".
 5333:               &Apache::loncommon::start_data_table_row()."\n".
 5334:               '<td colspan="2">'."\n".
 5335:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 5336:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
 5337:               '</td>'."\n".
 5338:               &Apache::loncommon::end_data_table_row()."\n".
 5339:               &Apache::loncommon::end_data_table()."\n".
 5340:               '</form><br />');
 5341:     return;
 5342: }
 5343: 
 5344: =pod
 5345: 
 5346: =item get_scantron_config
 5347: 
 5348:    Parse and return the scantron configuration line selected as a
 5349:    hash of configuration file fields.
 5350: 
 5351:  Arguments:
 5352:     which - the name of the configuration to parse from the file.
 5353: 
 5354: 
 5355:  Returns:
 5356:             If the named configuration is not in the file, an empty
 5357:             hash is returned.
 5358:     a hash with the fields
 5359:       name         - internal name for the this configuration setup
 5360:       description  - text to display to operator that describes this config
 5361:       CODElocation - if 0 or the string 'none'
 5362:                           - no CODE exists for this config
 5363:                      if -1 || the string 'letter'
 5364:                           - a CODE exists for this config and is
 5365:                             a string of letters
 5366:                      Unsupported value (but planned for future support)
 5367:                           if a positive integer
 5368:                                - The CODE exists as the first n items from
 5369:                                  the question section of the form
 5370:                           if the string 'number'
 5371:                                - The CODE exists for this config and is
 5372:                                  a string of numbers
 5373:       CODEstart   - (only matter if a CODE exists) column in the line where
 5374:                      the CODE starts
 5375:       CODElength  - length of the CODE
 5376:       IDstart     - column where the student/employee ID starts
 5377:       IDlength    - length of the student/employee ID info
 5378:       Qstart      - column where the information from the bubbled
 5379:                     'questions' start
 5380:       Qlength     - number of columns comprising a single bubble line from
 5381:                     the sheet. (usually either 1 or 10)
 5382:       Qon         - either a single character representing the character used
 5383:                     to signal a bubble was chosen in the positional setup, or
 5384:                     the string 'letter' if the letter of the chosen bubble is
 5385:                     in the final, or 'number' if a number representing the
 5386:                     chosen bubble is in the file (1->A 0->J)
 5387:       Qoff        - the character used to represent that a bubble was
 5388:                     left blank
 5389:       PaperID     - if the scanning process generates a unique number for each
 5390:                     sheet scanned the column that this ID number starts in
 5391:       PaperIDlength - number of columns that comprise the unique ID number
 5392:                       for the sheet of paper
 5393:       FirstName   - column that the first name starts in
 5394:       FirstNameLength - number of columns that the first name spans
 5395:  
 5396:       LastName    - column that the last name starts in
 5397:       LastNameLength - number of columns that the last name spans
 5398:       BubblesPerRow - number of bubbles available in each row used to 
 5399:                       bubble an answer. (If not specified, 10 assumed).
 5400: =cut
 5401: 
 5402: sub get_scantron_config {
 5403:     my ($which) = @_;
 5404:     my @lines = &get_scantronformat_file();
 5405:     my %config;
 5406:     #FIXME probably should move to XML it has already gotten a bit much now
 5407:     foreach my $line (@lines) {
 5408: 	my ($name,$descrip)=split(/:/,$line);
 5409: 	if ($name ne $which ) { next; }
 5410: 	chomp($line);
 5411: 	my @config=split(/:/,$line);
 5412: 	$config{'name'}=$config[0];
 5413: 	$config{'description'}=$config[1];
 5414: 	$config{'CODElocation'}=$config[2];
 5415: 	$config{'CODEstart'}=$config[3];
 5416: 	$config{'CODElength'}=$config[4];
 5417: 	$config{'IDstart'}=$config[5];
 5418: 	$config{'IDlength'}=$config[6];
 5419: 	$config{'Qstart'}=$config[7];
 5420:  	$config{'Qlength'}=$config[8];
 5421: 	$config{'Qoff'}=$config[9];
 5422: 	$config{'Qon'}=$config[10];
 5423: 	$config{'PaperID'}=$config[11];
 5424: 	$config{'PaperIDlength'}=$config[12];
 5425: 	$config{'FirstName'}=$config[13];
 5426: 	$config{'FirstNamelength'}=$config[14];
 5427: 	$config{'LastName'}=$config[15];
 5428: 	$config{'LastNamelength'}=$config[16];
 5429:         $config{'BubblesPerRow'}=$config[17];
 5430: 	last;
 5431:     }
 5432:     return %config;
 5433: }
 5434: 
 5435: =pod 
 5436: 
 5437: =item username_to_idmap
 5438: 
 5439:     creates a hash keyed by student/employee ID with values of the corresponding
 5440:     student username:domain.
 5441: 
 5442:   Arguments:
 5443: 
 5444:     $classlist - reference to the class list hash. This is a hash
 5445:                  keyed by student name:domain  whose elements are references
 5446:                  to arrays containing various chunks of information
 5447:                  about the student. (See loncoursedata for more info).
 5448: 
 5449:   Returns
 5450:     %idmap - the constructed hash
 5451: 
 5452: =cut
 5453: 
 5454: sub username_to_idmap {
 5455:     my ($classlist)= @_;
 5456:     my %idmap;
 5457:     foreach my $student (keys(%$classlist)) {
 5458: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
 5459: 	    $student;
 5460:     }
 5461:     return %idmap;
 5462: }
 5463: 
 5464: =pod
 5465: 
 5466: =item scantron_fixup_scanline
 5467: 
 5468:    Process a requested correction to a scanline.
 5469: 
 5470:   Arguments:
 5471:     $scantron_config   - hash from &get_scantron_config()
 5472:     $scan_data         - hash of correction information 
 5473:                           (see &scantron_getfile())
 5474:     $line              - existing scanline
 5475:     $whichline         - line number of the passed in scanline
 5476:     $field             - type of change to process 
 5477:                          (either 
 5478:                           'ID'     -> correct the student/employee ID
 5479:                           'CODE'   -> correct the CODE
 5480:                           'answer' -> fixup the submitted answers)
 5481:     
 5482:    $args               - hash of additional info,
 5483:                           - 'ID' 
 5484:                                'newid' -> studentID to use in replacement
 5485:                                           of existing one
 5486:                           - 'CODE' 
 5487:                                'CODE_ignore_dup' - set to true if duplicates
 5488:                                                    should be ignored.
 5489: 	                       'CODE' - is new code or 'use_unfound'
 5490:                                         if the existing unfound code should
 5491:                                         be used as is
 5492:                           - 'answer'
 5493:                                'response' - new answer or 'none' if blank
 5494:                                'question' - the bubble line to change
 5495:                                'questionnum' - the question identifier,
 5496:                                                may include subquestion. 
 5497: 
 5498:   Returns:
 5499:     $line - the modified scanline
 5500: 
 5501:   Side effects: 
 5502:     $scan_data - may be updated
 5503: 
 5504: =cut
 5505: 
 5506: 
 5507: sub scantron_fixup_scanline {
 5508:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 5509:     if ($field eq 'ID') {
 5510: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 5511: 	    return ($line,1,'New value too large');
 5512: 	}
 5513: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 5514: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 5515: 				     $args->{'newid'});
 5516: 	}
 5517: 	substr($line,$$scantron_config{'IDstart'}-1,
 5518: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 5519: 	if ($args->{'newid'}=~/^\s*$/) {
 5520: 	    &scan_data($scan_data,"$whichline.user",
 5521: 		       $args->{'username'}.':'.$args->{'domain'});
 5522: 	}
 5523:     } elsif ($field eq 'CODE') {
 5524: 	if ($args->{'CODE_ignore_dup'}) {
 5525: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 5526: 	}
 5527: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 5528: 	if ($args->{'CODE'} ne 'use_unfound') {
 5529: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 5530: 		return ($line,1,'New CODE value too large');
 5531: 	    }
 5532: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 5533: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 5534: 	    }
 5535: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 5536: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 5537: 	}
 5538:     } elsif ($field eq 'answer') {
 5539: 	my $length=$scantron_config->{'Qlength'};
 5540: 	my $off=$scantron_config->{'Qoff'};
 5541: 	my $on=$scantron_config->{'Qon'};
 5542: 	my $answer=${off}x$length;
 5543: 	if ($args->{'response'} eq 'none') {
 5544: 	    &scan_data($scan_data,
 5545: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 5546: 	} else {
 5547: 	    if ($on eq 'letter') {
 5548: 		my @alphabet=('A'..'Z');
 5549: 		$answer=$alphabet[$args->{'response'}];
 5550: 	    } elsif ($on eq 'number') {
 5551: 		$answer=$args->{'response'}+1;
 5552: 		if ($answer == 10) { $answer = '0'; }
 5553: 	    } else {
 5554: 		substr($answer,$args->{'response'},1)=$on;
 5555: 	    }
 5556: 	    &scan_data($scan_data,
 5557: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 5558: 	}
 5559: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 5560: 	substr($line,$where-1,$length)=$answer;
 5561:     }
 5562:     return $line;
 5563: }
 5564: 
 5565: =pod
 5566: 
 5567: =item scan_data
 5568: 
 5569:     Edit or look up  an item in the scan_data hash.
 5570: 
 5571:   Arguments:
 5572:     $scan_data  - The hash (see scantron_getfile)
 5573:     $key        - shorthand of the key to edit (actual key is
 5574:                   scantronfilename_key).
 5575:     $data        - New value of the hash entry.
 5576:     $delete      - If true, the entry is removed from the hash.
 5577: 
 5578:   Returns:
 5579:     The new value of the hash table field (undefined if deleted).
 5580: 
 5581: =cut
 5582: 
 5583: 
 5584: sub scan_data {
 5585:     my ($scan_data,$key,$value,$delete)=@_;
 5586:     my $filename=$env{'form.scantron_selectfile'};
 5587:     if (defined($value)) {
 5588: 	$scan_data->{$filename.'_'.$key} = $value;
 5589:     }
 5590:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 5591:     return $scan_data->{$filename.'_'.$key};
 5592: }
 5593: 
 5594: # ----- These first few routines are general use routines.----
 5595: 
 5596: # Return the number of occurences of a pattern in a string.
 5597: 
 5598: sub occurence_count {
 5599:     my ($string, $pattern) = @_;
 5600: 
 5601:     my @matches = ($string =~ /$pattern/g);
 5602: 
 5603:     return scalar(@matches);
 5604: }
 5605: 
 5606: 
 5607: # Take a string known to have digits and convert all the
 5608: # digits into letters in the range J,A..I.
 5609: 
 5610: sub digits_to_letters {
 5611:     my ($input) = @_;
 5612: 
 5613:     my @alphabet = ('J', 'A'..'I');
 5614: 
 5615:     my @input    = split(//, $input);
 5616:     my $output ='';
 5617:     for (my $i = 0; $i < scalar(@input); $i++) {
 5618: 	if ($input[$i] =~ /\d/) {
 5619: 	    $output .= $alphabet[$input[$i]];
 5620: 	} else {
 5621: 	    $output .= $input[$i];
 5622: 	}
 5623:     }
 5624:     return $output;
 5625: }
 5626: 
 5627: =pod 
 5628: 
 5629: =item scantron_parse_scanline
 5630: 
 5631:   Decodes a scanline from the selected scantron file
 5632: 
 5633:  Arguments:
 5634:     line             - The text of the scantron file line to process
 5635:     whichline        - Line number
 5636:     scantron_config  - Hash describing the format of the scantron lines.
 5637:     scan_data        - Hash of extra information about the scanline
 5638:                        (see scantron_getfile for more information)
 5639:     just_header      - True if should not process question answers but only
 5640:                        the stuff to the left of the answers.
 5641:  Returns:
 5642:    Hash containing the result of parsing the scanline
 5643: 
 5644:    Keys are all proceeded by the string 'scantron.'
 5645: 
 5646:        CODE    - the CODE in use for this scanline
 5647:        useCODE - 1 if the CODE is invalid but it usage has been forced
 5648:                  by the operator
 5649:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 5650:                             CODEs were selected, but the usage has been
 5651:                             forced by the operator
 5652:        ID  - student/employee ID
 5653:        PaperID - if used, the ID number printed on the sheet when the 
 5654:                  paper was scanned
 5655:        FirstName - first name from the sheet
 5656:        LastName  - last name from the sheet
 5657: 
 5658:      if just_header was not true these key may also exist
 5659: 
 5660:        missingerror - a list of bubble ranges that are considered to be answers
 5661:                       to a single question that don't have any bubbles filled in.
 5662:                       Of the form questionnumber:firstbubblenumber:count.
 5663:        doubleerror  - a list of bubble ranges that are considered to be answers
 5664:                       to a single question that have more than one bubble filled in.
 5665:                       Of the form questionnumber::firstbubblenumber:count
 5666:    
 5667:                 In the above, count is the number of bubble responses in the
 5668:                 input line needed to represent the possible answers to the question.
 5669:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 5670:                 per line would have count = 2.
 5671: 
 5672:        maxquest     - the number of the last bubble line that was parsed
 5673: 
 5674:        (<number> starts at 1)
 5675:        <number>.answer - zero or more letters representing the selected
 5676:                          letters from the scanline for the bubble line 
 5677:                          <number>.
 5678:                          if blank there was either no bubble or there where
 5679:                          multiple bubbles, (consult the keys missingerror and
 5680:                          doubleerror if this is an error condition)
 5681: 
 5682: =cut
 5683: 
 5684: sub scantron_parse_scanline {
 5685:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
 5686: 
 5687:     my %record;
 5688:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 5689:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 5690:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
 5691:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 5692: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 5693: 	if ($$scantron_config{'CODElocation'} < 0 ||
 5694: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 5695: 	    $$scantron_config{'CODElocation'} eq 'number') {
 5696: 	    $record{'scantron.CODE'}=substr($data,
 5697: 					    $$scantron_config{'CODEstart'}-1,
 5698: 					    $$scantron_config{'CODElength'});
 5699: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 5700: 		$record{'scantron.useCODE'}=1;
 5701: 	    }
 5702: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 5703: 		$record{'scantron.CODE_ignore_dup'}=1;
 5704: 	    }
 5705: 	} else {
 5706: 	    #FIXME interpret first N questions
 5707: 	}
 5708:     }
 5709:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 5710: 				  $$scantron_config{'IDlength'});
 5711:     $record{'scantron.PaperID'}=
 5712: 	substr($data,$$scantron_config{'PaperID'}-1,
 5713: 	       $$scantron_config{'PaperIDlength'});
 5714:     $record{'scantron.FirstName'}=
 5715: 	substr($data,$$scantron_config{'FirstName'}-1,
 5716: 	       $$scantron_config{'FirstNamelength'});
 5717:     $record{'scantron.LastName'}=
 5718: 	substr($data,$$scantron_config{'LastName'}-1,
 5719: 	       $$scantron_config{'LastNamelength'});
 5720:     if ($just_header) { return \%record; }
 5721: 
 5722:     my @alphabet=('A'..'Z');
 5723:     my $questnum=0;
 5724:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 5725: 
 5726:     chomp($questions);		# Get rid of any trailing \n.
 5727:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 5728:     while (length($questions)) {
 5729: 	my $answers_needed = $bubble_lines_per_response{$questnum};
 5730:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 5731:                              || 1;
 5732:         $questnum++;
 5733:         my $quest_id = $questnum;
 5734:         my $currentquest = substr($questions,0,$answer_length);
 5735:         $questions       = substr($questions,$answer_length);
 5736:         if (length($currentquest) < $answer_length) { next; }
 5737: 
 5738:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
 5739:             my $subquestnum = 1;
 5740:             my $subquestions = $currentquest;
 5741:             my @subanswers_needed = 
 5742:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
 5743:             foreach my $subans (@subanswers_needed) {
 5744:                 my $subans_length =
 5745:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 5746:                 my $currsubquest = substr($subquestions,0,$subans_length);
 5747:                 $subquestions   = substr($subquestions,$subans_length);
 5748:                 $quest_id = "$questnum.$subquestnum";
 5749:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 5750:                     ($$scantron_config{'Qon'} eq 'number')) {
 5751:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 5752:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 5753:                         \@alphabet,\%record,$scantron_config,$scan_data);
 5754:                 } else {
 5755:                     $ansnum = &scantron_validator_positional($ansnum,
 5756:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
 5757:                 }
 5758:                 $subquestnum ++;
 5759:             }
 5760:         } else {
 5761:             if (($$scantron_config{'Qon'} eq 'letter') ||
 5762:                 ($$scantron_config{'Qon'} eq 'number')) {
 5763:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 5764:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5765:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5766:             } else {
 5767:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 5768:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5769:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5770:             }
 5771:         }
 5772:     }
 5773:     $record{'scantron.maxquest'}=$questnum;
 5774:     return \%record;
 5775: }
 5776: 
 5777: sub scantron_validator_lettnum {
 5778:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 5779:         $alphabet,$record,$scantron_config,$scan_data) = @_;
 5780: 
 5781:     # Qon 'letter' implies for each slot in currquest we have:
 5782:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 5783:     #    about anything else (esp. a value of Qoff) for missing
 5784:     #    bubbles.
 5785:     #
 5786:     # Qon 'number' implies each slot gives a digit that indexes the
 5787:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 5788:     #    and * or ? for double bubbles on a single line.
 5789:     #
 5790: 
 5791:     my $matchon;
 5792:     if ($$scantron_config{'Qon'} eq 'letter') {
 5793:         $matchon = '[A-Z]';
 5794:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 5795:         $matchon = '\d';
 5796:     }
 5797:     my $occurrences = 0;
 5798:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5799:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5800:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5801:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5802:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5803:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5804:         my @singlelines = split('',$currquest);
 5805:         foreach my $entry (@singlelines) {
 5806:             $occurrences = &occurence_count($entry,$matchon);
 5807:             if ($occurrences > 1) {
 5808:                 last;
 5809:             }
 5810:         } 
 5811:     } else {
 5812:         $occurrences = &occurence_count($currquest,$matchon); 
 5813:     }
 5814:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 5815:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5816:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5817:             my $bubble = substr($currquest,$ans,1);
 5818:             if ($bubble =~ /$matchon/ ) {
 5819:                 if ($$scantron_config{'Qon'} eq 'number') {
 5820:                     if ($bubble == 0) {
 5821:                         $bubble = 10; 
 5822:                     }
 5823:                     $record->{"scantron.$ansnum.answer"} = 
 5824:                         $alphabet->[$bubble-1];
 5825:                 } else {
 5826:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 5827:                 }
 5828:             } else {
 5829:                 $record->{"scantron.$ansnum.answer"}='';
 5830:             }
 5831:             $ansnum++;
 5832:         }
 5833:     } elsif (!defined($currquest)
 5834:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 5835:             || (&occurence_count($currquest,$matchon) == 0)) {
 5836:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5837:             $record->{"scantron.$ansnum.answer"}='';
 5838:             $ansnum++;
 5839:         }
 5840:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5841:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 5842:         }
 5843:     } else {
 5844:         if ($$scantron_config{'Qon'} eq 'number') {
 5845:             $currquest = &digits_to_letters($currquest);            
 5846:         }
 5847:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5848:             my $bubble = substr($currquest,$ans,1);
 5849:             $record->{"scantron.$ansnum.answer"} = $bubble;
 5850:             $ansnum++;
 5851:         }
 5852:     }
 5853:     return $ansnum;
 5854: }
 5855: 
 5856: sub scantron_validator_positional {
 5857:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 5858:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
 5859: 
 5860:     # Otherwise there's a positional notation;
 5861:     # each bubble line requires Qlength items, and there are filled in
 5862:     # bubbles for each case where there 'Qon' characters.
 5863:     #
 5864: 
 5865:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 5866: 
 5867:     # If the split only gives us one element.. the full length of the
 5868:     # answer string, no bubbles are filled in:
 5869: 
 5870:     if ($answers_needed eq '') {
 5871:         return;
 5872:     }
 5873: 
 5874:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 5875:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5876:             $record->{"scantron.$ansnum.answer"}='';
 5877:             $ansnum++;
 5878:         }
 5879:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5880:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 5881:         }
 5882:     } elsif (scalar(@array) == 2) {
 5883:         my $location = length($array[0]);
 5884:         my $line_num = int($location / $$scantron_config{'Qlength'});
 5885:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 5886:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5887:             if ($ans eq $line_num) {
 5888:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 5889:             } else {
 5890:                 $record->{"scantron.$ansnum.answer"} = ' ';
 5891:             }
 5892:             $ansnum++;
 5893:          }
 5894:     } else {
 5895:         #  If there's more than one instance of a bubble character
 5896:         #  That's a double bubble; with positional notation we can
 5897:         #  record all the bubbles filled in as well as the
 5898:         #  fact this response consists of multiple bubbles.
 5899:         #
 5900:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5901:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5902:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5903:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5904:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5905:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5906:             my $doubleerror = 0;
 5907:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 5908:                    (!$doubleerror)) {
 5909:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 5910:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 5911:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 5912:                if (length(@currarray) > 2) {
 5913:                    $doubleerror = 1;
 5914:                } 
 5915:             }
 5916:             if ($doubleerror) {
 5917:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5918:             }
 5919:         } else {
 5920:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5921:         }
 5922:         my $item = $ansnum;
 5923:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5924:             $record->{"scantron.$item.answer"} = '';
 5925:             $item ++;
 5926:         }
 5927: 
 5928:         my @ans=@array;
 5929:         my $i=0;
 5930:         my $increment = 0;
 5931:         while ($#ans) {
 5932:             $i+=length($ans[0]) + $increment;
 5933:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 5934:             my $bubble = $i%$$scantron_config{'Qlength'};
 5935:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 5936:             shift(@ans);
 5937:             $increment = 1;
 5938:         }
 5939:         $ansnum += $answers_needed;
 5940:     }
 5941:     return $ansnum;
 5942: }
 5943: 
 5944: =pod
 5945: 
 5946: =item scantron_add_delay
 5947: 
 5948:    Adds an error message that occurred during the grading phase to a
 5949:    queue of messages to be shown after grading pass is complete
 5950: 
 5951:  Arguments:
 5952:    $delayqueue  - arrary ref of hash ref of error messages
 5953:    $scanline    - the scanline that caused the error
 5954:    $errormesage - the error message
 5955:    $errorcode   - a numeric code for the error
 5956: 
 5957:  Side Effects:
 5958:    updates the $delayqueue to have a new hash ref of the error
 5959: 
 5960: =cut
 5961: 
 5962: sub scantron_add_delay {
 5963:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 5964:     push(@$delayqueue,
 5965: 	 {'line' => $scanline, 'emsg' => $errormessage,
 5966: 	  'ecode' => $errorcode }
 5967: 	 );
 5968: }
 5969: 
 5970: =pod
 5971: 
 5972: =item scantron_find_student
 5973: 
 5974:    Finds the username for the current scanline
 5975: 
 5976:   Arguments:
 5977:    $scantron_record - hash result from scantron_parse_scanline
 5978:    $scan_data       - hash of correction information 
 5979:                       (see &scantron_getfile() form more information)
 5980:    $idmap           - hash from &username_to_idmap()
 5981:    $line            - number of current scanline
 5982:  
 5983:   Returns:
 5984:    Either 'username:domain' or undef if unknown
 5985: 
 5986: =cut
 5987: 
 5988: sub scantron_find_student {
 5989:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 5990:     my $scanID=$$scantron_record{'scantron.ID'};
 5991:     if ($scanID =~ /^\s*$/) {
 5992:  	return &scan_data($scan_data,"$line.user");
 5993:     }
 5994:     foreach my $id (keys(%$idmap)) {
 5995:  	if (lc($id) eq lc($scanID)) {
 5996:  	    return $$idmap{$id};
 5997:  	}
 5998:     }
 5999:     return undef;
 6000: }
 6001: 
 6002: =pod
 6003: 
 6004: =item scantron_filter
 6005: 
 6006:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 6007:    hidden resources was selected
 6008: 
 6009: =cut
 6010: 
 6011: sub scantron_filter {
 6012:     my ($curres)=@_;
 6013: 
 6014:     if (ref($curres) && $curres->is_problem()) {
 6015: 	# if the user has asked to not have either hidden
 6016: 	# or 'randomout' controlled resources to be graded
 6017: 	# don't include them
 6018: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6019: 	    && $curres->randomout) {
 6020: 	    return 0;
 6021: 	}
 6022: 	return 1;
 6023:     }
 6024:     return 0;
 6025: }
 6026: 
 6027: =pod
 6028: 
 6029: =item scantron_process_corrections
 6030: 
 6031:    Gets correction information out of submitted form data and corrects
 6032:    the scanline
 6033: 
 6034: =cut
 6035: 
 6036: sub scantron_process_corrections {
 6037:     my ($r) = @_;
 6038:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6039:     my ($scanlines,$scan_data)=&scantron_getfile();
 6040:     my $classlist=&Apache::loncoursedata::get_classlist();
 6041:     my $which=$env{'form.scantron_line'};
 6042:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 6043:     my ($skip,$err,$errmsg);
 6044:     if ($env{'form.scantron_skip_record'}) {
 6045: 	$skip=1;
 6046:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 6047: 	my $newstudent=$env{'form.scantron_username'}.':'.
 6048: 	    $env{'form.scantron_domain'};
 6049: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 6050: 	($line,$err,$errmsg)=
 6051: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6052: 				     'ID',{'newid'=>$newid,
 6053: 				    'username'=>$env{'form.scantron_username'},
 6054: 				    'domain'=>$env{'form.scantron_domain'}});
 6055:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 6056: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 6057: 	my $newCODE;
 6058: 	my %args;
 6059: 	if      ($resolution eq 'use_unfound') {
 6060: 	    $newCODE='use_unfound';
 6061: 	} elsif ($resolution eq 'use_found') {
 6062: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 6063: 	} elsif ($resolution eq 'use_typed') {
 6064: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 6065: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 6066: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 6067: 	}
 6068: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 6069: 	    $args{'CODE_ignore_dup'}=1;
 6070: 	}
 6071: 	$args{'CODE'}=$newCODE;
 6072: 	($line,$err,$errmsg)=
 6073: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6074: 				     'CODE',\%args);
 6075:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 6076: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 6077: 	    ($line,$err,$errmsg)=
 6078: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 6079: 					 $which,'answer',
 6080: 					 { 'question'=>$question,
 6081: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 6082:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 6083: 	    if ($err) { last; }
 6084: 	}
 6085:     }
 6086:     if ($err) {
 6087: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
 6088:     } else {
 6089: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 6090: 	&scantron_putfile($scanlines,$scan_data);
 6091:     }
 6092: }
 6093: 
 6094: =pod
 6095: 
 6096: =item reset_skipping_status
 6097: 
 6098:    Forgets the current set of remember skipped scanlines (and thus
 6099:    reverts back to considering all lines in the
 6100:    scantron_skipped_<filename> file)
 6101: 
 6102: =cut
 6103: 
 6104: sub reset_skipping_status {
 6105:     my ($scanlines,$scan_data)=&scantron_getfile();
 6106:     &scan_data($scan_data,'remember_skipping',undef,1);
 6107:     &scantron_putfile(undef,$scan_data);
 6108: }
 6109: 
 6110: =pod
 6111: 
 6112: =item start_skipping
 6113: 
 6114:    Marks a scanline to be skipped. 
 6115: 
 6116: =cut
 6117: 
 6118: sub start_skipping {
 6119:     my ($scan_data,$i)=@_;
 6120:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6121:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 6122: 	$remembered{$i}=2;
 6123:     } else {
 6124: 	$remembered{$i}=1;
 6125:     }
 6126:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 6127: }
 6128: 
 6129: =pod
 6130: 
 6131: =item should_be_skipped
 6132: 
 6133:    Checks whether a scanline should be skipped.
 6134: 
 6135: =cut
 6136: 
 6137: sub should_be_skipped {
 6138:     my ($scanlines,$scan_data,$i)=@_;
 6139:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 6140: 	# not redoing old skips
 6141: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 6142: 	return 0;
 6143:     }
 6144:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6145: 
 6146:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 6147: 	return 0;
 6148:     }
 6149:     return 1;
 6150: }
 6151: 
 6152: =pod
 6153: 
 6154: =item remember_current_skipped
 6155: 
 6156:    Discovers what scanlines are in the scantron_skipped_<filename>
 6157:    file and remembers them into scan_data for later use.
 6158: 
 6159: =cut
 6160: 
 6161: sub remember_current_skipped {
 6162:     my ($scanlines,$scan_data)=&scantron_getfile();
 6163:     my %to_remember;
 6164:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6165: 	if ($scanlines->{'skipped'}[$i]) {
 6166: 	    $to_remember{$i}=1;
 6167: 	}
 6168:     }
 6169: 
 6170:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 6171:     &scantron_putfile(undef,$scan_data);
 6172: }
 6173: 
 6174: =pod
 6175: 
 6176: =item check_for_error
 6177: 
 6178:     Checks if there was an error when attempting to remove a specific
 6179:     scantron_.. bubble sheet data file. Prints out an error if
 6180:     something went wrong.
 6181: 
 6182: =cut
 6183: 
 6184: sub check_for_error {
 6185:     my ($r,$result)=@_;
 6186:     if ($result ne 'ok' && $result ne 'not_found' ) {
 6187: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 6188:     }
 6189: }
 6190: 
 6191: =pod
 6192: 
 6193: =item scantron_warning_screen
 6194: 
 6195:    Interstitial screen to make sure the operator has selected the
 6196:    correct options before we start the validation phase.
 6197: 
 6198: =cut
 6199: 
 6200: sub scantron_warning_screen {
 6201:     my ($button_text,$symb)=@_;
 6202:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 6203:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6204:     my $CODElist;
 6205:     if ($scantron_config{'CODElocation'} &&
 6206: 	$scantron_config{'CODEstart'} &&
 6207: 	$scantron_config{'CODElength'}) {
 6208: 	$CODElist=$env{'form.scantron_CODElist'};
 6209: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
 6210: 	$CODElist=
 6211: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 6212: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 6213:     }
 6214:     return ('
 6215: <p>
 6216: <span class="LC_warning">
 6217: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
 6218: </p>
 6219: <table>
 6220: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 6221: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 6222: '.$CODElist.'
 6223: </table>
 6224: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'<br />
 6225: '.&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>
 6226: 
 6227: <br />
 6228: ');
 6229: }
 6230: 
 6231: =pod
 6232: 
 6233: =item scantron_do_warning
 6234: 
 6235:    Check if the operator has picked something for all required
 6236:    fields. Error out if something is missing.
 6237: 
 6238: =cut
 6239: 
 6240: sub scantron_do_warning {
 6241:     my ($r,$symb)=@_;
 6242:     if (!$symb) {return '';}
 6243:     my $default_form_data=&defaultFormData($symb);
 6244:     $r->print(&scantron_form_start().$default_form_data);
 6245:     if ( $env{'form.selectpage'} eq '' ||
 6246: 	 $env{'form.scantron_selectfile'} eq '' ||
 6247: 	 $env{'form.scantron_format'} eq '' ) {
 6248: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
 6249: 	if ( $env{'form.selectpage'} eq '') {
 6250: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 6251: 	} 
 6252: 	if ( $env{'form.scantron_selectfile'} eq '') {
 6253: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected a file that contains the student's response data.").'</span></p>');
 6254: 	} 
 6255: 	if ( $env{'form.scantron_format'} eq '') {
 6256: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected the format of the student's response data.").'</span></p>');
 6257: 	} 
 6258:     } else {
 6259: 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
 6260: 	$r->print('
 6261: '.$warning.'
 6262: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 6263: <input type="hidden" name="command" value="scantron_validate" />
 6264: ');
 6265:     }
 6266:     $r->print("</form><br />");
 6267:     return '';
 6268: }
 6269: 
 6270: =pod
 6271: 
 6272: =item scantron_form_start
 6273: 
 6274:     html hidden input for remembering all selected grading options
 6275: 
 6276: =cut
 6277: 
 6278: sub scantron_form_start {
 6279:     my ($max_bubble)=@_;
 6280:     my $result= <<SCANTRONFORM;
 6281: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 6282:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 6283:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 6284:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 6285:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 6286:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 6287:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 6288:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 6289:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 6290:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 6291: SCANTRONFORM
 6292: 
 6293:   my $line = 0;
 6294:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 6295:        my $chunk =
 6296: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 6297:        $chunk .=
 6298: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 6299:        $chunk .= 
 6300:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 6301:        $chunk .=
 6302:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 6303:        $result .= $chunk;
 6304:        $line++;
 6305:    }
 6306:     return $result;
 6307: }
 6308: 
 6309: =pod
 6310: 
 6311: =item scantron_validate_file
 6312: 
 6313:     Dispatch routine for doing validation of a bubble sheet data file.
 6314: 
 6315:     Also processes any necessary information resets that need to
 6316:     occur before validation begins (ignore previous corrections,
 6317:     restarting the skipped records processing)
 6318: 
 6319: =cut
 6320: 
 6321: sub scantron_validate_file {
 6322:     my ($r,$symb) = @_;
 6323:     if (!$symb) {return '';}
 6324:     my $default_form_data=&defaultFormData($symb);
 6325:     
 6326:     # do the detection of only doing skipped records first befroe we delete
 6327:     # them when doing the corrections reset
 6328:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 6329: 	&reset_skipping_status();
 6330:     }
 6331:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 6332: 	&remember_current_skipped();
 6333: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 6334:     }
 6335: 
 6336:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 6337: 	&check_for_error($r,&scantron_remove_file('corrected'));
 6338: 	&check_for_error($r,&scantron_remove_file('skipped'));
 6339: 	&check_for_error($r,&scantron_remove_scan_data());
 6340: 	$env{'form.scantron_options_ignore'}='done';
 6341:     }
 6342: 
 6343:     if ($env{'form.scantron_corrections'}) {
 6344: 	&scantron_process_corrections($r);
 6345:     }
 6346:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 6347:     #get the student pick code ready
 6348:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 6349:     my $nav_error;
 6350:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6351:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 6352:     if ($nav_error) {
 6353:         $r->print(&navmap_errormsg());
 6354:         return '';
 6355:     }
 6356:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 6357:     $r->print($result);
 6358:     
 6359:     my @validate_phases=( 'sequence',
 6360: 			  'ID',
 6361: 			  'CODE',
 6362: 			  'doublebubble',
 6363: 			  'missingbubbles');
 6364:     if (!$env{'form.validatepass'}) {
 6365: 	$env{'form.validatepass'} = 0;
 6366:     }
 6367:     my $currentphase=$env{'form.validatepass'};
 6368: 
 6369: 
 6370:     my $stop=0;
 6371:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 6372: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 6373: 	$r->rflush();
 6374: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 6375: 	{
 6376: 	    no strict 'refs';
 6377: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 6378: 	}
 6379:     }
 6380:     if (!$stop) {
 6381: 	my $warning=&scantron_warning_screen('Start Grading',$symb);
 6382: 	$r->print(&mt('Validation process complete.').'<br />'.
 6383:                   $warning.
 6384:                   &mt('Perform verification for each student after storage of submissions?').
 6385:                   '&nbsp;<span class="LC_nobreak"><label>'.
 6386:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 6387:                   ('&nbsp;'x3).'<label>'.
 6388:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 6389:                   '</label></span><br />'.
 6390:                   &mt('Grading will take longer if you use verification.').'<br />'.
 6391:                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
 6392:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 6393:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 6394:     } else {
 6395: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 6396: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 6397:     }
 6398:     if ($stop) {
 6399: 	if ($validate_phases[$currentphase] eq 'sequence') {
 6400: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 6401: 	    $r->print(' '.&mt('this error').' <br />');
 6402: 
 6403: 	    $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>');
 6404: 	} else {
 6405:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 6406: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 6407:             } else {
 6408:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 6409:             }
 6410: 	    $r->print(' '.&mt('using corrected info').' <br />');
 6411: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 6412: 	    $r->print(" ".&mt("this scanline saving it for later."));
 6413: 	}
 6414:     }
 6415:     $r->print(" </form><br />");
 6416:     return '';
 6417: }
 6418: 
 6419: 
 6420: =pod
 6421: 
 6422: =item scantron_remove_file
 6423: 
 6424:    Removes the requested bubble sheet data file, makes sure that
 6425:    scantron_original_<filename> is never removed
 6426: 
 6427: 
 6428: =cut
 6429: 
 6430: sub scantron_remove_file {
 6431:     my ($which)=@_;
 6432:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6433:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6434:     my $file='scantron_';
 6435:     if ($which eq 'corrected' || $which eq 'skipped') {
 6436: 	$file.=$which.'_';
 6437:     } else {
 6438: 	return 'refused';
 6439:     }
 6440:     $file.=$env{'form.scantron_selectfile'};
 6441:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 6442: }
 6443: 
 6444: 
 6445: =pod
 6446: 
 6447: =item scantron_remove_scan_data
 6448: 
 6449:    Removes all scan_data correction for the requested bubble sheet
 6450:    data file.  (In the case that both the are doing skipped records we need
 6451:    to remember the old skipped lines for the time being so that element
 6452:    persists for a while.)
 6453: 
 6454: =cut
 6455: 
 6456: sub scantron_remove_scan_data {
 6457:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6458:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6459:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 6460:     my @todelete;
 6461:     my $filename=$env{'form.scantron_selectfile'};
 6462:     foreach my $key (@keys) {
 6463: 	if ($key=~/^\Q$filename\E_/) {
 6464: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 6465: 		$key=~/remember_skipping/) {
 6466: 		next;
 6467: 	    }
 6468: 	    push(@todelete,$key);
 6469: 	}
 6470:     }
 6471:     my $result;
 6472:     if (@todelete) {
 6473: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 6474: 				       \@todelete,$cdom,$cname);
 6475:     } else {
 6476: 	$result = 'ok';
 6477:     }
 6478:     return $result;
 6479: }
 6480: 
 6481: 
 6482: =pod
 6483: 
 6484: =item scantron_getfile
 6485: 
 6486:     Fetches the requested bubble sheet data file (all 3 versions), and
 6487:     the scan_data hash
 6488:   
 6489:   Arguments:
 6490:     None
 6491: 
 6492:   Returns:
 6493:     2 hash references
 6494: 
 6495:      - first one has 
 6496:          orig      -
 6497:          corrected -
 6498:          skipped   -  each of which points to an array ref of the specified
 6499:                       file broken up into individual lines
 6500:          count     - number of scanlines
 6501:  
 6502:      - second is the scan_data hash possible keys are
 6503:        ($number refers to scanline numbered $number and thus the key affects
 6504:         only that scanline
 6505:         $bubline refers to the specific bubble line element and the aspects
 6506:         refers to that specific bubble line element)
 6507: 
 6508:        $number.user - username:domain to use
 6509:        $number.CODE_ignore_dup 
 6510:                     - ignore the duplicate CODE error 
 6511:        $number.useCODE
 6512:                     - use the CODE in the scanline as is
 6513:        $number.no_bubble.$bubline
 6514:                     - it is valid that there is no bubbled in bubble
 6515:                       at $number $bubline
 6516:        remember_skipping
 6517:                     - a frozen hash containing keys of $number and values
 6518:                       of either 
 6519:                         1 - we are on a 'do skipped records pass' and plan
 6520:                             on processing this line
 6521:                         2 - we are on a 'do skipped records pass' and this
 6522:                             scanline has been marked to skip yet again
 6523: 
 6524: =cut
 6525: 
 6526: sub scantron_getfile {
 6527:     #FIXME really would prefer a scantron directory
 6528:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6529:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6530:     my $lines;
 6531:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6532: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 6533:     my %scanlines;
 6534:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 6535:     my $temp=$scanlines{'orig'};
 6536:     $scanlines{'count'}=$#$temp;
 6537: 
 6538:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6539: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 6540:     if ($lines eq '-1') {
 6541: 	$scanlines{'corrected'}=[];
 6542:     } else {
 6543: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 6544:     }
 6545:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6546: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 6547:     if ($lines eq '-1') {
 6548: 	$scanlines{'skipped'}=[];
 6549:     } else {
 6550: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 6551:     }
 6552:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 6553:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 6554:     my %scan_data = @tmp;
 6555:     return (\%scanlines,\%scan_data);
 6556: }
 6557: 
 6558: =pod
 6559: 
 6560: =item lonnet_putfile
 6561: 
 6562:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 6563: 
 6564:  Arguments:
 6565:    $contents - data to store
 6566:    $filename - filename to store $contents into
 6567: 
 6568:  Returns:
 6569:    result value from &Apache::lonnet::finishuserfileupload
 6570: 
 6571: =cut
 6572: 
 6573: sub lonnet_putfile {
 6574:     my ($contents,$filename)=@_;
 6575:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6576:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6577:     $env{'form.sillywaytopassafilearound'}=$contents;
 6578:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 6579: 
 6580: }
 6581: 
 6582: =pod
 6583: 
 6584: =item scantron_putfile
 6585: 
 6586:     Stores the current version of the bubble sheet data files, and the
 6587:     scan_data hash. (Does not modify the original version only the
 6588:     corrected and skipped versions.
 6589: 
 6590:  Arguments:
 6591:     $scanlines - hash ref that looks like the first return value from
 6592:                  &scantron_getfile()
 6593:     $scan_data - hash ref that looks like the second return value from
 6594:                  &scantron_getfile()
 6595: 
 6596: =cut
 6597: 
 6598: sub scantron_putfile {
 6599:     my ($scanlines,$scan_data) = @_;
 6600:     #FIXME really would prefer a scantron directory
 6601:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6602:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6603:     if ($scanlines) {
 6604: 	my $prefix='scantron_';
 6605: # no need to update orig, shouldn't change
 6606: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 6607: #		    $env{'form.scantron_selectfile'});
 6608: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 6609: 			$prefix.'corrected_'.
 6610: 			$env{'form.scantron_selectfile'});
 6611: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 6612: 			$prefix.'skipped_'.
 6613: 			$env{'form.scantron_selectfile'});
 6614:     }
 6615:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 6616: }
 6617: 
 6618: =pod
 6619: 
 6620: =item scantron_get_line
 6621: 
 6622:    Returns the correct version of the scanline
 6623: 
 6624:  Arguments:
 6625:     $scanlines - hash ref that looks like the first return value from
 6626:                  &scantron_getfile()
 6627:     $scan_data - hash ref that looks like the second return value from
 6628:                  &scantron_getfile()
 6629:     $i         - number of the requested line (starts at 0)
 6630: 
 6631:  Returns:
 6632:    A scanline, (either the original or the corrected one if it
 6633:    exists), or undef if the requested scanline should be
 6634:    skipped. (Either because it's an skipped scanline, or it's an
 6635:    unskipped scanline and we are not doing a 'do skipped scanlines'
 6636:    pass.
 6637: 
 6638: =cut
 6639: 
 6640: sub scantron_get_line {
 6641:     my ($scanlines,$scan_data,$i)=@_;
 6642:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 6643:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 6644:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 6645:     return $scanlines->{'orig'}[$i]; 
 6646: }
 6647: 
 6648: =pod
 6649: 
 6650: =item scantron_todo_count
 6651: 
 6652:     Counts the number of scanlines that need processing.
 6653: 
 6654:  Arguments:
 6655:     $scanlines - hash ref that looks like the first return value from
 6656:                  &scantron_getfile()
 6657:     $scan_data - hash ref that looks like the second return value from
 6658:                  &scantron_getfile()
 6659: 
 6660:  Returns:
 6661:     $count - number of scanlines to process
 6662: 
 6663: =cut
 6664: 
 6665: sub get_todo_count {
 6666:     my ($scanlines,$scan_data)=@_;
 6667:     my $count=0;
 6668:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6669: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6670: 	if ($line=~/^[\s\cz]*$/) { next; }
 6671: 	$count++;
 6672:     }
 6673:     return $count;
 6674: }
 6675: 
 6676: =pod
 6677: 
 6678: =item scantron_put_line
 6679: 
 6680:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
 6681:     data file.
 6682: 
 6683:  Arguments:
 6684:     $scanlines - hash ref that looks like the first return value from
 6685:                  &scantron_getfile()
 6686:     $scan_data - hash ref that looks like the second return value from
 6687:                  &scantron_getfile()
 6688:     $i         - line number to update
 6689:     $newline   - contents of the updated scanline
 6690:     $skip      - if true make the line for skipping and update the
 6691:                  'skipped' file
 6692: 
 6693: =cut
 6694: 
 6695: sub scantron_put_line {
 6696:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 6697:     if ($skip) {
 6698: 	$scanlines->{'skipped'}[$i]=$newline;
 6699: 	&start_skipping($scan_data,$i);
 6700: 	return;
 6701:     }
 6702:     $scanlines->{'corrected'}[$i]=$newline;
 6703: }
 6704: 
 6705: =pod
 6706: 
 6707: =item scantron_clear_skip
 6708: 
 6709:    Remove a line from the 'skipped' file
 6710: 
 6711:  Arguments:
 6712:     $scanlines - hash ref that looks like the first return value from
 6713:                  &scantron_getfile()
 6714:     $scan_data - hash ref that looks like the second return value from
 6715:                  &scantron_getfile()
 6716:     $i         - line number to update
 6717: 
 6718: =cut
 6719: 
 6720: sub scantron_clear_skip {
 6721:     my ($scanlines,$scan_data,$i)=@_;
 6722:     if (exists($scanlines->{'skipped'}[$i])) {
 6723: 	undef($scanlines->{'skipped'}[$i]);
 6724: 	return 1;
 6725:     }
 6726:     return 0;
 6727: }
 6728: 
 6729: =pod
 6730: 
 6731: =item scantron_filter_not_exam
 6732: 
 6733:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 6734:    filter out resources that are not marked as 'exam' mode
 6735: 
 6736: =cut
 6737: 
 6738: sub scantron_filter_not_exam {
 6739:     my ($curres)=@_;
 6740:     
 6741:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 6742: 	# if the user has asked to not have either hidden
 6743: 	# or 'randomout' controlled resources to be graded
 6744: 	# don't include them
 6745: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6746: 	    && $curres->randomout) {
 6747: 	    return 0;
 6748: 	}
 6749: 	return 1;
 6750:     }
 6751:     return 0;
 6752: }
 6753: 
 6754: =pod
 6755: 
 6756: =item scantron_validate_sequence
 6757: 
 6758:     Validates the selected sequence, checking for resource that are
 6759:     not set to exam mode.
 6760: 
 6761: =cut
 6762: 
 6763: sub scantron_validate_sequence {
 6764:     my ($r,$currentphase) = @_;
 6765: 
 6766:     my $navmap=Apache::lonnavmaps::navmap->new();
 6767:     unless (ref($navmap)) {
 6768:         $r->print(&navmap_errormsg());
 6769:         return (1,$currentphase);
 6770:     }
 6771:     my (undef,undef,$sequence)=
 6772: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 6773: 
 6774:     my $map=$navmap->getResourceByUrl($sequence);
 6775: 
 6776:     $r->print('<input type="hidden" name="validate_sequence_exam"
 6777:                                     value="ignore" />');
 6778:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 6779: 	my @resources=
 6780: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 6781: 	if (@resources) {
 6782: 	    $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>");
 6783: 	    return (1,$currentphase);
 6784: 	}
 6785:     }
 6786: 
 6787:     return (0,$currentphase+1);
 6788: }
 6789: 
 6790: 
 6791: 
 6792: sub scantron_validate_ID {
 6793:     my ($r,$currentphase) = @_;
 6794:     
 6795:     #get student info
 6796:     my $classlist=&Apache::loncoursedata::get_classlist();
 6797:     my %idmap=&username_to_idmap($classlist);
 6798: 
 6799:     #get scantron line setup
 6800:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6801:     my ($scanlines,$scan_data)=&scantron_getfile();
 6802: 
 6803:     my $nav_error;
 6804:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
 6805:     if ($nav_error) {
 6806:         $r->print(&navmap_errormsg());
 6807:         return(1,$currentphase);
 6808:     }
 6809: 
 6810:     my %found=('ids'=>{},'usernames'=>{});
 6811:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6812: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6813: 	if ($line=~/^[\s\cz]*$/) { next; }
 6814: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 6815: 						 $scan_data);
 6816: 	my $id=$$scan_record{'scantron.ID'};
 6817: 	my $found;
 6818: 	foreach my $checkid (keys(%idmap)) {
 6819: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 6820: 	}
 6821: 	if ($found) {
 6822: 	    my $username=$idmap{$found};
 6823: 	    if ($found{'ids'}{$found}) {
 6824: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6825: 					 $line,'duplicateID',$found);
 6826: 		return(1,$currentphase);
 6827: 	    } elsif ($found{'usernames'}{$username}) {
 6828: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6829: 					 $line,'duplicateID',$username);
 6830: 		return(1,$currentphase);
 6831: 	    }
 6832: 	    #FIXME store away line we previously saw the ID on to use above
 6833: 	    $found{'ids'}{$found}++;
 6834: 	    $found{'usernames'}{$username}++;
 6835: 	} else {
 6836: 	    if ($id =~ /^\s*$/) {
 6837: 		my $username=&scan_data($scan_data,"$i.user");
 6838: 		if (defined($username) && $found{'usernames'}{$username}) {
 6839: 		    &scantron_get_correction($r,$i,$scan_record,
 6840: 					     \%scantron_config,
 6841: 					     $line,'duplicateID',$username);
 6842: 		    return(1,$currentphase);
 6843: 		} elsif (!defined($username)) {
 6844: 		    &scantron_get_correction($r,$i,$scan_record,
 6845: 					     \%scantron_config,
 6846: 					     $line,'incorrectID');
 6847: 		    return(1,$currentphase);
 6848: 		}
 6849: 		$found{'usernames'}{$username}++;
 6850: 	    } else {
 6851: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6852: 					 $line,'incorrectID');
 6853: 		return(1,$currentphase);
 6854: 	    }
 6855: 	}
 6856:     }
 6857: 
 6858:     return (0,$currentphase+1);
 6859: }
 6860: 
 6861: 
 6862: sub scantron_get_correction {
 6863:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
 6864: #FIXME in the case of a duplicated ID the previous line, probably need
 6865: #to show both the current line and the previous one and allow skipping
 6866: #the previous one or the current one
 6867: 
 6868:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 6869: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6870: 			    " for PaperID <tt>[_1]</tt>",
 6871: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
 6872:     } else {
 6873: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6874: 			    " in scanline [_1] <pre>[_2]</pre>",
 6875: 			    $i,$line)."</p> \n");
 6876:     }
 6877:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
 6878: 			  "The name on the paper is [_2],[_3]",
 6879: 			  $$scan_record{'scantron.ID'},
 6880: 			  $$scan_record{'scantron.LastName'},
 6881: 			  $$scan_record{'scantron.FirstName'})."</p>";
 6882: 
 6883:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 6884:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 6885:                            # Array populated for doublebubble or
 6886:     my @lines_to_correct;  # missingbubble errors to build javascript
 6887:                            # to validate radio button checking   
 6888: 
 6889:     if ($error =~ /ID$/) {
 6890: 	if ($error eq 'incorrectID') {
 6891: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
 6892: 		      "</p>\n");
 6893: 	} elsif ($error eq 'duplicateID') {
 6894: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 6895: 	}
 6896: 	$r->print($message);
 6897: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6898: 	$r->print("\n<ul><li> ");
 6899: 	#FIXME it would be nice if this sent back the user ID and
 6900: 	#could do partial userID matches
 6901: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 6902: 				       'scantron_username','scantron_domain'));
 6903: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 6904: 	$r->print("\n@".
 6905: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 6906: 
 6907: 	$r->print('</li>');
 6908:     } elsif ($error =~ /CODE$/) {
 6909: 	if ($error eq 'incorrectCODE') {
 6910: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 6911: 	} elsif ($error eq 'duplicateCODE') {
 6912: 	    $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");
 6913: 	}
 6914: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
 6915: 			    $$scan_record{'scantron.CODE'})."<br />\n");
 6916: 	$r->print($message);
 6917: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6918: 	$r->print("\n<br /> ");
 6919: 	my $i=0;
 6920: 	if ($error eq 'incorrectCODE' 
 6921: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 6922: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 6923: 	    if ($closest > 0) {
 6924: 		foreach my $testcode (@{$closest}) {
 6925: 		    my $checked='';
 6926: 		    if (!$i) { $checked=' checked="checked"'; }
 6927: 		    $r->print("
 6928:    <label>
 6929:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
 6930:        ".&mt("Use the similar CODE [_1] instead.",
 6931: 	    "<b><tt>".$testcode."</tt></b>")."
 6932:     </label>
 6933:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 6934: 		    $r->print("\n<br />");
 6935: 		    $i++;
 6936: 		}
 6937: 	    }
 6938: 	}
 6939: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 6940: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
 6941: 	    $r->print("
 6942:     <label>
 6943:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
 6944:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
 6945: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 6946:     </label>");
 6947: 	    $r->print("\n<br />");
 6948: 	}
 6949: 
 6950: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
 6951: function change_radio(field) {
 6952:     var slct=document.scantronupload.scantron_CODE_resolution;
 6953:     var i;
 6954:     for (i=0;i<slct.length;i++) {
 6955:         if (slct[i].value==field) { slct[i].checked=true; }
 6956:     }
 6957: }
 6958: ENDSCRIPT
 6959: 	my $href="/adm/pickcode?".
 6960: 	   "form=".&escape("scantronupload").
 6961: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 6962: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 6963: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 6964: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 6965: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 6966: 	    $r->print("
 6967:     <label>
 6968:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 6969:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 6970: 	     "<a target='_blank' href='$href'>","</a>")."
 6971:     </label> 
 6972:     ".&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\')" />'));
 6973: 	    $r->print("\n<br />");
 6974: 	}
 6975: 	$r->print("
 6976:     <label>
 6977:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 6978:        ".&mt("Use [_1] as the CODE.",
 6979: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 6980: 	$r->print("\n<br /><br />");
 6981:     } elsif ($error eq 'doublebubble') {
 6982: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 6983: 
 6984: 	# The form field scantron_questions is acutally a list of line numbers.
 6985: 	# represented by this form so:
 6986: 
 6987: 	my $line_list = &questions_to_line_list($arg);
 6988: 
 6989: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 6990: 		  $line_list.'" />');
 6991: 	$r->print($message);
 6992: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 6993: 	foreach my $question (@{$arg}) {
 6994: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 6995:                                                    $scan_record, $error);
 6996:             push(@lines_to_correct,@linenums);
 6997: 	}
 6998:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 6999:     } elsif ($error eq 'missingbubble') {
 7000: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
 7001: 	$r->print($message);
 7002: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 7003: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 7004: 
 7005: 	# The form field scantron_questions is actually a list of line numbers not
 7006: 	# a list of question numbers. Therefore:
 7007: 	#
 7008: 	
 7009: 	my $line_list = &questions_to_line_list($arg);
 7010: 
 7011: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7012: 		  $line_list.'" />');
 7013: 	foreach my $question (@{$arg}) {
 7014: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7015:                                                    $scan_record, $error);
 7016:             push(@lines_to_correct,@linenums);
 7017: 	}
 7018:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7019:     } else {
 7020: 	$r->print("\n<ul>");
 7021:     }
 7022:     $r->print("\n</li></ul>");
 7023: }
 7024: 
 7025: sub verify_bubbles_checked {
 7026:     my (@ansnums) = @_;
 7027:     my $ansnumstr = join('","',@ansnums);
 7028:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 7029:     my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
 7030: function verify_bubble_radio(form) {
 7031:     var ansnumArray = new Array ("$ansnumstr");
 7032:     var need_bubble_count = 0;
 7033:     for (var i=0; i<ansnumArray.length; i++) {
 7034:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 7035:             var bubble_picked = 0; 
 7036:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 7037:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 7038:                     bubble_picked = 1;
 7039:                 }
 7040:             }
 7041:             if (bubble_picked == 0) {
 7042:                 need_bubble_count ++;
 7043:             }
 7044:         }
 7045:     }
 7046:     if (need_bubble_count) {
 7047:         alert("$warning");
 7048:         return;
 7049:     }
 7050:     form.submit(); 
 7051: }
 7052: ENDSCRIPT
 7053:     return $output;
 7054: }
 7055: 
 7056: =pod
 7057: 
 7058: =item  questions_to_line_list
 7059: 
 7060: Converts a list of questions into a string of comma separated
 7061: line numbers in the answer sheet used by the questions.  This is
 7062: used to fill in the scantron_questions form field.
 7063: 
 7064:   Arguments:
 7065:      questions    - Reference to an array of questions.
 7066: 
 7067: =cut
 7068: 
 7069: 
 7070: sub questions_to_line_list {
 7071:     my ($questions) = @_;
 7072:     my @lines;
 7073: 
 7074:     foreach my $item (@{$questions}) {
 7075:         my $question = $item;
 7076:         my ($first,$count,$last);
 7077:         if ($item =~ /^(\d+)\.(\d+)$/) {
 7078:             $question = $1;
 7079:             my $subquestion = $2;
 7080:             $first = $first_bubble_line{$question-1} + 1;
 7081:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7082:             my $subcount = 1;
 7083:             while ($subcount<$subquestion) {
 7084:                 $first += $subans[$subcount-1];
 7085:                 $subcount ++;
 7086:             }
 7087:             $count = $subans[$subquestion-1];
 7088:         } else {
 7089: 	    $first   = $first_bubble_line{$question-1} + 1;
 7090: 	    $count   = $bubble_lines_per_response{$question-1};
 7091:         }
 7092:         $last = $first+$count-1;
 7093:         push(@lines, ($first..$last));
 7094:     }
 7095:     return join(',', @lines);
 7096: }
 7097: 
 7098: =pod 
 7099: 
 7100: =item prompt_for_corrections
 7101: 
 7102: Prompts for a potentially multiline correction to the
 7103: user's bubbling (factors out common code from scantron_get_correction
 7104: for multi and missing bubble cases).
 7105: 
 7106:  Arguments:
 7107:    $r           - Apache request object.
 7108:    $question    - The question number to prompt for.
 7109:    $scan_config - The scantron file configuration hash.
 7110:    $scan_record - Reference to the hash that has the the parsed scanlines.
 7111:    $error       - Type of error
 7112: 
 7113:  Implicit inputs:
 7114:    %bubble_lines_per_response   - Starting line numbers for each question.
 7115:                                   Numbered from 0 (but question numbers are from
 7116:                                   1.
 7117:    %first_bubble_line           - Starting bubble line for each question.
 7118:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 7119:                                   type problems render as separate sub-questions, 
 7120:                                   in exam mode. This hash contains a 
 7121:                                   comma-separated list of the lines per 
 7122:                                   sub-question.
 7123:    %responsetype_per_response   - essayresponse, formularesponse,
 7124:                                   stringresponse, imageresponse, reactionresponse,
 7125:                                   and organicresponse type problem parts can have
 7126:                                   multiple lines per response if the weight
 7127:                                   assigned exceeds 10.  In this case, only
 7128:                                   one bubble per line is permitted, but more 
 7129:                                   than one line might contain bubbles, e.g.
 7130:                                   bubbling of: line 1 - J, line 2 - J, 
 7131:                                   line 3 - B would assign 22 points.  
 7132: 
 7133: =cut
 7134: 
 7135: sub prompt_for_corrections {
 7136:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
 7137:     my ($current_line,$lines);
 7138:     my @linenums;
 7139:     my $questionnum = $question;
 7140:     if ($question =~ /^(\d+)\.(\d+)$/) {
 7141:         $question = $1;
 7142:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7143:         my $subquestion = $2;
 7144:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7145:         my $subcount = 1;
 7146:         while ($subcount<$subquestion) {
 7147:             $current_line += $subans[$subcount-1];
 7148:             $subcount ++;
 7149:         }
 7150:         $lines = $subans[$subquestion-1];
 7151:     } else {
 7152:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7153:         $lines        = $bubble_lines_per_response{$question-1};
 7154:     }
 7155:     if ($lines > 1) {
 7156:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 7157:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
 7158:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
 7159:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
 7160:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
 7161:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
 7162:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
 7163:             $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 />');
 7164:         } else {
 7165:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 7166:         }
 7167:     }
 7168:     for (my $i =0; $i < $lines; $i++) {
 7169:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 7170: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
 7171: 	        		  $questionnum,$error,split('', $selected));
 7172:         push(@linenums,$current_line);
 7173: 	$current_line++;
 7174:     }
 7175:     if ($lines > 1) {
 7176: 	$r->print("<hr /><br />");
 7177:     }
 7178:     return @linenums;
 7179: }
 7180: 
 7181: =pod
 7182: 
 7183: =item scantron_bubble_selector
 7184:   
 7185:    Generates the html radiobuttons to correct a single bubble line
 7186:    possibly showing the existing the selected bubbles if known
 7187: 
 7188:  Arguments:
 7189:     $r           - Apache request object
 7190:     $scan_config - hash from &get_scantron_config()
 7191:     $line        - Number of the line being displayed.
 7192:     $questionnum - Question number (may include subquestion)
 7193:     $error       - Type of error.
 7194:     @selected    - Array of bubbles picked on this line.
 7195: 
 7196: =cut
 7197: 
 7198: sub scantron_bubble_selector {
 7199:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 7200:     my $max=$$scan_config{'Qlength'};
 7201: 
 7202:     my $scmode=$$scan_config{'Qon'};
 7203:     if ($scmode eq 'number' || $scmode eq 'letter') { 
 7204:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
 7205:             ($$scan_config{'BubblesPerRow'} > 0)) {
 7206:             $max=$$scan_config{'BubblesPerRow'};
 7207:             if (($scmode eq 'number') && ($max > 10)) {
 7208:                 $max = 10;
 7209:             } elsif (($scmode eq 'letter') && $max > 26) {
 7210:                 $max = 26;
 7211:             }
 7212:         } else {
 7213:             $max = 10;
 7214:         }
 7215:     }
 7216: 
 7217:     my @alphabet=('A'..'Z');
 7218:     $r->print(&Apache::loncommon::start_data_table().
 7219:               &Apache::loncommon::start_data_table_row());
 7220:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 7221:     for (my $i=0;$i<$max+1;$i++) {
 7222: 	$r->print("\n".'<td align="center">');
 7223: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 7224: 	else { $r->print('&nbsp;'); }
 7225: 	$r->print('</td>');
 7226:     }
 7227:     $r->print(&Apache::loncommon::end_data_table_row().
 7228:               &Apache::loncommon::start_data_table_row());
 7229:     for (my $i=0;$i<$max;$i++) {
 7230: 	$r->print("\n".
 7231: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 7232: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 7233:     }
 7234:     my $nobub_checked = ' ';
 7235:     if ($error eq 'missingbubble') {
 7236:         $nobub_checked = ' checked = "checked" ';
 7237:     }
 7238:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 7239: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 7240:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 7241:               $line.'" value="'.$questionnum.'" /></td>');
 7242:     $r->print(&Apache::loncommon::end_data_table_row().
 7243:               &Apache::loncommon::end_data_table());
 7244: }
 7245: 
 7246: =pod
 7247: 
 7248: =item num_matches
 7249: 
 7250:    Counts the number of characters that are the same between the two arguments.
 7251: 
 7252:  Arguments:
 7253:    $orig - CODE from the scanline
 7254:    $code - CODE to match against
 7255: 
 7256:  Returns:
 7257:    $count - integer count of the number of same characters between the
 7258:             two arguments
 7259: 
 7260: =cut
 7261: 
 7262: sub num_matches {
 7263:     my ($orig,$code) = @_;
 7264:     my @code=split(//,$code);
 7265:     my @orig=split(//,$orig);
 7266:     my $same=0;
 7267:     for (my $i=0;$i<scalar(@code);$i++) {
 7268: 	if ($code[$i] eq $orig[$i]) { $same++; }
 7269:     }
 7270:     return $same;
 7271: }
 7272: 
 7273: =pod
 7274: 
 7275: =item scantron_get_closely_matching_CODEs
 7276: 
 7277:    Cycles through all CODEs and finds the set that has the greatest
 7278:    number of same characters as the provided CODE
 7279: 
 7280:  Arguments:
 7281:    $allcodes - hash ref returned by &get_codes()
 7282:    $CODE     - CODE from the current scanline
 7283: 
 7284:  Returns:
 7285:    2 element list
 7286:     - first elements is number of how closely matching the best fit is 
 7287:       (5 means best set has 5 matching characters)
 7288:     - second element is an arrary ref containing the set of valid CODEs
 7289:       that best fit the passed in CODE
 7290: 
 7291: =cut
 7292: 
 7293: sub scantron_get_closely_matching_CODEs {
 7294:     my ($allcodes,$CODE)=@_;
 7295:     my @CODEs;
 7296:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 7297: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 7298:     }
 7299: 
 7300:     return ($#CODEs,$CODEs[-1]);
 7301: }
 7302: 
 7303: =pod
 7304: 
 7305: =item get_codes
 7306: 
 7307:    Builds a hash which has keys of all of the valid CODEs from the selected
 7308:    set of remembered CODEs.
 7309: 
 7310:  Arguments:
 7311:   $old_name - name of the set of remembered CODEs
 7312:   $cdom     - domain of the course
 7313:   $cnum     - internal course name
 7314: 
 7315:  Returns:
 7316:   %allcodes - keys are the valid CODEs, values are all 1
 7317: 
 7318: =cut
 7319: 
 7320: sub get_codes {
 7321:     my ($old_name, $cdom, $cnum) = @_;
 7322:     if (!$old_name) {
 7323: 	$old_name=$env{'form.scantron_CODElist'};
 7324:     }
 7325:     if (!$cdom) {
 7326: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 7327:     }
 7328:     if (!$cnum) {
 7329: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 7330:     }
 7331:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 7332: 				    $cdom,$cnum);
 7333:     my %allcodes;
 7334:     if ($result{"type\0$old_name"} eq 'number') {
 7335: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 7336:     } else {
 7337: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 7338:     }
 7339:     return %allcodes;
 7340: }
 7341: 
 7342: =pod
 7343: 
 7344: =item scantron_validate_CODE
 7345: 
 7346:    Validates all scanlines in the selected file to not have any
 7347:    invalid or underspecified CODEs and that none of the codes are
 7348:    duplicated if this was requested.
 7349: 
 7350: =cut
 7351: 
 7352: sub scantron_validate_CODE {
 7353:     my ($r,$currentphase) = @_;
 7354:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7355:     if ($scantron_config{'CODElocation'} &&
 7356: 	$scantron_config{'CODEstart'} &&
 7357: 	$scantron_config{'CODElength'}) {
 7358: 	if (!defined($env{'form.scantron_CODElist'})) {
 7359: 	    &FIXME_blow_up()
 7360: 	}
 7361:     } else {
 7362: 	return (0,$currentphase+1);
 7363:     }
 7364:     
 7365:     my %usedCODEs;
 7366: 
 7367:     my %allcodes=&get_codes();
 7368: 
 7369:     my $nav_error;
 7370:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
 7371:     if ($nav_error) {
 7372:         $r->print(&navmap_errormsg());
 7373:         return(1,$currentphase);
 7374:     }
 7375: 
 7376:     my ($scanlines,$scan_data)=&scantron_getfile();
 7377:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7378: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7379: 	if ($line=~/^[\s\cz]*$/) { next; }
 7380: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7381: 						 $scan_data);
 7382: 	my $CODE=$$scan_record{'scantron.CODE'};
 7383: 	my $error=0;
 7384: 	if (!&Apache::lonnet::validCODE($CODE)) {
 7385: 	    &scantron_get_correction($r,$i,$scan_record,
 7386: 				     \%scantron_config,
 7387: 				     $line,'incorrectCODE',\%allcodes);
 7388: 	    return(1,$currentphase);
 7389: 	}
 7390: 	if (%allcodes && !exists($allcodes{$CODE}) 
 7391: 	    && !$$scan_record{'scantron.useCODE'}) {
 7392: 	    &scantron_get_correction($r,$i,$scan_record,
 7393: 				     \%scantron_config,
 7394: 				     $line,'incorrectCODE',\%allcodes);
 7395: 	    return(1,$currentphase);
 7396: 	}
 7397: 	if (exists($usedCODEs{$CODE}) 
 7398: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 7399: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 7400: 	    &scantron_get_correction($r,$i,$scan_record,
 7401: 				     \%scantron_config,
 7402: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 7403: 	    return(1,$currentphase);
 7404: 	}
 7405: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 7406:     }
 7407:     return (0,$currentphase+1);
 7408: }
 7409: 
 7410: =pod
 7411: 
 7412: =item scantron_validate_doublebubble
 7413: 
 7414:    Validates all scanlines in the selected file to not have any
 7415:    bubble lines with multiple bubbles marked.
 7416: 
 7417: =cut
 7418: 
 7419: sub scantron_validate_doublebubble {
 7420:     my ($r,$currentphase) = @_;
 7421:     #get student info
 7422:     my $classlist=&Apache::loncoursedata::get_classlist();
 7423:     my %idmap=&username_to_idmap($classlist);
 7424: 
 7425:     #get scantron line setup
 7426:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7427:     my ($scanlines,$scan_data)=&scantron_getfile();
 7428:     my $nav_error;
 7429:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
 7430:     if ($nav_error) {
 7431:         $r->print(&navmap_errormsg());
 7432:         return(1,$currentphase);
 7433:     }
 7434: 
 7435:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7436: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7437: 	if ($line=~/^[\s\cz]*$/) { next; }
 7438: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7439: 						 $scan_data);
 7440: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 7441: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 7442: 				 'doublebubble',
 7443: 				 $$scan_record{'scantron.doubleerror'});
 7444:     	return (1,$currentphase);
 7445:     }
 7446:     return (0,$currentphase+1);
 7447: }
 7448: 
 7449: 
 7450: sub scantron_get_maxbubble {
 7451:     my ($nav_error,$scantron_config) = @_;
 7452:     if (defined($env{'form.scantron_maxbubble'}) &&
 7453: 	$env{'form.scantron_maxbubble'}) {
 7454: 	&restore_bubble_lines();
 7455: 	return $env{'form.scantron_maxbubble'};
 7456:     }
 7457: 
 7458:     my (undef, undef, $sequence) =
 7459: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7460: 
 7461:     my $navmap=Apache::lonnavmaps::navmap->new();
 7462:     unless (ref($navmap)) {
 7463:         if (ref($nav_error)) {
 7464:             $$nav_error = 1;
 7465:         }
 7466:         return;
 7467:     }
 7468:     my $map=$navmap->getResourceByUrl($sequence);
 7469:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7470:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
 7471: 
 7472:     &Apache::lonxml::clear_problem_counter();
 7473: 
 7474:     my $uname       = $env{'user.name'};
 7475:     my $udom        = $env{'user.domain'};
 7476:     my $cid         = $env{'request.course.id'};
 7477:     my $total_lines = 0;
 7478:     %bubble_lines_per_response = ();
 7479:     %first_bubble_line         = ();
 7480:     %subdivided_bubble_lines   = ();
 7481:     %responsetype_per_response = ();
 7482: 
 7483:     my $response_number = 0;
 7484:     my $bubble_line     = 0;
 7485:     foreach my $resource (@resources) {
 7486:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom,undef,$bubbles_per_row);
 7487:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 7488: 	    foreach my $part_id (@{$parts}) {
 7489:                 my $lines;
 7490: 
 7491: 	        # TODO - make this a persistent hash not an array.
 7492: 
 7493:                 # optionresponse, matchresponse and rankresponse type items 
 7494:                 # render as separate sub-questions in exam mode.
 7495:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 7496:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 7497:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 7498:                     my ($numbub,$numshown);
 7499:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 7500:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 7501:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 7502:                         }
 7503:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 7504:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 7505:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 7506:                         }
 7507:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 7508:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 7509:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 7510:                         }
 7511:                     }
 7512:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 7513:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 7514:                     }
 7515:                     my $bubbles_per_row =
 7516:                         &bubblesheet_bubbles_per_row($scantron_config);
 7517:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
 7518:                     if (($numbub % $bubbles_per_row) != 0) {
 7519:                         $inner_bubble_lines++;
 7520:                     }
 7521:                     for (my $i=0; $i<$numshown; $i++) {
 7522:                         $subdivided_bubble_lines{$response_number} .= 
 7523:                             $inner_bubble_lines.',';
 7524:                     }
 7525:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 7526:                     $lines = $numshown * $inner_bubble_lines;
 7527:                 } else {
 7528:                     $lines = $analysis->{"$part_id.bubble_lines"};
 7529:                 }
 7530: 
 7531:                 $first_bubble_line{$response_number} = $bubble_line;
 7532: 	        $bubble_lines_per_response{$response_number} = $lines;
 7533:                 $responsetype_per_response{$response_number} = 
 7534:                     $analysis->{$part_id.'.type'};
 7535: 	        $response_number++;
 7536: 
 7537: 	        $bubble_line +=  $lines;
 7538: 	        $total_lines +=  $lines;
 7539: 	    }
 7540:         }
 7541:     }
 7542:     &Apache::lonnet::delenv('scantron.');
 7543: 
 7544:     &save_bubble_lines();
 7545:     $env{'form.scantron_maxbubble'} =
 7546: 	$total_lines;
 7547:     return $env{'form.scantron_maxbubble'};
 7548: }
 7549: 
 7550: sub bubblesheet_bubbles_per_row {
 7551:     my ($scantron_config) = @_;
 7552:     my $bubbles_per_row;
 7553:     if (ref($scantron_config) eq 'HASH') {
 7554:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
 7555:     }
 7556:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
 7557:         $bubbles_per_row = 10;
 7558:     }
 7559:     return $bubbles_per_row;
 7560: }
 7561: 
 7562: sub scantron_validate_missingbubbles {
 7563:     my ($r,$currentphase) = @_;
 7564:     #get student info
 7565:     my $classlist=&Apache::loncoursedata::get_classlist();
 7566:     my %idmap=&username_to_idmap($classlist);
 7567: 
 7568:     #get scantron line setup
 7569:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7570:     my ($scanlines,$scan_data)=&scantron_getfile();
 7571:     my $nav_error;
 7572:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 7573:     if ($nav_error) {
 7574:         return(1,$currentphase);
 7575:     }
 7576:     if (!$max_bubble) { $max_bubble=2**31; }
 7577:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7578: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7579: 	if ($line=~/^[\s\cz]*$/) { next; }
 7580: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7581: 						 $scan_data);
 7582: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 7583: 	my @to_correct;
 7584: 	
 7585: 	# Probably here's where the error is...
 7586: 
 7587: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 7588:             my $lastbubble;
 7589:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 7590:                my $question = $1;
 7591:                my $subquestion = $2;
 7592:                if (!defined($first_bubble_line{$question -1})) { next; }
 7593:                my $first = $first_bubble_line{$question-1};
 7594:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7595:                my $subcount = 1;
 7596:                while ($subcount<$subquestion) {
 7597:                    $first += $subans[$subcount-1];
 7598:                    $subcount ++;
 7599:                }
 7600:                my $count = $subans[$subquestion-1];
 7601:                $lastbubble = $first + $count;
 7602:             } else {
 7603:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
 7604:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
 7605:             }
 7606:             if ($lastbubble > $max_bubble) { next; }
 7607: 	    push(@to_correct,$missing);
 7608: 	}
 7609: 	if (@to_correct) {
 7610: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7611: 				     $line,'missingbubble',\@to_correct);
 7612: 	    return (1,$currentphase);
 7613: 	}
 7614: 
 7615:     }
 7616:     return (0,$currentphase+1);
 7617: }
 7618: 
 7619: 
 7620: sub scantron_process_students {
 7621:     my ($r,$symb) = @_;
 7622: 
 7623:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7624:     if (!$symb) {
 7625: 	return '';
 7626:     }
 7627:     my $default_form_data=&defaultFormData($symb);
 7628: 
 7629:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7630:     my $bubbles_per_row =
 7631:         &bubblesheet_bubbles_per_row(\%scantron_config);
 7632:     my ($scanlines,$scan_data)=&scantron_getfile();
 7633:     my $classlist=&Apache::loncoursedata::get_classlist();
 7634:     my %idmap=&username_to_idmap($classlist);
 7635:     my $navmap=Apache::lonnavmaps::navmap->new();
 7636:     unless (ref($navmap)) {
 7637:         $r->print(&navmap_errormsg());
 7638:         return '';
 7639:     }  
 7640:     my $map=$navmap->getResourceByUrl($sequence);
 7641:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7642:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
 7643:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 7644:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 7645:     my $resource_error;
 7646:     foreach my $resource (@resources) {
 7647:         my $ressymb;
 7648:         if (ref($resource)) {
 7649:             $ressymb = $resource->symb();
 7650:         } else {
 7651:             $resource_error = 1;
 7652:             last;
 7653:         }
 7654:         my ($analysis,$parts) =
 7655:             &scantron_partids_tograde($resource,$env{'request.course.id'},
 7656:                                       $env{'user.name'},$env{'user.domain'},1,$bubbles_per_row);
 7657:         $grader_partids_by_symb{$ressymb} = $parts;
 7658:         if (ref($analysis) eq 'HASH') {
 7659:             if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 7660:                 $grader_randomlists_by_symb{$ressymb} = 
 7661:                     $analysis->{'parts_withrandomlist'};
 7662:             }
 7663:         }
 7664:     }
 7665:     if ($resource_error) {
 7666:         $r->print(&navmap_errormsg());
 7667:         return '';
 7668:     }
 7669: 
 7670:     my ($uname,$udom);
 7671:     my $result= <<SCANTRONFORM;
 7672: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 7673:   <input type="hidden" name="command" value="scantron_configphase" />
 7674:   $default_form_data
 7675: SCANTRONFORM
 7676:     $r->print($result);
 7677: 
 7678:     my @delayqueue;
 7679:     my (%completedstudents,%scandata);
 7680:     
 7681:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 7682:     my $count=&get_todo_count($scanlines,$scan_data);
 7683:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet Status',
 7684:  				    'Bubblesheet Progress',$count,
 7685: 				    'inline',undef,'scantronupload');
 7686:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 7687: 					  'Processing first student');
 7688:     $r->print('<br />');
 7689:     my $start=&Time::HiRes::time();
 7690:     my $i=-1;
 7691:     my $started;
 7692: 
 7693:     my $nav_error;
 7694:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 7695:     if ($nav_error) {
 7696:         $r->print(&navmap_errormsg());
 7697:         return '';
 7698:     }
 7699: 
 7700:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 7701:     # the user and return.
 7702: 
 7703:     if ($ssi_error) {
 7704: 	$r->print("</form>");
 7705: 	&ssi_print_error($r);
 7706:         &Apache::lonnet::remove_lock($lock);
 7707: 	return '';		# Dunno why the other returns return '' rather than just returning.
 7708:     }
 7709: 
 7710:     my %lettdig = &letter_to_digits();
 7711:     my $numletts = scalar(keys(%lettdig));
 7712: 
 7713:     while ($i<$scanlines->{'count'}) {
 7714:  	($uname,$udom)=('','');
 7715:  	$i++;
 7716:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7717:  	if ($line=~/^[\s\cz]*$/) { next; }
 7718: 	if ($started) {
 7719: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 7720: 						     'last student');
 7721: 	}
 7722: 	$started=1;
 7723:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7724:  						 $scan_data);
 7725:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 7726:  					      \%idmap,$i)) {
 7727:   	    &scantron_add_delay(\@delayqueue,$line,
 7728:  				'Unable to find a student that matches',1);
 7729:  	    next;
 7730:   	}
 7731:  	if (exists $completedstudents{$uname}) {
 7732:  	    &scantron_add_delay(\@delayqueue,$line,
 7733:  				'Student '.$uname.' has multiple sheets',2);
 7734:  	    next;
 7735:  	}
 7736:   	($uname,$udom)=split(/:/,$uname);
 7737: 
 7738:         my (%partids_by_symb,$res_error);
 7739:         foreach my $resource (@resources) {
 7740:             my $ressymb;
 7741:             if (ref($resource)) {
 7742:                 $ressymb = $resource->symb();
 7743:             } else {
 7744:                 $res_error = 1;
 7745:                 last;
 7746:             }
 7747:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 7748:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 7749:                 my ($analysis,$parts) =
 7750:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom,undef,$bubbles_per_row);
 7751:                 $partids_by_symb{$ressymb} = $parts;
 7752:             } else {
 7753:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
 7754:             }
 7755:         }
 7756: 
 7757:         if ($res_error) {
 7758:             &scantron_add_delay(\@delayqueue,$line,
 7759:                                 'An error occurred while grading student '.$uname,2);
 7760:             next;
 7761:         }
 7762: 
 7763: 	&Apache::lonxml::clear_problem_counter();
 7764:   	&Apache::lonnet::appenv($scan_record);
 7765: 
 7766: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 7767: 	    &scantron_putfile($scanlines,$scan_data);
 7768: 	}
 7769: 	
 7770:         my $scancode;
 7771:         if ((exists($scan_record->{'scantron.CODE'})) &&
 7772:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 7773:             $scancode = $scan_record->{'scantron.CODE'};
 7774:         } else {
 7775:             $scancode = '';
 7776:         }
 7777: 
 7778:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 7779:                                    \@resources,\%partids_by_symb,
 7780:                                    $bubbles_per_row) eq 'ssi_error') {
 7781:             $ssi_error = 0; # So end of handler error message does not trigger.
 7782:             $r->print("</form>");
 7783:             &ssi_print_error($r);
 7784:             &Apache::lonnet::remove_lock($lock);
 7785:             return '';      # Why return ''?  Beats me.
 7786:         }
 7787: 
 7788: 	$completedstudents{$uname}={'line'=>$line};
 7789:         if ($env{'form.verifyrecord'}) {
 7790:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 7791:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 7792:             chomp($studentdata);
 7793:             $studentdata =~ s/\r$//;
 7794:             my $studentrecord = '';
 7795:             my $counter = -1;
 7796:             foreach my $resource (@resources) {
 7797:                 my $ressymb = $resource->symb();
 7798:                 ($counter,my $recording) =
 7799:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 7800:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
 7801:                                              \%scantron_config,\%lettdig,$numletts);
 7802:                 $studentrecord .= $recording;
 7803:             }
 7804:             if ($studentrecord ne $studentdata) {
 7805:                 &Apache::lonxml::clear_problem_counter();
 7806:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 7807:                                            \@resources,\%partids_by_symb,
 7808:                                            $bubbles_per_row) eq 'ssi_error') {
 7809:                     $ssi_error = 0; # So end of handler error message does not trigger.
 7810:                     $r->print("</form>");
 7811:                     &ssi_print_error($r);
 7812:                     &Apache::lonnet::remove_lock($lock);
 7813:                     delete($completedstudents{$uname});
 7814:                     return '';
 7815:                 }
 7816:                 $counter = -1;
 7817:                 $studentrecord = '';
 7818:                 foreach my $resource (@resources) {
 7819:                     my $ressymb = $resource->symb();
 7820:                     ($counter,my $recording) =
 7821:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 7822:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 7823:                                                  \%scantron_config,\%lettdig,$numletts);
 7824:                     $studentrecord .= $recording;
 7825:                 }
 7826:                 if ($studentrecord ne $studentdata) {
 7827:                     $r->print('<p><span class="LC_error">');
 7828:                     if ($scancode eq '') {
 7829:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2].',
 7830:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 7831:                     } else {
 7832:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2] and CODE: [_3].',
 7833:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 7834:                     }
 7835:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 7836:                               &Apache::loncommon::start_data_table_header_row()."\n".
 7837:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 7838:                               &Apache::loncommon::end_data_table_header_row()."\n".
 7839:                               &Apache::loncommon::start_data_table_row().
 7840:                               '<td>'.&mt('Bubble Sheet').'</td>'.
 7841:                               '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
 7842:                               &Apache::loncommon::end_data_table_row().
 7843:                               &Apache::loncommon::start_data_table_row().
 7844:                               '<td>Stored submissions</td>'.
 7845:                               '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
 7846:                               &Apache::loncommon::end_data_table_row().
 7847:                               &Apache::loncommon::end_data_table().'</p>');
 7848:                 } else {
 7849:                     $r->print('<br /><span class="LC_warning">'.
 7850:                              &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 />'.
 7851:                              &mt("As a consequence, this user's submission history records two tries.").
 7852:                                  '</span><br />');
 7853:                 }
 7854:             }
 7855:         }
 7856:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 7857:     } continue {
 7858: 	&Apache::lonxml::clear_problem_counter();
 7859: 	&Apache::lonnet::delenv('scantron.');
 7860:     }
 7861:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 7862:     &Apache::lonnet::remove_lock($lock);
 7863: #    my $lasttime = &Time::HiRes::time()-$start;
 7864: #    $r->print("<p>took $lasttime</p>");
 7865: 
 7866:     $r->print("</form>");
 7867:     return '';
 7868: }
 7869: 
 7870: sub graders_resources_pass {
 7871:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
 7872:         $bubbles_per_row) = @_;
 7873:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
 7874:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
 7875:         foreach my $resource (@{$resources}) {
 7876:             my $ressymb = $resource->symb();
 7877:             my ($analysis,$parts) =
 7878:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
 7879:                                           $env{'user.name'},$env{'user.domain'},1,$bubbles_per_row);
 7880:             $grader_partids_by_symb->{$ressymb} = $parts;
 7881:             if (ref($analysis) eq 'HASH') {
 7882:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 7883:                     $grader_randomlists_by_symb->{$ressymb} =
 7884:                         $analysis->{'parts_withrandomlist'};
 7885:                 }
 7886:             }
 7887:         }
 7888:     }
 7889:     return;
 7890: }
 7891: 
 7892: sub grade_student_bubbles {
 7893:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row) = @_;
 7894: # Walk folder as student here to get resources in order student sees.
 7895:     if (ref($resources) eq 'ARRAY') {
 7896:         my $count = 0;
 7897:         foreach my $resource (@{$resources}) {
 7898:             my $ressymb = $resource->symb();
 7899:             my %form = ('submitted'      => 'scantron',
 7900:                         'grade_target'   => 'grade',
 7901:                         'grade_username' => $uname,
 7902:                         'grade_domain'   => $udom,
 7903:                         'grade_courseid' => $env{'request.course.id'},
 7904:                         'grade_symb'     => $ressymb,
 7905:                         'CODE'           => $scancode
 7906:                        );
 7907:             if ($bubbles_per_row ne '') {
 7908:                 $form{'bubbles_per_row'} = $bubbles_per_row;
 7909:             }
 7910:             if (ref($parts) eq 'HASH') {
 7911:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 7912:                     foreach my $part (@{$parts->{$ressymb}}) {
 7913:                         $form{'scantron_questnum_start.'.$part} =
 7914:                             1+$env{'form.scantron.first_bubble_line.'.$count};
 7915:                         $count++;
 7916:                     }
 7917:                 }
 7918:             }
 7919:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 7920:             return 'ssi_error' if ($ssi_error);
 7921:             last if (&Apache::loncommon::connection_aborted($r));
 7922:         }
 7923:     }
 7924:     return;
 7925: }
 7926: 
 7927: sub scantron_upload_scantron_data {
 7928:     my ($r,$symb)=@_;
 7929:     my $dom = $env{'request.role.domain'};
 7930:     my $domdesc = &Apache::lonnet::domain($dom,'description');
 7931:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
 7932:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 7933: 							  'domainid',
 7934: 							  'coursename',$dom);
 7935:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
 7936:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
 7937:     my $default_form_data=&defaultFormData($symb);
 7938:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
 7939:     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.");
 7940:     $r->print(&Apache::lonhtmlcommon::scripttag('
 7941:     function checkUpload(formname) {
 7942: 	if (formname.upfile.value == "") {
 7943: 	    alert("'.$nofile_alert.'");
 7944: 	    return false;
 7945: 	}
 7946:         if (formname.courseid.value == "") {
 7947:             alert("'.$nocourseid_alert.'");
 7948:             return false;
 7949:         }
 7950: 	formname.submit();
 7951:     }
 7952: 
 7953:     function ToSyllabus() {
 7954:         var cdom = '."'$dom'".';
 7955:         var cnum = document.rules.courseid.value;
 7956:         if (cdom == "" || cdom == null) {
 7957:             return;
 7958:         }
 7959:         if (cnum == "" || cnum == null) {
 7960:            return;
 7961:         }
 7962:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
 7963:                             "height=350,width=350,scrollbars=yes,menubar=no");
 7964:         return;
 7965:     }
 7966: 
 7967: '));
 7968:     $r->print('
 7969: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
 7970: 
 7971: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 7972: '.$default_form_data.
 7973:   &Apache::lonhtmlcommon::start_pick_box().
 7974:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
 7975:   '<input name="courseid" type="text" size="30" />'.$select_link.
 7976:   &Apache::lonhtmlcommon::row_closure().
 7977:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
 7978:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
 7979:   &Apache::lonhtmlcommon::row_closure().
 7980:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
 7981:   '<input name="domainid" type="hidden" />'.$domdesc.
 7982:   &Apache::lonhtmlcommon::row_closure().
 7983:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
 7984:   '<input type="file" name="upfile" size="50" />'.
 7985:   &Apache::lonhtmlcommon::row_closure(1).
 7986:   &Apache::lonhtmlcommon::end_pick_box().'<br />
 7987: 
 7988: <input name="command" value="scantronupload_save" type="hidden" />
 7989: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 7990: </form>
 7991: ');
 7992:     return '';
 7993: }
 7994: 
 7995: 
 7996: sub scantron_upload_scantron_data_save {
 7997:     my($r,$symb)=@_;
 7998:     my $doanotherupload=
 7999: 	'<br /><form action="/adm/grades" method="post">'."\n".
 8000: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 8001: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 8002: 	'</form>'."\n";
 8003:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 8004: 	!&Apache::lonnet::allowed('usc',
 8005: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 8006: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
 8007: 	unless ($symb) {
 8008: 	    $r->print($doanotherupload);
 8009: 	}
 8010: 	return '';
 8011:     }
 8012:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 8013:     my $uploadedfile;
 8014:     $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
 8015:     if (length($env{'form.upfile'}) < 2) {
 8016:         $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>'));
 8017:     } else {
 8018:         my $result = 
 8019:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
 8020:                                             $env{'form.courseid'},$env{'form.domainid'});
 8021: 	if ($result =~ m{^/uploaded/}) {
 8022: 	    $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
 8023:                           '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
 8024: 			  '<span class="LC_filename">'.$result.'</span>'));
 8025:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
 8026:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
 8027:                                                        $env{'form.courseid'},$uploadedfile));
 8028: 	} else {
 8029: 	    $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
 8030:                           '<span class="LC_error">','</span>',$result,
 8031: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 8032: 	}
 8033:     }
 8034:     if ($symb) {
 8035: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
 8036:     } else {
 8037: 	$r->print($doanotherupload);
 8038:     }
 8039:     return '';
 8040: }
 8041: 
 8042: sub validate_uploaded_scantron_file {
 8043:     my ($cdom,$cname,$fname) = @_;
 8044:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
 8045:     my @lines;
 8046:     if ($scanlines ne '-1') {
 8047:         @lines=split("\n",$scanlines,-1);
 8048:     }
 8049:     my $output;
 8050:     if (@lines) {
 8051:         my (%counts,$max_match_format);
 8052:         my ($max_match_count,$max_match_pct) = (0,0);
 8053:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
 8054:         my %idmap = &username_to_idmap($classlist);
 8055:         foreach my $key (keys(%idmap)) {
 8056:             my $lckey = lc($key);
 8057:             $idmap{$lckey} = $idmap{$key};
 8058:         }
 8059:         my %unique_formats;
 8060:         my @formatlines = &get_scantronformat_file();
 8061:         foreach my $line (@formatlines) {
 8062:             chomp($line);
 8063:             my @config = split(/:/,$line);
 8064:             my $idstart = $config[5];
 8065:             my $idlength = $config[6];
 8066:             if (($idstart ne '') && ($idlength > 0)) {
 8067:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
 8068:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
 8069:                 } else {
 8070:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
 8071:                 }
 8072:             }
 8073:         }
 8074:         foreach my $key (keys(%unique_formats)) {
 8075:             my ($idstart,$idlength) = split(':',$key);
 8076:             %{$counts{$key}} = (
 8077:                                'found'   => 0,
 8078:                                'total'   => 0,
 8079:                               );
 8080:             foreach my $line (@lines) {
 8081:                 next if ($line =~ /^#/);
 8082:                 next if ($line =~ /^[\s\cz]*$/);
 8083:                 my $id = substr($line,$idstart-1,$idlength);
 8084:                 $id = lc($id);
 8085:                 if (exists($idmap{$id})) {
 8086:                     $counts{$key}{'found'} ++;
 8087:                 }
 8088:                 $counts{$key}{'total'} ++;
 8089:             }
 8090:             if ($counts{$key}{'total'}) {
 8091:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
 8092:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
 8093:                     $max_match_pct = $percent_match;
 8094:                     $max_match_format = $key;
 8095:                     $max_match_count = $counts{$key}{'total'};
 8096:                 }
 8097:             }
 8098:         }
 8099:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
 8100:             my $format_descs;
 8101:             my $numwithformat = @{$unique_formats{$max_match_format}};
 8102:             for (my $i=0; $i<$numwithformat; $i++) {
 8103:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
 8104:                 if ($i<$numwithformat-2) {
 8105:                     $format_descs .= '"<i>'.$desc.'</i>", ';
 8106:                 } elsif ($i==$numwithformat-2) {
 8107:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
 8108:                 } elsif ($i==$numwithformat-1) {
 8109:                     $format_descs .= '"<i>'.$desc.'</i>"';
 8110:                 }
 8111:             }
 8112:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
 8113:             $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).
 8114:                        '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
 8115:                        '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
 8116:                        '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
 8117:                                   '<i>'.$cdom.'</i>').'</li>'.
 8118:                        '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
 8119:                        '<li>'.&mt('The course roster is not up to date').'</li>'.
 8120:                        '</ul>';
 8121:         }
 8122:     } else {
 8123:         $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
 8124:     }
 8125:     return $output;
 8126: }
 8127: 
 8128: sub valid_file {
 8129:     my ($requested_file)=@_;
 8130:     foreach my $filename (sort(&scantron_filenames())) {
 8131: 	if ($requested_file eq $filename) { return 1; }
 8132:     }
 8133:     return 0;
 8134: }
 8135: 
 8136: sub scantron_download_scantron_data {
 8137:     my ($r,$symb)=@_;
 8138:     my $default_form_data=&defaultFormData($symb);
 8139:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 8140:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8141:     my $file=$env{'form.scantron_selectfile'};
 8142:     if (! &valid_file($file)) {
 8143: 	$r->print('
 8144: 	<p>
 8145: 	    '.&mt('The requested file name was invalid.').'
 8146:         </p>
 8147: ');
 8148: 	return;
 8149:     }
 8150:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 8151:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 8152:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 8153:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 8154:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 8155:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 8156:     $r->print('
 8157:     <p>
 8158: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
 8159: 	      '<a href="'.$orig.'">','</a>').'
 8160:     </p>
 8161:     <p>
 8162: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 8163: 	      '<a href="'.$corrected.'">','</a>').'
 8164:     </p>
 8165:     <p>
 8166: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 8167: 	      '<a href="'.$skipped.'">','</a>').'
 8168:     </p>
 8169: ');
 8170:     return '';
 8171: }
 8172: 
 8173: sub checkscantron_results {
 8174:     my ($r,$symb) = @_;
 8175:     if (!$symb) {return '';}
 8176:     my $cid = $env{'request.course.id'};
 8177:     my %lettdig = &letter_to_digits();
 8178:     my $numletts = scalar(keys(%lettdig));
 8179:     my $cnum = $env{'course.'.$cid.'.num'};
 8180:     my $cdom = $env{'course.'.$cid.'.domain'};
 8181:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8182:     my %record;
 8183:     my %scantron_config =
 8184:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
 8185:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8186:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
 8187:     my $classlist=&Apache::loncoursedata::get_classlist();
 8188:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 8189:     my $navmap=Apache::lonnavmaps::navmap->new();
 8190:     unless (ref($navmap)) {
 8191:         $r->print(&navmap_errormsg());
 8192:         return '';
 8193:     }
 8194:     my $map=$navmap->getResourceByUrl($sequence);
 8195:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8196:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
 8197:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,                             \%grader_randomlists_by_symb);
 8198: 
 8199:     my ($uname,$udom);
 8200:     my (%scandata,%lastname,%bylast);
 8201:     $r->print('
 8202: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 8203: 
 8204:     my @delayqueue;
 8205:     my %completedstudents;
 8206: 
 8207:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
 8208:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet/Submissions Comparison Status',
 8209:                                     'Progress of Bubblesheet Data/Submission Records Comparison',$count,
 8210:                                     'inline',undef,'checkscantron');
 8211:     my ($username,$domain,$started);
 8212:     my $nav_error;
 8213:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 8214:     if ($nav_error) {
 8215:         $r->print(&navmap_errormsg());
 8216:         return '';
 8217:     }
 8218: 
 8219:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 8220:                                           'Processing first student');
 8221:     my $start=&Time::HiRes::time();
 8222:     my $i=-1;
 8223: 
 8224:     while ($i<$scanlines->{'count'}) {
 8225:         ($username,$domain,$uname)=('','','');
 8226:         $i++;
 8227:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 8228:         if ($line=~/^[\s\cz]*$/) { next; }
 8229:         if ($started) {
 8230:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 8231:                                                      'last student');
 8232:         }
 8233:         $started=1;
 8234:         my $scan_record=
 8235:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 8236:                                                      $scan_data);
 8237:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
 8238:                                                               \%idmap,$i)) {
 8239:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 8240:                                 'Unable to find a student that matches',1);
 8241:             next;
 8242:         }
 8243:         if (exists $completedstudents{$uname}) {
 8244:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 8245:                                 'Student '.$uname.' has multiple sheets',2);
 8246:             next;
 8247:         }
 8248:         my $pid = $scan_record->{'scantron.ID'};
 8249:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 8250:         push(@{$bylast{$lastname{$pid}}},$pid);
 8251:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 8252:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 8253:         chomp($scandata{$pid});
 8254:         $scandata{$pid} =~ s/\r$//;
 8255:         ($username,$domain)=split(/:/,$uname);
 8256:         my $counter = -1;
 8257:         foreach my $resource (@resources) {
 8258:             my $parts;
 8259:             my $ressymb = $resource->symb();
 8260:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 8261:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 8262:                 (my $analysis,$parts) =
 8263:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$username,$domain,undef,$bubbles_per_row);
 8264:             } else {
 8265:                 $parts = $grader_partids_by_symb{$ressymb};
 8266:             }
 8267:             ($counter,my $recording) =
 8268:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
 8269:                                          $scandata{$pid},$parts,
 8270:                                          \%scantron_config,\%lettdig,$numletts);
 8271:             $record{$pid} .= $recording;
 8272:         }
 8273:     }
 8274:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 8275:     $r->print('<br />');
 8276:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 8277:     $passed = 0;
 8278:     $failed = 0;
 8279:     $numstudents = 0;
 8280:     foreach my $last (sort(keys(%bylast))) {
 8281:         if (ref($bylast{$last}) eq 'ARRAY') {
 8282:             foreach my $pid (sort(@{$bylast{$last}})) {
 8283:                 my $showscandata = $scandata{$pid};
 8284:                 my $showrecord = $record{$pid};
 8285:                 $showscandata =~ s/\s/&nbsp;/g;
 8286:                 $showrecord =~ s/\s/&nbsp;/g;
 8287:                 if ($scandata{$pid} eq $record{$pid}) {
 8288:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 8289:                     $okstudents .= '<tr class="'.$css_class.'">'.
 8290: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 8291: '</tr>'."\n".
 8292: '<tr class="'.$css_class.'">'."\n".
 8293: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
 8294:                     $passed ++;
 8295:                 } else {
 8296:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
 8297:                     $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".
 8298: '</tr>'."\n".
 8299: '<tr class="'.$css_class.'">'."\n".
 8300: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
 8301: '</tr>'."\n";
 8302:                     $failed ++;
 8303:                 }
 8304:                 $numstudents ++;
 8305:             }
 8306:         }
 8307:     }
 8308:     $r->print(
 8309:         '<p>'
 8310:        .&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).',
 8311:             '<b>',
 8312:             $numstudents,
 8313:             '</b>',
 8314:             $env{'form.scantron_maxbubble'})
 8315:        .'</p>'
 8316:     );
 8317:     $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>');
 8318:     if ($passed) {
 8319:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
 8320:         $r->print(&Apache::loncommon::start_data_table()."\n".
 8321:                  &Apache::loncommon::start_data_table_header_row()."\n".
 8322:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 8323:                  &Apache::loncommon::end_data_table_header_row()."\n".
 8324:                  $okstudents."\n".
 8325:                  &Apache::loncommon::end_data_table().'<br />');
 8326:     }
 8327:     if ($failed) {
 8328:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
 8329:         $r->print(&Apache::loncommon::start_data_table()."\n".
 8330:                  &Apache::loncommon::start_data_table_header_row()."\n".
 8331:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 8332:                  &Apache::loncommon::end_data_table_header_row()."\n".
 8333:                  $badstudents."\n".
 8334:                  &Apache::loncommon::end_data_table()).'<br />'.
 8335:                  &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.');  
 8336:     }
 8337:     $r->print('</form><br />');
 8338:     return;
 8339: }
 8340: 
 8341: sub verify_scantron_grading {
 8342:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
 8343:         $scantron_config,$lettdig,$numletts) = @_;
 8344:     my ($record,%expected,%startpos);
 8345:     return ($counter,$record) if (!ref($resource));
 8346:     return ($counter,$record) if (!$resource->is_problem());
 8347:     my $symb = $resource->symb();
 8348:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
 8349:     foreach my $part_id (@{$partids}) {
 8350:         $counter ++;
 8351:         $expected{$part_id} = 0;
 8352:         if ($env{"form.scantron.sub_bubblelines.$counter"}) {
 8353:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
 8354:             foreach my $item (@sub_lines) {
 8355:                 $expected{$part_id} += $item;
 8356:             }
 8357:         } else {
 8358:             $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
 8359:         }
 8360:         $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
 8361:     }
 8362:     if ($symb) {
 8363:         my %recorded;
 8364:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
 8365:         if ($returnhash{'version'}) {
 8366:             my %lasthash=();
 8367:             my $version;
 8368:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 8369:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 8370:                     $lasthash{$key}=$returnhash{$version.':'.$key};
 8371:                 }
 8372:             }
 8373:             foreach my $key (keys(%lasthash)) {
 8374:                 if ($key =~ /\.scantron$/) {
 8375:                     my $value = &unescape($lasthash{$key});
 8376:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
 8377:                     if ($value eq '') {
 8378:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
 8379:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
 8380:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8381:                             }
 8382:                         }
 8383:                     } else {
 8384:                         my @tocheck;
 8385:                         my @items = split(//,$value);
 8386:                         if (($scantron_config->{'Qon'} eq 'letter') ||
 8387:                             ($scantron_config->{'Qon'} eq 'number')) {
 8388:                             if (@items < $expected{$part_id}) {
 8389:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
 8390:                                 my @singles = split(//,$fragment);
 8391:                                 foreach my $pos (@singles) {
 8392:                                     if ($pos eq ' ') {
 8393:                                         push(@tocheck,$pos);
 8394:                                     } else {
 8395:                                         my $next = shift(@items);
 8396:                                         push(@tocheck,$next);
 8397:                                     }
 8398:                                 }
 8399:                             } else {
 8400:                                 @tocheck = @items;
 8401:                             }
 8402:                             foreach my $letter (@tocheck) {
 8403:                                 if ($scantron_config->{'Qon'} eq 'letter') {
 8404:                                     if ($letter !~ /^[A-J]$/) {
 8405:                                         $letter = $scantron_config->{'Qoff'};
 8406:                                     }
 8407:                                     $recorded{$part_id} .= $letter;
 8408:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
 8409:                                     my $digit;
 8410:                                     if ($letter !~ /^[A-J]$/) {
 8411:                                         $digit = $scantron_config->{'Qoff'};
 8412:                                     } else {
 8413:                                         $digit = $lettdig->{$letter};
 8414:                                     }
 8415:                                     $recorded{$part_id} .= $digit;
 8416:                                 }
 8417:                             }
 8418:                         } else {
 8419:                             @tocheck = @items;
 8420:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
 8421:                                 my $curr_sub = shift(@tocheck);
 8422:                                 my $digit;
 8423:                                 if ($curr_sub =~ /^[A-J]$/) {
 8424:                                     $digit = $lettdig->{$curr_sub}-1;
 8425:                                 }
 8426:                                 if ($curr_sub eq 'J') {
 8427:                                     $digit += scalar($numletts);
 8428:                                 }
 8429:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 8430:                                     if ($j == $digit) {
 8431:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
 8432:                                     } else {
 8433:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8434:                                     }
 8435:                                 }
 8436:                             }
 8437:                         }
 8438:                     }
 8439:                 }
 8440:             }
 8441:         }
 8442:         foreach my $part_id (@{$partids}) {
 8443:             if ($recorded{$part_id} eq '') {
 8444:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
 8445:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 8446:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8447:                     }
 8448:                 }
 8449:             }
 8450:             $record .= $recorded{$part_id};
 8451:         }
 8452:     }
 8453:     return ($counter,$record);
 8454: }
 8455: 
 8456: sub letter_to_digits { 
 8457:     my %lettdig = (
 8458:                     A => 1,
 8459:                     B => 2,
 8460:                     C => 3,
 8461:                     D => 4,
 8462:                     E => 5,
 8463:                     F => 6,
 8464:                     G => 7,
 8465:                     H => 8,
 8466:                     I => 9,
 8467:                     J => 0,
 8468:                   );
 8469:     return %lettdig;
 8470: }
 8471: 
 8472: 
 8473: #-------- end of section for handling grading scantron forms -------
 8474: #
 8475: #-------------------------------------------------------------------
 8476: 
 8477: #-------------------------- Menu interface -------------------------
 8478: #
 8479: #--- Href with symb and command ---
 8480: 
 8481: sub href_symb_cmd {
 8482:     my ($symb,$cmd)=@_;
 8483:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&command='.$cmd;
 8484: }
 8485: 
 8486: sub grading_menu {
 8487:     my ($request,$symb) = @_;
 8488:     if (!$symb) {return '';}
 8489: 
 8490:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 8491:                   'command'=>'individual');
 8492:     
 8493:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8494: 
 8495:     $fields{'command'}='ungraded';
 8496:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8497: 
 8498:     $fields{'command'}='table';
 8499:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8500: 
 8501:     $fields{'command'}='all_for_one';
 8502:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8503: 
 8504:     $fields{'command'}='downloadfilesselect';
 8505:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8506: 
 8507:     $fields{'command'} = 'csvform';
 8508:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8509:     
 8510:     $fields{'command'} = 'processclicker';
 8511:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8512:     
 8513:     $fields{'command'} = 'scantron_selectphase';
 8514:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8515: 
 8516:     $fields{'command'} = 'initialverifyreceipt';
 8517:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8518:     
 8519:     my @menu = ({	categorytitle=>'Hand Grading',
 8520:             items =>[
 8521:                         {	linktext => 'Select individual students to grade',
 8522:                     		url => $url1a,
 8523:                     		permission => 'F',
 8524:                     		icon => 'grade_students.png',
 8525:                     		linktitle => 'Grade current resource for a selection of students.'
 8526:                         }, 
 8527:                         {       linktext => 'Grade ungraded submissions.',
 8528:                                 url => $url1b,
 8529:                                 permission => 'F',
 8530:                                 icon => 'ungrade_sub.png',
 8531:                                 linktitle => 'Grade all submissions that have not been graded yet.'
 8532:                         },
 8533: 
 8534:                         {       linktext => 'Grading table',
 8535:                                 url => $url1c,
 8536:                                 permission => 'F',
 8537:                                 icon => 'grading_table.png',
 8538:                                 linktitle => 'Grade current resource for all students.'
 8539:                         },
 8540:                         {       linktext => 'Grade page/folder for one student',
 8541:                                 url => $url1d,
 8542:                                 permission => 'F',
 8543:                                 icon => 'grade_PageFolder.png',
 8544:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
 8545:                         },
 8546:                         {       linktext => 'Download submissions',
 8547:                                 url => $url1e,
 8548:                                 permission => 'F',
 8549:                                 icon => 'download_sub.png',
 8550:                                 linktitle => 'Download all students submissions.'
 8551:                         }]},
 8552:                          { categorytitle=>'Automated Grading',
 8553:                items =>[
 8554: 
 8555:                 	    {	linktext => 'Upload Scores',
 8556:                     		url => $url2,
 8557:                     		permission => 'F',
 8558:                     		icon => 'uploadscores.png',
 8559:                     		linktitle => 'Specify a file containing the class scores for current resource.'
 8560:                 	    },
 8561:                 	    {	linktext => 'Process Clicker',
 8562:                     		url => $url3,
 8563:                     		permission => 'F',
 8564:                     		icon => 'addClickerInfoFile.png',
 8565:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
 8566:                 	    },
 8567:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
 8568:                     		url => $url4,
 8569:                     		permission => 'F',
 8570:                     		icon => 'bubblesheet.png',
 8571:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
 8572:                 	    },
 8573:                             {   linktext => 'Verify Receipt Number',
 8574:                                 url => $url5,
 8575:                                 permission => 'F',
 8576:                                 icon => 'receipt_number.png',
 8577:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
 8578:                             }
 8579: 
 8580:                     ]
 8581:             });
 8582: 
 8583:     # Create the menu
 8584:     my $Str;
 8585:     $Str .= '<form method="post" action="" name="gradingMenu">';
 8586:     $Str .= '<input type="hidden" name="command" value="" />'.
 8587:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 8588: 
 8589:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
 8590:     return $Str;    
 8591: }
 8592: 
 8593: 
 8594: sub ungraded {
 8595:     my ($request)=@_;
 8596:     &submit_options($request);
 8597: }
 8598: 
 8599: sub submit_options_sequence {
 8600:     my ($request,$symb) = @_;
 8601:     if (!$symb) {return '';}
 8602:     &commonJSfunctions($request);
 8603:     my $result;
 8604: 
 8605:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8606:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 8607:     $result.=&selectfield(0).
 8608:             '<input type="hidden" name="command" value="pickStudentPage" />
 8609:             <div>
 8610:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 8611:             </div>
 8612:         </div>
 8613:   </form>';
 8614:     return $result;
 8615: }
 8616: 
 8617: sub submit_options_table {
 8618:     my ($request,$symb) = @_;
 8619:     if (!$symb) {return '';}
 8620:     &commonJSfunctions($request);
 8621:     my $result;
 8622: 
 8623:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8624:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 8625: 
 8626:     $result.=&selectfield(0).
 8627:             '<input type="hidden" name="command" value="viewgrades" />
 8628:             <div>
 8629:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 8630:             </div>
 8631:         </div>
 8632:   </form>';
 8633:     return $result;
 8634: }
 8635: 
 8636: sub submit_options_download {
 8637:     my ($request,$symb) = @_;
 8638:     if (!$symb) {return '';}
 8639: 
 8640:     &commonJSfunctions($request);
 8641: 
 8642:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8643:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 8644:     $result.='
 8645: <h2>
 8646:   '.&mt('Select Students for Which to Download Submissions').'
 8647: </h2>'.&selectfield(1).'
 8648:                 <input type="hidden" name="command" value="downloadfileslink" /> 
 8649:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 8650:             </div>
 8651:           </div>
 8652: 
 8653: 
 8654:   </form>';
 8655:     return $result;
 8656: }
 8657: 
 8658: #--- Displays the submissions first page -------
 8659: sub submit_options {
 8660:     my ($request,$symb) = @_;
 8661:     if (!$symb) {return '';}
 8662: 
 8663:     &commonJSfunctions($request);
 8664:     my $result;
 8665: 
 8666:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8667: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 8668:     $result.=&selectfield(1).'
 8669:                 <input type="hidden" name="command" value="submission" /> 
 8670: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
 8671:             </div>
 8672:           </div>
 8673: 
 8674: 
 8675:   </form>';
 8676:     return $result;
 8677: }
 8678: 
 8679: sub selectfield {
 8680:    my ($full)=@_;
 8681:    my %options = 
 8682:           (&Apache::lonlocal::texthash(
 8683:              'yes'       => 'with submissions',
 8684:              'queued'    => 'in grading queue',
 8685:              'graded'    => 'with ungraded submissions',
 8686:              'incorrect' => 'with incorrect submissions',
 8687:              'all'       => 'with any status'),
 8688:              'select_form_order' => ['yes','queued','graded','incorrect','all']);
 8689:    my $result='<div class="LC_columnSection">
 8690:   
 8691:     <fieldset>
 8692:       <legend>
 8693:        '.&mt('Sections').'
 8694:       </legend>
 8695:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
 8696:     </fieldset>
 8697:   
 8698:     <fieldset>
 8699:       <legend>
 8700:         '.&mt('Groups').'
 8701:       </legend>
 8702:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
 8703:     </fieldset>
 8704:   
 8705:     <fieldset>
 8706:       <legend>
 8707:         '.&mt('Access Status').'
 8708:       </legend>
 8709:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
 8710:     </fieldset>';
 8711:     if ($full) {
 8712:        $result.='
 8713:     <fieldset>
 8714:       <legend>
 8715:         '.&mt('Submission Status').'
 8716:       </legend>'.
 8717:        &Apache::loncommon::select_form('all','submitonly',\%options).
 8718:    '</fieldset>';
 8719:     }
 8720:     $result.='</div><br />';
 8721:     return $result;
 8722: }
 8723: 
 8724: sub reset_perm {
 8725:     undef(%perm);
 8726: }
 8727: 
 8728: sub init_perm {
 8729:     &reset_perm();
 8730:     foreach my $test_perm ('vgr','mgr','opa') {
 8731: 
 8732: 	my $scope = $env{'request.course.id'};
 8733: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
 8734: 
 8735: 	    $scope .= '/'.$env{'request.course.sec'};
 8736: 	    if ( $perm{$test_perm}=
 8737: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
 8738: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
 8739: 	    } else {
 8740: 		delete($perm{$test_perm});
 8741: 	    }
 8742: 	}
 8743:     }
 8744: }
 8745: 
 8746: sub gather_clicker_ids {
 8747:     my %clicker_ids;
 8748: 
 8749:     my $classlist = &Apache::loncoursedata::get_classlist();
 8750: 
 8751:     # Set up a couple variables.
 8752:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
 8753:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
 8754:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
 8755: 
 8756:     foreach my $student (keys(%$classlist)) {
 8757:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
 8758:         my $username = $classlist->{$student}->[$username_idx];
 8759:         my $domain   = $classlist->{$student}->[$domain_idx];
 8760:         my $clickers =
 8761: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
 8762:         foreach my $id (split(/\,/,$clickers)) {
 8763:             $id=~s/^[\#0]+//;
 8764:             $id=~s/[\-\:]//g;
 8765:             if (exists($clicker_ids{$id})) {
 8766: 		$clicker_ids{$id}.=','.$username.':'.$domain;
 8767:             } else {
 8768: 		$clicker_ids{$id}=$username.':'.$domain;
 8769:             }
 8770:         }
 8771:     }
 8772:     return %clicker_ids;
 8773: }
 8774: 
 8775: sub gather_adv_clicker_ids {
 8776:     my %clicker_ids;
 8777:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 8778:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8779:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
 8780:     foreach my $element (sort(keys(%coursepersonnel))) {
 8781:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
 8782:             my ($puname,$pudom)=split(/\:/,$person);
 8783:             my $clickers =
 8784: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
 8785:             foreach my $id (split(/\,/,$clickers)) {
 8786: 		$id=~s/^[\#0]+//;
 8787:                 $id=~s/[\-\:]//g;
 8788: 		if (exists($clicker_ids{$id})) {
 8789: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
 8790: 		} else {
 8791: 		    $clicker_ids{$id}=$puname.':'.$pudom;
 8792: 		}
 8793:             }
 8794:         }
 8795:     }
 8796:     return %clicker_ids;
 8797: }
 8798: 
 8799: sub clicker_grading_parameters {
 8800:     return ('gradingmechanism' => 'scalar',
 8801:             'upfiletype' => 'scalar',
 8802:             'specificid' => 'scalar',
 8803:             'pcorrect' => 'scalar',
 8804:             'pincorrect' => 'scalar');
 8805: }
 8806: 
 8807: sub process_clicker {
 8808:     my ($r,$symb)=@_;
 8809:     if (!$symb) {return '';}
 8810:     my $result=&checkforfile_js();
 8811:     $result.=&Apache::loncommon::start_data_table().
 8812:              &Apache::loncommon::start_data_table_header_row().
 8813:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
 8814:              &Apache::loncommon::end_data_table_header_row().
 8815:              &Apache::loncommon::start_data_table_row()."<td>\n";
 8816: # Attempt to restore parameters from last session, set defaults if not present
 8817:     my %Saveable_Parameters=&clicker_grading_parameters();
 8818:     &Apache::loncommon::restore_course_settings('grades_clicker',
 8819:                                                  \%Saveable_Parameters);
 8820:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
 8821:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
 8822:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
 8823:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
 8824: 
 8825:     my %checked;
 8826:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
 8827:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
 8828:           $checked{$gradingmechanism}=' checked="checked"';
 8829:        }
 8830:     }
 8831: 
 8832:     my $upload=&mt("Evaluate File");
 8833:     my $type=&mt("Type");
 8834:     my $attendance=&mt("Award points just for participation");
 8835:     my $personnel=&mt("Correctness determined from response by course personnel");
 8836:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
 8837:     my $given=&mt("Correctness determined from given list of answers").' '.
 8838:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
 8839:     my $pcorrect=&mt("Percentage points for correct solution");
 8840:     my $pincorrect=&mt("Percentage points for incorrect solution");
 8841:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
 8842: 						   {'iclicker' => 'i>clicker',
 8843:                                                     'interwrite' => 'interwrite PRS'});
 8844:     $symb = &Apache::lonenc::check_encrypt($symb);
 8845:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
 8846: function sanitycheck() {
 8847: // Accept only integer percentages
 8848:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
 8849:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
 8850: // Find out grading choice
 8851:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8852:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
 8853:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
 8854:       }
 8855:    }
 8856: // By default, new choice equals user selection
 8857:    newgradingchoice=gradingchoice;
 8858: // Not good to give more points for false answers than correct ones
 8859:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
 8860:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
 8861:    }
 8862: // If new choice is attendance only, and old choice was correctness-based, restore defaults
 8863:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
 8864:       document.forms.gradesupload.pcorrect.value=100;
 8865:       document.forms.gradesupload.pincorrect.value=100;
 8866:    }
 8867: // If the values are different, cannot be attendance only
 8868:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
 8869:        (gradingchoice=='attendance')) {
 8870:        newgradingchoice='personnel';
 8871:    }
 8872: // Change grading choice to new one
 8873:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8874:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
 8875:          document.forms.gradesupload.gradingmechanism[i].checked=true;
 8876:       } else {
 8877:          document.forms.gradesupload.gradingmechanism[i].checked=false;
 8878:       }
 8879:    }
 8880: // Remember the old state
 8881:    document.forms.gradesupload.waschecked.value=newgradingchoice;
 8882: }
 8883: ENDUPFORM
 8884:     $result.= <<ENDUPFORM;
 8885: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 8886: <input type="hidden" name="symb" value="$symb" />
 8887: <input type="hidden" name="command" value="processclickerfile" />
 8888: <input type="file" name="upfile" size="50" />
 8889: <br /><label>$type: $selectform</label>
 8890: ENDUPFORM
 8891:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
 8892:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
 8893:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
 8894: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
 8895: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
 8896: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
 8897: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
 8898: <br />&nbsp;&nbsp;&nbsp;
 8899: <input type="text" name="givenanswer" size="50" />
 8900: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
 8901: ENDGRADINGFORM
 8902:          $result.='</td>'.&Apache::loncommon::end_data_table_row().
 8903:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
 8904:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
 8905: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
 8906: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 8907: </form>'
 8908: ENDPERCFORM
 8909:     $result.='</td>'.
 8910:              &Apache::loncommon::end_data_table_row().
 8911:              &Apache::loncommon::end_data_table();
 8912:     return $result;
 8913: }
 8914: 
 8915: sub process_clicker_file {
 8916:     my ($r,$symb)=@_;
 8917:     if (!$symb) {return '';}
 8918: 
 8919:     my %Saveable_Parameters=&clicker_grading_parameters();
 8920:     &Apache::loncommon::store_course_settings('grades_clicker',
 8921:                                               \%Saveable_Parameters);
 8922:     my $result='';
 8923:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
 8924: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
 8925: 	return $result;
 8926:     }
 8927:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
 8928:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
 8929:         return $result;
 8930:     }
 8931:     my $foundgiven=0;
 8932:     if ($env{'form.gradingmechanism'} eq 'given') {
 8933:         $env{'form.givenanswer'}=~s/^\s*//gs;
 8934:         $env{'form.givenanswer'}=~s/\s*$//gs;
 8935:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
 8936:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
 8937:         my @answers=split(/\,/,$env{'form.givenanswer'});
 8938:         $foundgiven=$#answers+1;
 8939:     }
 8940:     my %clicker_ids=&gather_clicker_ids();
 8941:     my %correct_ids;
 8942:     if ($env{'form.gradingmechanism'} eq 'personnel') {
 8943: 	%correct_ids=&gather_adv_clicker_ids();
 8944:     }
 8945:     if ($env{'form.gradingmechanism'} eq 'specific') {
 8946: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
 8947: 	   $correct_id=~tr/a-z/A-Z/;
 8948: 	   $correct_id=~s/\s//gs;
 8949: 	   $correct_id=~s/^[\#0]+//;
 8950:            $correct_id=~s/[\-\:]//g;
 8951:            if ($correct_id) {
 8952: 	      $correct_ids{$correct_id}='specified';
 8953:            }
 8954:         }
 8955:     }
 8956:     if ($env{'form.gradingmechanism'} eq 'attendance') {
 8957: 	$result.=&mt('Score based on attendance only');
 8958:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
 8959:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
 8960:     } else {
 8961: 	my $number=0;
 8962: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
 8963: 	foreach my $id (sort(keys(%correct_ids))) {
 8964: 	    $result.='<br /><tt>'.$id.'</tt> - ';
 8965: 	    if ($correct_ids{$id} eq 'specified') {
 8966: 		$result.=&mt('specified');
 8967: 	    } else {
 8968: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
 8969: 		$result.=&Apache::loncommon::plainname($uname,$udom);
 8970: 	    }
 8971: 	    $number++;
 8972: 	}
 8973:         $result.="</p>\n";
 8974: 	if ($number==0) {
 8975: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
 8976: 	    return $result;
 8977: 	}
 8978:     }
 8979:     if (length($env{'form.upfile'}) < 2) {
 8980:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
 8981: 		     '<span class="LC_error">',
 8982: 		     '</span>',
 8983: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
 8984:         return $result;
 8985:     }
 8986: 
 8987: # Were able to get all the info needed, now analyze the file
 8988: 
 8989:     $result.=&Apache::loncommon::studentbrowser_javascript();
 8990:     $symb = &Apache::lonenc::check_encrypt($symb);
 8991:     $result.=&Apache::loncommon::start_data_table().
 8992:              &Apache::loncommon::start_data_table_header_row().
 8993:              '<th>'.&mt('Evaluate clicker file').'</th>'.
 8994:              &Apache::loncommon::end_data_table_header_row().
 8995:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
 8996: <td>
 8997: <form method="post" action="/adm/grades" name="clickeranalysis">
 8998: <input type="hidden" name="symb" value="$symb" />
 8999: <input type="hidden" name="command" value="assignclickergrades" />
 9000: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
 9001: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
 9002: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
 9003: ENDHEADER
 9004:     if ($env{'form.gradingmechanism'} eq 'given') {
 9005:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
 9006:     } 
 9007:     my %responses;
 9008:     my @questiontitles;
 9009:     my $errormsg='';
 9010:     my $number=0;
 9011:     if ($env{'form.upfiletype'} eq 'iclicker') {
 9012: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
 9013:     }
 9014:     if ($env{'form.upfiletype'} eq 'interwrite') {
 9015:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
 9016:     }
 9017:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
 9018:              '<input type="hidden" name="number" value="'.$number.'" />'.
 9019:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
 9020:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
 9021:              '<br />';
 9022:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
 9023:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
 9024:        return $result;
 9025:     } 
 9026: # Remember Question Titles
 9027: # FIXME: Possibly need delimiter other than ":"
 9028:     for (my $i=0;$i<$number;$i++) {
 9029:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
 9030:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
 9031:     }
 9032:     my $correct_count=0;
 9033:     my $student_count=0;
 9034:     my $unknown_count=0;
 9035: # Match answers with usernames
 9036: # FIXME: Possibly need delimiter other than ":"
 9037:     foreach my $id (keys(%responses)) {
 9038:        if ($correct_ids{$id}) {
 9039:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
 9040:           $correct_count++;
 9041:        } elsif ($clicker_ids{$id}) {
 9042:           if ($clicker_ids{$id}=~/\,/) {
 9043: # More than one user with the same clicker!
 9044:              $result.="</td>".&Apache::loncommon::end_data_table_row().
 9045:                            &Apache::loncommon::start_data_table_row()."<td>".
 9046:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
 9047:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 9048:                            "<select name='multi".$id."'>";
 9049:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
 9050:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
 9051:              }
 9052:              $result.='</select>';
 9053:              $unknown_count++;
 9054:           } else {
 9055: # Good: found one and only one user with the right clicker
 9056:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
 9057:              $student_count++;
 9058:           }
 9059:        } else {
 9060:           $result.="</td>".&Apache::loncommon::end_data_table_row().
 9061:                            &Apache::loncommon::start_data_table_row()."<td>".
 9062:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
 9063:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 9064:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
 9065:                    "\n".&mt("Domain").": ".
 9066:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
 9067:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,0,$id);
 9068:           $unknown_count++;
 9069:        }
 9070:     }
 9071:     $result.='<hr />'.
 9072:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
 9073:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
 9074:        if ($correct_count==0) {
 9075:           $errormsg.="Found no correct answers answers for grading!";
 9076:        } elsif ($correct_count>1) {
 9077:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
 9078:        }
 9079:     }
 9080:     if ($number<1) {
 9081:        $errormsg.="Found no questions.";
 9082:     }
 9083:     if ($errormsg) {
 9084:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
 9085:     } else {
 9086:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
 9087:     }
 9088:     $result.='</form></td>'.
 9089:              &Apache::loncommon::end_data_table_row().
 9090:              &Apache::loncommon::end_data_table();
 9091:     return $result;
 9092: }
 9093: 
 9094: sub iclicker_eval {
 9095:     my ($questiontitles,$responses)=@_;
 9096:     my $number=0;
 9097:     my $errormsg='';
 9098:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 9099:         my %components=&Apache::loncommon::record_sep($line);
 9100:         my @entries=map {$components{$_}} (sort(keys(%components)));
 9101: 	if ($entries[0] eq 'Question') {
 9102: 	    for (my $i=3;$i<$#entries;$i+=6) {
 9103: 		$$questiontitles[$number]=$entries[$i];
 9104: 		$number++;
 9105: 	    }
 9106: 	}
 9107: 	if ($entries[0]=~/^\#/) {
 9108: 	    my $id=$entries[0];
 9109: 	    my @idresponses;
 9110: 	    $id=~s/^[\#0]+//;
 9111: 	    for (my $i=0;$i<$number;$i++) {
 9112: 		my $idx=3+$i*6;
 9113:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
 9114: 		push(@idresponses,$entries[$idx]);
 9115: 	    }
 9116: 	    $$responses{$id}=join(',',@idresponses);
 9117: 	}
 9118:     }
 9119:     return ($errormsg,$number);
 9120: }
 9121: 
 9122: sub interwrite_eval {
 9123:     my ($questiontitles,$responses)=@_;
 9124:     my $number=0;
 9125:     my $errormsg='';
 9126:     my $skipline=1;
 9127:     my $questionnumber=0;
 9128:     my %idresponses=();
 9129:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 9130:         my %components=&Apache::loncommon::record_sep($line);
 9131:         my @entries=map {$components{$_}} (sort(keys(%components)));
 9132:         if ($entries[1] eq 'Time') { $skipline=0; next; }
 9133:         if ($entries[1] eq 'Response') { $skipline=1; }
 9134:         next if $skipline;
 9135:         if ($entries[0]!=$questionnumber) {
 9136:            $questionnumber=$entries[0];
 9137:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
 9138:            $number++;
 9139:         }
 9140:         my $id=$entries[4];
 9141:         $id=~s/^[\#0]+//;
 9142:         $id=~s/^v\d*\://i;
 9143:         $id=~s/[\-\:]//g;
 9144:         $idresponses{$id}[$number]=$entries[6];
 9145:     }
 9146:     foreach my $id (keys(%idresponses)) {
 9147:        $$responses{$id}=join(',',@{$idresponses{$id}});
 9148:        $$responses{$id}=~s/^\s*\,//;
 9149:     }
 9150:     return ($errormsg,$number);
 9151: }
 9152: 
 9153: sub assign_clicker_grades {
 9154:     my ($r,$symb)=@_;
 9155:     if (!$symb) {return '';}
 9156: # See which part we are saving to
 9157:     my $res_error;
 9158:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 9159:     if ($res_error) {
 9160:         return &navmap_errormsg();
 9161:     }
 9162: # FIXME: This should probably look for the first handgradeable part
 9163:     my $part=$$partlist[0];
 9164: # Start screen output
 9165:     my $result=&Apache::loncommon::start_data_table().
 9166:              &Apache::loncommon::start_data_table_header_row().
 9167:              '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
 9168:              &Apache::loncommon::end_data_table_header_row().
 9169:              &Apache::loncommon::start_data_table_row().'<td>';
 9170: # Get correct result
 9171: # FIXME: Possibly need delimiter other than ":"
 9172:     my @correct=();
 9173:     my $gradingmechanism=$env{'form.gradingmechanism'};
 9174:     my $number=$env{'form.number'};
 9175:     if ($gradingmechanism ne 'attendance') {
 9176:        foreach my $key (keys(%env)) {
 9177:           if ($key=~/^form\.correct\:/) {
 9178:              my @input=split(/\,/,$env{$key});
 9179:              for (my $i=0;$i<=$#input;$i++) {
 9180:                  if (($correct[$i]) && ($input[$i]) &&
 9181:                      ($correct[$i] ne $input[$i])) {
 9182:                     $result.='<br /><span class="LC_warning">'.
 9183:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
 9184:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
 9185:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
 9186:                     $correct[$i]=$input[$i];
 9187:                  }
 9188:              }
 9189:           }
 9190:        }
 9191:        for (my $i=0;$i<$number;$i++) {
 9192:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
 9193:              $result.='<br /><span class="LC_error">'.
 9194:                       &mt('No correct result given for question "[_1]"!',
 9195:                           $env{'form.question:'.$i}).'</span>';
 9196:           }
 9197:        }
 9198:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
 9199:     }
 9200: # Start grading
 9201:     my $pcorrect=$env{'form.pcorrect'};
 9202:     my $pincorrect=$env{'form.pincorrect'};
 9203:     my $storecount=0;
 9204:     my %users=();
 9205:     foreach my $key (keys(%env)) {
 9206:        my $user='';
 9207:        if ($key=~/^form\.student\:(.*)$/) {
 9208:           $user=$1;
 9209:        }
 9210:        if ($key=~/^form\.unknown\:(.*)$/) {
 9211:           my $id=$1;
 9212:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
 9213:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
 9214:           } elsif ($env{'form.multi'.$id}) {
 9215:              $user=$env{'form.multi'.$id};
 9216:           }
 9217:        }
 9218:        if ($user) {
 9219:           if ($users{$user}) {
 9220:              $result.='<br /><span class="LC_warning">'.
 9221:                       &mt("More than one entry found for <tt>[_1]</tt>!",$user).
 9222:                       '</span><br />';
 9223:           }
 9224:           $users{$user}=1; 
 9225:           my @answer=split(/\,/,$env{$key});
 9226:           my $sum=0;
 9227:           my $realnumber=$number;
 9228:           for (my $i=0;$i<$number;$i++) {
 9229:              if  ($correct[$i] eq '-') {
 9230:                 $realnumber--;
 9231:              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/))  {
 9232:                 if ($gradingmechanism eq 'attendance') {
 9233:                    $sum+=$pcorrect;
 9234:                 } elsif ($correct[$i] eq '*') {
 9235:                    $sum+=$pcorrect;
 9236:                 } else {
 9237: # We actually grade if correct or not
 9238:                    my $increment=$pincorrect;
 9239: # Special case: numerical answer "0"
 9240:                    if ($correct[$i] eq '0') {
 9241:                       if ($answer[$i]=~/^[0\.]+$/) {
 9242:                          $increment=$pcorrect;
 9243:                       }
 9244: # General numerical answer, both evaluate to something non-zero
 9245:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
 9246:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
 9247:                          $increment=$pcorrect;
 9248:                       }
 9249: # Must be just alphanumeric
 9250:                    } elsif ($answer[$i] eq $correct[$i]) {
 9251:                       $increment=$pcorrect;
 9252:                    }
 9253:                    $sum+=$increment;
 9254:                 }
 9255:              }
 9256:           }
 9257:           my $ave=$sum/(100*$realnumber);
 9258: # Store
 9259:           my ($username,$domain)=split(/\:/,$user);
 9260:           my %grades=();
 9261:           $grades{"resource.$part.solved"}='correct_by_override';
 9262:           $grades{"resource.$part.awarded"}=$ave;
 9263:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 9264:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
 9265:                                                  $env{'request.course.id'},
 9266:                                                  $domain,$username);
 9267:           if ($returncode ne 'ok') {
 9268:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
 9269:           } else {
 9270:              $storecount++;
 9271:           }
 9272:        }
 9273:     }
 9274: # We are done
 9275:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
 9276:              '</td>'.
 9277:              &Apache::loncommon::end_data_table_row().
 9278:              &Apache::loncommon::end_data_table();
 9279:     return $result;
 9280: }
 9281: 
 9282: sub navmap_errormsg {
 9283:     return '<div class="LC_error">'.
 9284:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
 9285:            &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>').
 9286:            '</div>';
 9287: }
 9288: 
 9289: sub startpage {
 9290:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag) = @_;
 9291:     unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
 9292:     $r->print(&Apache::loncommon::start_page('Grading',undef,
 9293:                                           {'bread_crumbs' => $crumbs}));
 9294:     &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
 9295:     unless ($nodisplayflag) {
 9296:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag));
 9297:     }
 9298: }
 9299: 
 9300: sub select_problem {
 9301:     my ($r)=@_;
 9302:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
 9303:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1));
 9304:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
 9305:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
 9306: }
 9307: 
 9308: sub handler {
 9309:     my $request=$_[0];
 9310:     &reset_caches();
 9311:     if ($request->header_only) {
 9312:         &Apache::loncommon::content_type($request,'text/html');
 9313:         $request->send_http_header;
 9314:         return OK;
 9315:     }
 9316:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
 9317: 
 9318:     &init_perm();
 9319:     if (!$env{'request.course.id'}) {
 9320:         # Not in a course.
 9321:         $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
 9322:         return HTTP_NOT_ACCEPTABLE;
 9323:     } elsif (!%perm) {
 9324:         $request->internal_redirect('/adm/quickgrades');
 9325:     }
 9326:     &Apache::loncommon::content_type($request,'text/html');
 9327:     $request->send_http_header;
 9328: 
 9329: 
 9330: # see what command we need to execute
 9331: 
 9332:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
 9333:     my $command=$commands[0];
 9334: 
 9335:     if ($#commands > 0) {
 9336: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
 9337:     }
 9338: 
 9339: # see what the symb is
 9340: 
 9341:     my $symb=$env{'form.symb'};
 9342:     unless ($symb) {
 9343:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
 9344:        $symb=&Apache::lonnet::symbread($url);
 9345:     }
 9346:     &Apache::lonenc::check_decrypt(\$symb);
 9347: 
 9348:     $ssi_error = 0;
 9349:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
 9350: #
 9351: # Not called from a resource, but inside a course
 9352: #    
 9353:         &startpage($request,undef,[],1,1);
 9354:         &select_problem($request);
 9355:     } else {
 9356: 	if ($command eq 'submission' && $perm{'vgr'}) {
 9357:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}]);
 9358: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
 9359: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
 9360:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
 9361:                                        {href=>'',text=>'Select student'}],1,1);
 9362: 	    &pickStudentPage($request,$symb);
 9363: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
 9364:             &startpage($request,$symb,
 9365:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
 9366:                                        {href=>'',text=>'Select student'},
 9367:                                        {href=>'',text=>'Grade student'}],1,1);
 9368: 	    &displayPage($request,$symb);
 9369: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
 9370:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
 9371:                                        {href=>'',text=>'Select student'},
 9372:                                        {href=>'',text=>'Grade student'},
 9373:                                        {href=>'',text=>'Store grades'}],1,1);
 9374: 	    &updateGradeByPage($request,$symb);
 9375: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
 9376:             &startpage($request,$symb,[{href=>'',text=>'...'},
 9377:                                        {href=>'',text=>'Modify grades'}]);
 9378: 	    &processGroup($request,$symb);
 9379: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
 9380:             &startpage($request,$symb);
 9381: 	    $request->print(&grading_menu($request,$symb));
 9382: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
 9383:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
 9384: 	    $request->print(&submit_options($request,$symb));
 9385:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
 9386:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}]);
 9387:             $request->print(&listStudents($request,$symb,'graded'));
 9388:         } elsif ($command eq 'table' && $perm{'vgr'}) {
 9389:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
 9390:             $request->print(&submit_options_table($request,$symb));
 9391:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
 9392:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
 9393:             $request->print(&submit_options_sequence($request,$symb));
 9394: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
 9395:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
 9396: 	    $request->print(&viewgrades($request,$symb));
 9397: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
 9398:             &startpage($request,$symb,[{href=>'',text=>'...'},
 9399:                                        {href=>'',text=>'Store grades'}]);
 9400: 	    $request->print(&processHandGrade($request,$symb));
 9401: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
 9402:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
 9403:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
 9404:                                                                              text=>"Modify grades"},
 9405:                                        {href=>'', text=>"Store grades"}]);
 9406: 	    $request->print(&editgrades($request,$symb));
 9407:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
 9408:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
 9409:             $request->print(&initialverifyreceipt($request,$symb));
 9410: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
 9411:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
 9412:                                        {href=>'',text=>'Verification Result'}]);
 9413: 	    $request->print(&verifyreceipt($request,$symb));
 9414:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
 9415:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
 9416:             $request->print(&process_clicker($request,$symb));
 9417:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
 9418:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
 9419:                                        {href=>'', text=>'Process clicker file'}]);
 9420:             $request->print(&process_clicker_file($request,$symb));
 9421:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
 9422:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
 9423:                                        {href=>'', text=>'Process clicker file'},
 9424:                                        {href=>'', text=>'Store grades'}]);
 9425:             $request->print(&assign_clicker_grades($request,$symb));
 9426: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
 9427:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
 9428: 	    $request->print(&upcsvScores_form($request,$symb));
 9429: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
 9430:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
 9431: 	    $request->print(&csvupload($request,$symb));
 9432: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
 9433:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
 9434: 	    $request->print(&csvuploadmap($request,$symb));
 9435: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
 9436: 	    if ($env{'form.associate'} ne 'Reverse Association') {
 9437:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
 9438: 		$request->print(&csvuploadoptions($request,$symb));
 9439: 	    } else {
 9440: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
 9441: 		    $env{'form.upfile_associate'} = 'reverse';
 9442: 		} else {
 9443: 		    $env{'form.upfile_associate'} = 'forward';
 9444: 		}
 9445:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
 9446: 		$request->print(&csvuploadmap($request,$symb));
 9447: 	    }
 9448: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
 9449:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
 9450: 	    $request->print(&csvuploadassign($request,$symb));
 9451: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
 9452:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9453: 	    $request->print(&scantron_selectphase($request,undef,$symb));
 9454:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
 9455:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9456:  	    $request->print(&scantron_do_warning($request,$symb));
 9457: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
 9458:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9459: 	    $request->print(&scantron_validate_file($request,$symb));
 9460: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
 9461:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9462: 	    $request->print(&scantron_process_students($request,$symb));
 9463:  	} elsif ($command eq 'scantronupload' && 
 9464:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9465: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9466:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9467:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
 9468:  	} elsif ($command eq 'scantronupload_save' &&
 9469:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9470: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9471:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9472:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
 9473:  	} elsif ($command eq 'scantron_download' &&
 9474: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 9475:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9476:  	    $request->print(&scantron_download_scantron_data($request,$symb));
 9477:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
 9478:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9479:             $request->print(&checkscantron_results($request,$symb));
 9480:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
 9481:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}]);
 9482:             $request->print(&submit_options_download($request,$symb));
 9483:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
 9484:             &startpage($request,$symb,
 9485:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
 9486:     {href=>'', text=>'Download submissions'}]);
 9487:             &submit_download_link($request,$symb);
 9488: 	} elsif ($command) {
 9489:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
 9490: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
 9491: 	}
 9492:     }
 9493:     if ($ssi_error) {
 9494: 	&ssi_print_error($request);
 9495:     }
 9496:     &Apache::lonquickgrades::endGradeScreen($request);
 9497:     $request->print(&Apache::loncommon::end_page());
 9498:     &reset_caches();
 9499:     return OK;
 9500: }
 9501: 
 9502: 1;
 9503: 
 9504: __END__;
 9505: 
 9506: 
 9507: =head1 NAME
 9508: 
 9509: Apache::grades
 9510: 
 9511: =head1 SYNOPSIS
 9512: 
 9513: Handles the viewing of grades.
 9514: 
 9515: This is part of the LearningOnline Network with CAPA project
 9516: described at http://www.lon-capa.org.
 9517: 
 9518: =head1 OVERVIEW
 9519: 
 9520: Do an ssi with retries:
 9521: While I'd love to factor out this with the vesrion in lonprintout,
 9522: 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
 9523: I'm not quite ready to invent (e.g. an ssi_with_retry object).
 9524: 
 9525: At least the logic that drives this has been pulled out into loncommon.
 9526: 
 9527: 
 9528: 
 9529: ssi_with_retries - Does the server side include of a resource.
 9530:                      if the ssi call returns an error we'll retry it up to
 9531:                      the number of times requested by the caller.
 9532:                      If we still have a proble, no text is appended to the
 9533:                      output and we set some global variables.
 9534:                      to indicate to the caller an SSI error occurred.  
 9535:                      All of this is supposed to deal with the issues described
 9536:                      in LonCAPA BZ 5631 see:
 9537:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
 9538:                      by informing the user that this happened.
 9539: 
 9540: Parameters:
 9541:   resource   - The resource to include.  This is passed directly, without
 9542:                interpretation to lonnet::ssi.
 9543:   form       - The form hash parameters that guide the interpretation of the resource
 9544:                
 9545:   retries    - Number of retries allowed before giving up completely.
 9546: Returns:
 9547:   On success, returns the rendered resource identified by the resource parameter.
 9548: Side Effects:
 9549:   The following global variables can be set:
 9550:    ssi_error                - If an unrecoverable error occurred this becomes true.
 9551:                               It is up to the caller to initialize this to false
 9552:                               if desired.
 9553:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
 9554:                               of the resource that could not be rendered by the ssi
 9555:                               call.
 9556:    ssi_error_message   - The error string fetched from the ssi response
 9557:                               in the event of an error.
 9558: 
 9559: 
 9560: =head1 HANDLER SUBROUTINE
 9561: 
 9562: ssi_with_retries()
 9563: 
 9564: =head1 SUBROUTINES
 9565: 
 9566: =over
 9567: 
 9568: =item scantron_get_correction() : 
 9569: 
 9570:    Builds the interface screen to interact with the operator to fix a
 9571:    specific error condition in a specific scanline
 9572: 
 9573:  Arguments:
 9574:     $r           - Apache request object
 9575:     $i           - number of the current scanline
 9576:     $scan_record - hash ref as returned from &scantron_parse_scanline()
 9577:     $scan_config - hash ref as returned from &get_scantron_config()
 9578:     $line        - full contents of the current scanline
 9579:     $error       - error condition, valid values are
 9580:                    'incorrectCODE', 'duplicateCODE',
 9581:                    'doublebubble', 'missingbubble',
 9582:                    'duplicateID', 'incorrectID'
 9583:     $arg         - extra information needed
 9584:        For errors:
 9585:          - duplicateID   - paper number that this studentID was seen before on
 9586:          - duplicateCODE - array ref of the paper numbers this CODE was
 9587:                            seen on before
 9588:          - incorrectCODE - current incorrect CODE 
 9589:          - doublebubble  - array ref of the bubble lines that have double
 9590:                            bubble errors
 9591:          - missingbubble - array ref of the bubble lines that have missing
 9592:                            bubble errors
 9593: 
 9594: =item  scantron_get_maxbubble() : 
 9595: 
 9596:    Arguments:
 9597:        $nav_error  - Reference to scalar which is a flag to indicate a
 9598:                       failure to retrieve a navmap object.
 9599:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
 9600:        calling routine should trap the error condition and display the warning
 9601:        found in &navmap_errormsg().
 9602: 
 9603:        $scantron_config - Reference to bubblesheet format configuration hash.
 9604: 
 9605:    Returns the maximum number of bubble lines that are expected to
 9606:    occur. Does this by walking the selected sequence rendering the
 9607:    resource and then checking &Apache::lonxml::get_problem_counter()
 9608:    for what the current value of the problem counter is.
 9609: 
 9610:    Caches the results to $env{'form.scantron_maxbubble'},
 9611:    $env{'form.scantron.bubble_lines.n'}, 
 9612:    $env{'form.scantron.first_bubble_line.n'} and
 9613:    $env{"form.scantron.sub_bubblelines.n"}
 9614:    which are the total number of bubble, lines, the number of bubble
 9615:    lines for response n and number of the first bubble line for response n,
 9616:    and a comma separated list of numbers of bubble lines for sub-questions
 9617:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
 9618: 
 9619: 
 9620: =item  scantron_validate_missingbubbles() : 
 9621: 
 9622:    Validates all scanlines in the selected file to not have any
 9623:     answers that don't have bubbles that have not been verified
 9624:     to be bubble free.
 9625: 
 9626: =item  scantron_process_students() : 
 9627: 
 9628:    Routine that does the actual grading of the bubble sheet information.
 9629: 
 9630:    The parsed scanline hash is added to %env 
 9631: 
 9632:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
 9633:    foreach resource , with the form data of
 9634: 
 9635: 	'submitted'     =>'scantron' 
 9636: 	'grade_target'  =>'grade',
 9637: 	'grade_username'=> username of student
 9638: 	'grade_domain'  => domain of student
 9639: 	'grade_courseid'=> of course
 9640: 	'grade_symb'    => symb of resource to grade
 9641: 
 9642:     This triggers a grading pass. The problem grading code takes care
 9643:     of converting the bubbled letter information (now in %env) into a
 9644:     valid submission.
 9645: 
 9646: =item  scantron_upload_scantron_data() :
 9647: 
 9648:     Creates the screen for adding a new bubble sheet data file to a course.
 9649: 
 9650: =item  scantron_upload_scantron_data_save() : 
 9651: 
 9652:    Adds a provided bubble information data file to the course if user
 9653:    has the correct privileges to do so. 
 9654: 
 9655: =item  valid_file() :
 9656: 
 9657:    Validates that the requested bubble data file exists in the course.
 9658: 
 9659: =item  scantron_download_scantron_data() : 
 9660: 
 9661:    Shows a list of the three internal files (original, corrected,
 9662:    skipped) for a specific bubble sheet data file that exists in the
 9663:    course.
 9664: 
 9665: =item  scantron_validate_ID() : 
 9666: 
 9667:    Validates all scanlines in the selected file to not have any
 9668:    invalid or underspecified student/employee IDs
 9669: 
 9670: =item navmap_errormsg() :
 9671: 
 9672:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
 9673:    Should be called whenever the request to instantiate a navmap object fails.  
 9674: 
 9675: =back
 9676: 
 9677: =cut

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