File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.650: download - view: text, annotated - select for diffs
Sat Sep 17 19:01:20 2011 UTC (12 years, 7 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- 'Grading Menu' button was eliminated in rev 1.614.

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.650 2011/09/17 19:01:20 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 $alertmsg = &mt('Please select a word or group of words from document and then click this link.');
 1412:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1413: 
 1414: //===================== Show list of keywords ====================
 1415:   function keywords(formname) {
 1416:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
 1417:     if (nret==null) return;
 1418:     formname.keywords.value = nret;
 1419: 
 1420:     if (formname.keywords.value != "") {
 1421: 	formname.refresh.value = "on";
 1422: 	formname.submit();
 1423:     }
 1424:     return;
 1425:   }
 1426: 
 1427: //===================== Script to view submitted by ==================
 1428:   function viewSubmitter(submitter) {
 1429:     document.SCORE.refresh.value = "on";
 1430:     document.SCORE.NCT.value = "1";
 1431:     document.SCORE.unamedom0.value = submitter;
 1432:     document.SCORE.submit();
 1433:     return;
 1434:   }
 1435: 
 1436: //===================== Script to add keyword(s) ==================
 1437:   function getSel() {
 1438:     if (document.getSelection) txt = document.getSelection();
 1439:     else if (document.selection) txt = document.selection.createRange().text;
 1440:     else return;
 1441:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1442:     if (cleantxt=="") {
 1443: 	alert("$alertmsg");
 1444: 	return;
 1445:     }
 1446:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
 1447:     if (nret==null) return;
 1448:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1449:     if (document.SCORE.keywords.value != "") {
 1450: 	document.SCORE.refresh.value = "on";
 1451: 	document.SCORE.submit();
 1452:     }
 1453:     return;
 1454:   }
 1455: 
 1456: //====================== Script for composing message ==============
 1457:    // preload images
 1458:    img1 = new Image();
 1459:    img1.src = "$iconpath/mailbkgrd.gif";
 1460:    img2 = new Image();
 1461:    img2.src = "$iconpath/mailto.gif";
 1462: 
 1463:   function msgCenter(msgform,usrctr,fullname) {
 1464:     var Nmsg  = msgform.savemsgN.value;
 1465:     savedMsgHeader(Nmsg,usrctr,fullname);
 1466:     var subject = msgform.msgsub.value;
 1467:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1468:     re = /msgsub/;
 1469:     var shwsel = "";
 1470:     if (re.test(msgchk)) { shwsel = "checked" }
 1471:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1472:     displaySubject(checkEntities(subject),shwsel);
 1473:     for (var i=1; i<=Nmsg; i++) {
 1474: 	var testmsg = "savemsg"+i+",";
 1475: 	re = new RegExp(testmsg,"g");
 1476: 	shwsel = "";
 1477: 	if (re.test(msgchk)) { shwsel = "checked" }
 1478: 	var message = document.SCORE["savemsg"+i].value;
 1479: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1480: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1481: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1482:     }
 1483:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1484:     shwsel = "";
 1485:     re = /newmsg/;
 1486:     if (re.test(msgchk)) { shwsel = "checked" }
 1487:     newMsg(newmsg,shwsel);
 1488:     msgTail(); 
 1489:     return;
 1490:   }
 1491: 
 1492:   function checkEntities(strx) {
 1493:     if (strx.length == 0) return strx;
 1494:     var orgStr = ["&", "<", ">", '"']; 
 1495:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1496:     var counter = 0;
 1497:     while (counter < 4) {
 1498: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1499: 	counter++;
 1500:     }
 1501:     return strx;
 1502:   }
 1503: 
 1504:   function strReplace(strx, orgStr, newStr) {
 1505:     return strx.split(orgStr).join(newStr);
 1506:   }
 1507: 
 1508:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1509:     var height = 70*Nmsg+250;
 1510:     var scrollbar = "no";
 1511:     if (height > 600) {
 1512: 	height = 600;
 1513: 	scrollbar = "yes";
 1514:     }
 1515:     var xpos = (screen.width-600)/2;
 1516:     xpos = (xpos < 0) ? '0' : xpos;
 1517:     var ypos = (screen.height-height)/2-30;
 1518:     ypos = (ypos < 0) ? '0' : ypos;
 1519: 
 1520:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
 1521:     pWin.focus();
 1522:     pDoc = pWin.document;
 1523:     pDoc.$docopen;
 1524:     pDoc.write('$start_page_msg_central');
 1525: 
 1526:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1527:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1528:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
 1529: 
 1530:     pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
 1531:     pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
 1532:     pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
 1533: }
 1534:     function displaySubject(msg,shwsel) {
 1535:     pDoc = pWin.document;
 1536:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1537:     pDoc.write("<td>Subject<\\/td>");
 1538:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1539:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
 1540: }
 1541: 
 1542:   function displaySavedMsg(ctr,msg,shwsel) {
 1543:     pDoc = pWin.document;
 1544:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1545:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
 1546:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1547:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
 1548: }
 1549: 
 1550:   function newMsg(newmsg,shwsel) {
 1551:     pDoc = pWin.document;
 1552:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1553:     pDoc.write("<td align=\\"center\\">New<\\/td>");
 1554:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1555:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
 1556: }
 1557: 
 1558:   function msgTail() {
 1559:     pDoc = pWin.document;
 1560:     pDoc.write("<\\/table>");
 1561:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1562:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1563:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onclick=\\"self.close()\\"><br /><br />");
 1564:     pDoc.write("<\\/form>");
 1565:     pDoc.write('$end_page_msg_central');
 1566:     pDoc.close();
 1567: }
 1568: 
 1569: //====================== Script for keyword highlight options ==============
 1570:   function kwhighlight() {
 1571:     var kwclr    = document.SCORE.kwclr.value;
 1572:     var kwsize   = document.SCORE.kwsize.value;
 1573:     var kwstyle  = document.SCORE.kwstyle.value;
 1574:     var redsel = "";
 1575:     var grnsel = "";
 1576:     var blusel = "";
 1577:     if (kwclr=="red")   {var redsel="checked"};
 1578:     if (kwclr=="green") {var grnsel="checked"};
 1579:     if (kwclr=="blue")  {var blusel="checked"};
 1580:     var sznsel = "";
 1581:     var sz1sel = "";
 1582:     var sz2sel = "";
 1583:     if (kwsize=="0")  {var sznsel="checked"};
 1584:     if (kwsize=="+1") {var sz1sel="checked"};
 1585:     if (kwsize=="+2") {var sz2sel="checked"};
 1586:     var synsel = "";
 1587:     var syisel = "";
 1588:     var sybsel = "";
 1589:     if (kwstyle=="")    {var synsel="checked"};
 1590:     if (kwstyle=="<i>") {var syisel="checked"};
 1591:     if (kwstyle=="<b>") {var sybsel="checked"};
 1592:     highlightCentral();
 1593:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
 1594:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
 1595:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
 1596:     highlightend();
 1597:     return;
 1598:   }
 1599: 
 1600:   function highlightCentral() {
 1601: //    if (window.hwdWin) window.hwdWin.close();
 1602:     var xpos = (screen.width-400)/2;
 1603:     xpos = (xpos < 0) ? '0' : xpos;
 1604:     var ypos = (screen.height-330)/2-30;
 1605:     ypos = (ypos < 0) ? '0' : ypos;
 1606: 
 1607:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1608:     hwdWin.focus();
 1609:     var hDoc = hwdWin.document;
 1610:     hDoc.$docopen;
 1611:     hDoc.write('$start_page_highlight_central');
 1612:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1613:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options<\\/span><\\/h3><br /><br />");
 1614: 
 1615:     hDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
 1616:     hDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
 1617:     hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
 1618:   }
 1619: 
 1620:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1621:     var hDoc = hwdWin.document;
 1622:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1623:     hDoc.write("<td align=\\"left\\">");
 1624:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
 1625:     hDoc.write("<td align=\\"left\\">");
 1626:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
 1627:     hDoc.write("<td align=\\"left\\">");
 1628:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
 1629:     hDoc.write("<\\/tr>");
 1630:   }
 1631: 
 1632:   function highlightend() { 
 1633:     var hDoc = hwdWin.document;
 1634:     hDoc.write("<\\/table>");
 1635:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1636:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onclick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
 1637:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onclick=\\"self.close()\\"><br /><br />");
 1638:     hDoc.write("<\\/form>");
 1639:     hDoc.write('$end_page_highlight_central');
 1640:     hDoc.close();
 1641:   }
 1642: 
 1643: SUBJAVASCRIPT
 1644: }
 1645: 
 1646: sub get_increment {
 1647:     my $increment = $env{'form.increment'};
 1648:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1649:         $increment != .1) {
 1650:         $increment = 1;
 1651:     }
 1652:     return $increment;
 1653: }
 1654: 
 1655: sub gradeBox_start {
 1656:     return (
 1657:         &Apache::loncommon::start_data_table()
 1658:        .&Apache::loncommon::start_data_table_header_row()
 1659:        .'<th>'.&mt('Part').'</th>'
 1660:        .'<th>'.&mt('Points').'</th>'
 1661:        .'<th>&nbsp;</th>'
 1662:        .'<th>'.&mt('Assign Grade').'</th>'
 1663:        .'<th>'.&mt('Weight').'</th>'
 1664:        .'<th>'.&mt('Grade Status').'</th>'
 1665:        .&Apache::loncommon::end_data_table_header_row()
 1666:     );
 1667: }
 1668: 
 1669: sub gradeBox_end {
 1670:     return (
 1671:         &Apache::loncommon::end_data_table()
 1672:     );
 1673: }
 1674: #--- displays the grading box, used in essay type problem and grading by page/sequence
 1675: sub gradeBox {
 1676:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 1677:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1678: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 1679:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 1680:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
 1681:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
 1682:     $wgt       = ($wgt > 0 ? $wgt : '1');
 1683:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 1684: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 1685:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 1686:     my $display_part= &get_display_part($partid,$symb);
 1687:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 1688: 				       [$partid]);
 1689:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 1690:     if ($last_resets{$partid}) {
 1691:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 1692:     }
 1693:     $result.=&Apache::loncommon::start_data_table_row();
 1694:     my $ctr = 0;
 1695:     my $thisweight = 0;
 1696:     my $increment = &get_increment();
 1697: 
 1698:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 1699:     while ($thisweight<=$wgt) {
 1700: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 1701:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 1702: 	    $thisweight.')" value="'.$thisweight.'" '.
 1703: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 1704: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 1705:         $thisweight += $increment;
 1706: 	$ctr++;
 1707:     }
 1708:     $radio.='</tr></table>';
 1709: 
 1710:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 1711: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 1712: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 1713: 	$wgt.')" /></td>'."\n";
 1714:     $line.='<td>/'.$wgt.' '.$wgtmsg.
 1715: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 1716: 	' </td>'."\n";
 1717:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
 1718: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 1719:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 1720: 	$line.='<option></option>'.
 1721: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
 1722:     } else {
 1723: 	$line.='<option selected="selected"></option>'.
 1724: 	    '<option value="excused" >'.&mt('excused').'</option>';
 1725:     }
 1726:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
 1727: 
 1728: 
 1729:     $result .= 
 1730: 	    '<td>'.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
 1731:     $result.=&Apache::loncommon::end_data_table_row();
 1732:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 1733: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 1734: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 1735: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 1736:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 1737:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 1738:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 1739:         $aggtries.'" />'."\n";
 1740:     my $res_error;
 1741:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
 1742:     if ($res_error) {
 1743:         return &navmap_errormsg();
 1744:     }
 1745:     return $result;
 1746: }
 1747: 
 1748: sub handback_box {
 1749:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
 1750:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error_pointer);
 1751:     my (@respids);
 1752:      my @part_response_id = &flatten_responseType($responseType);
 1753:     foreach my $part_response_id (@part_response_id) {
 1754:     	my ($part,$resp) = @{ $part_response_id };
 1755:         if ($part eq $partid) {
 1756:             push(@respids,$resp);
 1757:         }
 1758:     }
 1759:     my $result;
 1760:     foreach my $respid (@respids) {
 1761: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 1762: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 1763: 	next if (!@$files);
 1764: 	my $file_counter = 1;
 1765: 	foreach my $file (@$files) {
 1766: 	    if ($file =~ /\/portfolio\//) {
 1767:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 1768:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
 1769:     	        $file_disp = "$name.$ext";
 1770:     	        $file = $file_path.$file_disp;
 1771:     	        $result.=&mt('Return commented version of [_1] to student.',
 1772:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 1773:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 1774:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
 1775:     	        $result.='('.&mt('File will be uploaded when you click on Save &amp; Next below.').')<br />';
 1776:     	        $file_counter++;
 1777: 	    }
 1778: 	}
 1779:     }
 1780:     return $result;    
 1781: }
 1782: 
 1783: sub show_problem {
 1784:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 1785:     my $rendered;
 1786:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 1787:     &Apache::lonxml::remember_problem_counter();
 1788:     if ($mode eq 'both' or $mode eq 'text') {
 1789: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 1790: 						       $env{'request.course.id'},
 1791: 						       undef,\%form);
 1792:     }
 1793:     if ($removeform) {
 1794: 	$rendered=~s|<form(.*?)>||g;
 1795: 	$rendered=~s|</form>||g;
 1796: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 1797:     }
 1798:     my $companswer;
 1799:     if ($mode eq 'both' or $mode eq 'answer') {
 1800: 	&Apache::lonxml::restore_problem_counter();
 1801: 	$companswer=
 1802: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 1803: 						    $env{'request.course.id'},
 1804: 						    %form);
 1805:     }
 1806:     if ($removeform) {
 1807: 	$companswer=~s|<form(.*?)>||g;
 1808: 	$companswer=~s|</form>||g;
 1809: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 1810:     }
 1811:     $rendered=
 1812:         '<div class="LC_Box">'
 1813:        .'<h3 class="LC_hcell">'.&mt('View of the problem').'</h3>'
 1814:        .$rendered
 1815:        .'</div>';
 1816:     $companswer=
 1817:         '<div class="LC_Box">'
 1818:        .'<h3 class="LC_hcell">'.&mt('Correct answer').'</h3>'
 1819:        .$companswer
 1820:        .'</div>';
 1821:     my $result;
 1822:     if ($mode eq 'both') {
 1823:         $result=$rendered.$companswer;
 1824:     } elsif ($mode eq 'text') {
 1825:         $result=$rendered;
 1826:     } elsif ($mode eq 'answer') {
 1827:         $result=$companswer;
 1828:     }
 1829:     return $result;
 1830: }
 1831: 
 1832: sub files_exist {
 1833:     my ($r, $symb) = @_;
 1834:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1835: 
 1836:     foreach my $student (@students) {
 1837:         my ($uname,$udom,$fullname) = split(/:/,$student);
 1838:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 1839: 					      $udom,$uname);
 1840:         my ($string,$timestamp)= &get_last_submission(\%record);
 1841:         foreach my $submission (@$string) {
 1842:             my ($partid,$respid) =
 1843: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 1844:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 1845: 					   \%record);
 1846:             return 1 if (@$files);
 1847:         }
 1848:     }
 1849:     return 0;
 1850: }
 1851: 
 1852: sub download_all_link {
 1853:     my ($r,$symb) = @_;
 1854:     unless (&files_exist($r, $symb)) {
 1855:        $r->print(&mt('There are currently no submitted documents.'));
 1856:        return;
 1857:     }
 1858: 
 1859:     my $all_students = 
 1860: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 1861: 
 1862:     my $parts =
 1863: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 1864: 
 1865:     my $identifier = &Apache::loncommon::get_cgi_id();
 1866:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 1867:                              'cgi.'.$identifier.'.symb' => $symb,
 1868:                              'cgi.'.$identifier.'.parts' => $parts,});
 1869:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 1870: 	      &mt('Download All Submitted Documents').'</a>');
 1871:     return;
 1872: }
 1873: 
 1874: sub submit_download_link {
 1875:     my ($request,$symb) = @_;
 1876:     if (!$symb) { return ''; }
 1877: #FIXME: Figure out which type of problem this is and provide appropriate download
 1878:     &download_all_link($request,$symb);
 1879: }
 1880: 
 1881: sub build_section_inputs {
 1882:     my $section_inputs;
 1883:     if ($env{'form.section'} eq '') {
 1884:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 1885:     } else {
 1886:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 1887:         foreach my $section (@sections) {
 1888:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 1889:         }
 1890:     }
 1891:     return $section_inputs;
 1892: }
 1893: 
 1894: # --------------------------- show submissions of a student, option to grade 
 1895: sub submission {
 1896:     my ($request,$counter,$total,$symb) = @_;
 1897:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 1898:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 1899:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 1900:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 1901: 
 1902:     my $probtitle=&Apache::lonnet::gettitle($symb); 
 1903:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 1904: 
 1905:     if (!&canview($usec)) {
 1906: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
 1907: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
 1908: 			$env{'request.course.id'}.')</span>');
 1909: 	return;
 1910:     }
 1911: 
 1912:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 1913:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 1914:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 1915:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 1916:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1917: 	'" src="'.$request->dir_config('lonIconsURL').
 1918: 	'/check.gif" height="16" border="0" />';
 1919: 
 1920:     my %old_essays;
 1921:     # header info
 1922:     if ($counter == 0) {
 1923: 	&sub_page_js($request);
 1924: 	&sub_page_kw_js($request);
 1925: 
 1926: 	# option to display problem, only once else it cause problems 
 1927:         # with the form later since the problem has a form.
 1928: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 1929: 	    my $mode;
 1930: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 1931: 		$mode='both';
 1932: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 1933: 		$mode='text';
 1934: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 1935: 		$mode='answer';
 1936: 	    }
 1937: 	    &Apache::lonxml::clear_problem_counter();
 1938: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 1939: 	}
 1940: 
 1941: 	# kwclr is the only variable that is guaranteed to be non blank 
 1942:         # if this subroutine has been called once.
 1943: 	my %keyhash = ();
 1944: #	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
 1945:         if (1) {
 1946: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 1947: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 1948: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 1949: 
 1950: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 1951: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 1952: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 1953: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 1954: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 1955: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
 1956: 		$keyhash{$symb.'_subject'} : $probtitle;
 1957: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 1958: 	}
 1959: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 1960: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 1961: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 1962: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 1963: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 1964: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 1965: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 1966: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 1967: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 1968: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 1969: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 1970: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 1971: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 1972: 			&build_section_inputs().
 1973: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 1974: 			'<input type="hidden" name="NCT"'.
 1975: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 1976: #	if ($env{'form.handgrade'} eq 'yes') {
 1977:         if (1) {
 1978: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 1979: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 1980: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 1981: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
 1982: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 1983: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 1984: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 1985: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
 1986: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
 1987: 	    }
 1988: 	}
 1989: 	
 1990: 	my ($cts,$prnmsg) = (1,'');
 1991: 	while ($cts <= $env{'form.savemsgN'}) {
 1992: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 1993: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 1994: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 1995: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 1996: 		'" />'."\n".
 1997: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 1998: 	    $cts++;
 1999: 	}
 2000: 	$request->print($prnmsg);
 2001: 
 2002: #	if ($env{'form.handgrade'} eq 'yes') {
 2003:         if (1) {
 2004: #
 2005: # Print out the keyword options line
 2006: #
 2007: 	    $request->print(<<KEYWORDS);
 2008: &nbsp;<b>Keyword Options:</b>&nbsp;
 2009: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
 2010: <a href="#" onmousedown="javascript:getSel(); return false"
 2011:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
 2012: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
 2013: KEYWORDS
 2014: #
 2015: # Load the other essays for similarity check
 2016: #
 2017:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 2018: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 2019: 	    $apath=&escape($apath);
 2020: 	    $apath=~s/\W/\_/gs;
 2021: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
 2022:         }
 2023:     }
 2024: 
 2025: # This is where output for one specific student would start
 2026:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
 2027:     $request->print(
 2028:         "\n\n"
 2029:        .'<div class="LC_grade_show_user'.$add_class.'">'
 2030:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
 2031:        ."\n"
 2032:     );
 2033: 
 2034:     # Show additional functions if allowed
 2035:     if ($perm{'vgr'}) {
 2036:         $request->print(
 2037:             &Apache::loncommon::track_student_link(
 2038:                 &mt('View recent activity'),
 2039:                 $uname,$udom,'check')
 2040:            .' '
 2041:         );
 2042:     }
 2043:     if ($perm{'opa'}) {
 2044:         $request->print(
 2045:             &Apache::loncommon::pprmlink(
 2046:                 &mt('Set/Change parameters'),
 2047:                 $uname,$udom,$symb,'check'));
 2048:     }
 2049: 
 2050:     # Show Problem
 2051:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2052: 	my $mode;
 2053: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2054: 	    $mode='both';
 2055: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2056: 	    $mode='text';
 2057: 	} elsif ($env{'form.vAns'} eq 'all') {
 2058: 	    $mode='answer';
 2059: 	}
 2060: 	&Apache::lonxml::clear_problem_counter();
 2061: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2062:     }
 2063: 
 2064:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2065:     my $res_error;
 2066:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2067:     if ($res_error) {
 2068:         $request->print(&navmap_errormsg());
 2069:         return;
 2070:     }
 2071: 
 2072:     # Display student info
 2073:     $request->print(($counter == 0 ? '' : '<br />'));
 2074: 
 2075:     my $result='<div class="LC_Box">'
 2076:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
 2077:     $result.='<input type="hidden" name="name'.$counter.
 2078:              '" value="'.$env{'form.fullname'}.'" />'."\n";
 2079: #    if ($env{'form.handgrade'} eq 'no') {
 2080:     if (1) {
 2081:         $result.='<p class="LC_info">'
 2082:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
 2083:                 ."</p>\n";
 2084:     }
 2085: 
 2086:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
 2087:     my $fullname;
 2088:     my $col_fullnames = [];
 2089: #    if ($env{'form.handgrade'} eq 'yes') {
 2090:     if (1) {
 2091: 	(my $sub_result,$fullname,$col_fullnames)=
 2092: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2093: 				 $counter);
 2094: 	$result.=$sub_result;
 2095:     }
 2096:     $request->print($result."\n");
 2097: 
 2098:     # print student answer/submission
 2099:     # Options are (1) Handgraded submission only
 2100:     #             (2) Last submission, includes submission that is not handgraded 
 2101:     #                  (for multi-response type part)
 2102:     #             (3) Last submission plus the parts info
 2103:     #             (4) The whole record for this student
 2104:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
 2105: 	my ($string,$timestamp)= &get_last_submission(\%record);
 2106: 	
 2107: 	my $lastsubonly;
 2108: 
 2109:         if ($$timestamp eq '') {
 2110:             $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
 2111:         } else {
 2112:             $lastsubonly =
 2113:                 '<div class="LC_grade_submissions_body">'
 2114:                .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
 2115: 
 2116: 	    my %seenparts;
 2117: 	    my @part_response_id = &flatten_responseType($responseType);
 2118: 	    foreach my $part (@part_response_id) {
 2119: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
 2120: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
 2121: 
 2122: 		my ($partid,$respid) = @{ $part };
 2123: 		my $display_part=&get_display_part($partid,$symb);
 2124: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2125: 		    if (exists($seenparts{$partid})) { next; }
 2126: 		    $seenparts{$partid}=1;
 2127: 		    my $submitby='<b>Part:</b> '.$display_part.
 2128: 			' <b>Collaborative submission by:</b> '.
 2129: 			'<a href="javascript:viewSubmitter(\''.
 2130: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
 2131: 			'\');" target="_self">'.
 2132: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
 2133: 		    $request->print($submitby);
 2134: 		    next;
 2135: 		}
 2136: 		my $responsetype = $responseType->{$partid}->{$respid};
 2137: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
 2138:                     $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
 2139:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2140:                         ' <span class="LC_internal_info">'.
 2141:                         '('.&mt('Response ID: [_1]',$respid).')'.
 2142:                         '</span>&nbsp; &nbsp;'.
 2143: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
 2144: 		    next;
 2145: 		}
 2146: 		foreach my $submission (@$string) {
 2147: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2148: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2149: 		    my ($ressub,$hide,$subval) = split(/:/,$submission,3);
 2150: 		    # Similarity check
 2151: 		    my $similar='';
 2152:                     my ($type,$trial,$rndseed);
 2153:                     if ($hide eq 'rand') {
 2154:                         $type = 'randomizetry';
 2155:                         $trial = $record{"resource.$partid.tries"};
 2156:                         $rndseed = $record{"resource.$partid.rndseed"};
 2157:                     }
 2158: 		    if($env{'form.checkPlag'}){
 2159: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2160: 			    &most_similar($uname,$udom,$subval,\%old_essays);
 2161: 			if ($osim) {
 2162: 			    $osim=int($osim*100.0);
 2163: 			    my %old_course_desc = 
 2164: 				&Apache::lonnet::coursedescription($ocrsid,
 2165: 								   {'one_time' => 1});
 2166: 
 2167:                             if ($hide eq 'anon') {
 2168:                                 $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
 2169:                                          &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
 2170:                             } else {
 2171: 			        $similar="<hr /><h3><span class=\"LC_warning\">".
 2172: 				    &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
 2173: 				        $osim,
 2174: 				        &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
 2175: 				        $old_course_desc{'description'},
 2176: 				        $old_course_desc{'num'},
 2177: 				        $old_course_desc{'domain'}).
 2178: 				    '</span></h3><blockquote><i>'.
 2179: 				    &keywords_highlight($oessay).
 2180: 				    '</i></blockquote><hr />';
 2181:                             }
 2182: 			}
 2183: 		    }
 2184: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom,
 2185:                                          undef,$type,$trial,$rndseed);
 2186: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
 2187: 			($env{'form.lastSub'} eq 'hdgrade' && 
 2188: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
 2189: 			my $display_part=&get_display_part($partid,$symb);
 2190:                         $lastsubonly.='<div class="LC_grade_submission_part">'.
 2191:                             '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2192:                             ' <span class="LC_internal_info">'.
 2193:                             '('.&mt('Response ID: [_1]',$respid).')'.
 2194:                             '</span>&nbsp; &nbsp;';
 2195: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2196: 			if (@$files) {
 2197:                             if ($hide eq 'anon') {
 2198:                                 $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
 2199:                             } else {
 2200:                                 $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
 2201:                                 foreach my $file (@$files) {
 2202:                                     &Apache::lonnet::allowuploaded('/adm/grades',$file);
 2203:                                     $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" /> '.$file.'</a>';
 2204:                                 }
 2205:                             }
 2206: 			    $lastsubonly.='<br />';
 2207: 			}
 2208:                         if ($hide eq 'anon') {
 2209:                             $lastsubonly.='<b>'.&mt('Anonymous Survey').'</b>'; 
 2210:                         } else {
 2211: 			    $lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
 2212: 			        &cleanRecord($subval,$responsetype,$symb,$partid,
 2213: 					     $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
 2214:                         }
 2215: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2216: 			$lastsubonly.='</div>';
 2217: 		    }
 2218: 		}
 2219: 	    }
 2220: 	    $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
 2221: 	}
 2222: 	$request->print($lastsubonly);
 2223:    } elsif ($env{'form.lastSub'} eq 'datesub') {
 2224:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2225: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2226:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2227: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2228: 								 $env{'request.course.id'},
 2229: 								 $last,'.submission',
 2230: 								 'Apache::grades::keywords_highlight'));
 2231:     }
 2232:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2233: 	.$udom.'" />'."\n");
 2234:     # return if view submission with no grading option
 2235:     if (!&canmodify($usec)) {
 2236: 	$request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
 2237: 	return;
 2238:     } else {
 2239: 	$request->print('</div>'."\n");
 2240:     }
 2241: 
 2242:     # essay grading message center
 2243: #    if ($env{'form.handgrade'} eq 'yes') {
 2244:     if (1) {
 2245: 	my $result='<div class="LC_grade_message_center">';
 2246:     
 2247: 	$result.='<div class="LC_grade_message_center_header">'.
 2248: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
 2249: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2250: 	my $msgfor = $givenn.' '.$lastname;
 2251: 	if (scalar(@$col_fullnames) > 0) {
 2252: 	    my $lastone = pop(@$col_fullnames);
 2253: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2254: 	}
 2255: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2256: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2257: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
 2258: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2259: 	    ',\''.$msgfor.'\');" target="_self">'.
 2260: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
 2261: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2262: 	    '<img src="'.$request->dir_config('lonIconsURL').
 2263: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
 2264: 	    '<br />&nbsp;('.
 2265: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
 2266: 	$result.='</div></div>';
 2267: 	$request->print($result);
 2268:     }
 2269: 
 2270:     my %seen = ();
 2271:     my @partlist;
 2272:     my @gradePartRespid;
 2273:     my @part_response_id = &flatten_responseType($responseType);
 2274:     $request->print(
 2275:         '<div class="LC_Box">'
 2276:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
 2277:     );
 2278:     $request->print(&gradeBox_start());
 2279:     foreach my $part_response_id (@part_response_id) {
 2280:     	my ($partid,$respid) = @{ $part_response_id };
 2281: 	my $part_resp = join('_',@{ $part_response_id });
 2282: 	next if ($seen{$partid} > 0);
 2283: 	$seen{$partid}++;
 2284: 	next if ($$handgrade{$part_resp} ne 'yes' 
 2285: 		 && $env{'form.lastSub'} eq 'hdgrade');
 2286: 	push(@partlist,$partid);
 2287: 	push(@gradePartRespid,$partid.'.'.$respid);
 2288: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2289:     }
 2290:     $request->print(&gradeBox_end()); # </div>
 2291:     $request->print('</div>');
 2292: 
 2293:     $request->print('<div class="LC_grade_info_links">');
 2294:     $request->print('</div>');
 2295: 
 2296:     $result='<input type="hidden" name="partlist'.$counter.
 2297: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2298:     $result.='<input type="hidden" name="gradePartRespid'.
 2299: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2300:     my $ctr = 0;
 2301:     while ($ctr < scalar(@partlist)) {
 2302: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2303: 	    $partlist[$ctr].'" />'."\n";
 2304: 	$ctr++;
 2305:     }
 2306:     $request->print($result.''."\n");
 2307: 
 2308: # Done with printing info for one student
 2309: 
 2310:     $request->print('</div>');#LC_grade_show_user
 2311: 
 2312: 
 2313:     # print end of form
 2314:     if ($counter == $total) {
 2315:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
 2316: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2317: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
 2318: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2319: 	my $ntstu ='<select name="NTSTU">'.
 2320: 	    '<option>1</option><option>2</option>'.
 2321: 	    '<option>3</option><option>5</option>'.
 2322: 	    '<option>7</option><option>10</option></select>'."\n";
 2323: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2324: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2325:         $endform.=&mt('[_1]student(s)',$ntstu);
 2326: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2327: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2328: 	    '<input type="button" value="'.&mt('Next').'" '.
 2329: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2330:         $endform.='<span class="LC_warning">'.
 2331:                   &mt('(Next and Previous (student) do not save the scores.)').
 2332:                   '</span>'."\n" ;
 2333:         $endform.="<input type='hidden' value='".&get_increment().
 2334:             "' name='increment' />";
 2335: 	$endform.='</td></tr></table></form>';
 2336: 	$request->print($endform);
 2337:     }
 2338:     return '';
 2339: }
 2340: 
 2341: sub check_collaborators {
 2342:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2343:     my ($result,@col_fullnames);
 2344:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2345:     foreach my $part (keys(%$handgrade)) {
 2346: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2347: 					'.maxcollaborators',
 2348: 					$symb,$udom,$uname);
 2349: 	next if ($ncol <= 0);
 2350: 	$part =~ s/\_/\./g;
 2351: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2352: 	my (@good_collaborators, @bad_collaborators);
 2353: 	foreach my $possible_collaborator
 2354: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2355: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2356: 	    next if ($possible_collaborator eq '');
 2357: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
 2358: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2359: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2360: 	    # Doing this grep allows 'fuzzy' specification
 2361: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2362: 			       keys(%$classlist));
 2363: 	    if (! scalar(@matches)) {
 2364: 		push(@bad_collaborators, $possible_collaborator);
 2365: 	    } else {
 2366: 		push(@good_collaborators, @matches);
 2367: 	    }
 2368: 	}
 2369: 	if (scalar(@good_collaborators) != 0) {
 2370: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
 2371: 	    foreach my $name (@good_collaborators) {
 2372: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2373: 		push(@col_fullnames, $givenn.' '.$lastname);
 2374: 		$result.='<li>'.$fullname->{$name}.'</li>';
 2375: 	    }
 2376: 	    $result.='</ol><br />'."\n";
 2377: 	    my ($part)=split(/\./,$part);
 2378: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2379: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2380: 		"\n";
 2381: 	}
 2382: 	if (scalar(@bad_collaborators) > 0) {
 2383: 	    $result.='<div class="LC_warning">';
 2384: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2385: 	    $result .= '</div>';
 2386: 	}         
 2387: 	if (scalar(@bad_collaborators > $ncol)) {
 2388: 	    $result .= '<div class="LC_warning">';
 2389: 	    $result .= &mt('This student has submitted too many '.
 2390: 		'collaborators.  Maximum is [_1].',$ncol);
 2391: 	    $result .= '</div>';
 2392: 	}
 2393:     }
 2394:     return ($result,$fullname,\@col_fullnames);
 2395: }
 2396: 
 2397: #--- Retrieve the last submission for all the parts
 2398: sub get_last_submission {
 2399:     my ($returnhash)=@_;
 2400:     my (@string,$timestamp,%lasthidden);
 2401:     if ($$returnhash{'version'}) {
 2402: 	my %lasthash=();
 2403: 	my ($version);
 2404: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2405: 	    foreach my $key (sort(split(/\:/,
 2406: 					$$returnhash{$version.':keys'}))) {
 2407: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2408: 		$timestamp = 
 2409: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2410: 	    }
 2411: 	}
 2412:         my (%typeparts,%randombytry);
 2413:         my $showsurv = 
 2414:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
 2415:         foreach my $key (sort(keys(%lasthash))) {
 2416:             if ($key =~ /\.type$/) {
 2417:                 if (($lasthash{$key} eq 'anonsurvey') || 
 2418:                     ($lasthash{$key} eq 'anonsurveycred') ||
 2419:                     ($lasthash{$key} eq 'randomizetry')) {
 2420:                     my ($ign,@parts) = split(/\./,$key);
 2421:                     pop(@parts);
 2422:                     my $id = join('.',@parts);
 2423:                     if ($lasthash{$key} eq 'randomizetry') {
 2424:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
 2425:                     } else {
 2426:                         unless ($showsurv) {
 2427:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
 2428:                         }
 2429:                     }
 2430:                     delete($lasthash{$key});
 2431:                 }
 2432:             }
 2433:         }
 2434:         my @hidden = keys(%typeparts);
 2435:         my @randomize = keys(%randombytry);
 2436: 	foreach my $key (keys(%lasthash)) {
 2437: 	    next if ($key !~ /\.submission$/);
 2438:             my $hide;
 2439:             if (@hidden) {
 2440:                 foreach my $id (@hidden) {
 2441:                     if ($key =~ /^\Q$id\E/) {
 2442:                         $hide = 'anon';
 2443:                         last;
 2444:                     }
 2445:                 }
 2446:             }
 2447:             unless ($hide) {
 2448:                 if (@randomize) {
 2449:                     foreach my $id (@hidden) {
 2450:                         if ($key =~ /^\Q$id\E/) {
 2451:                             $hide = 'rand';
 2452:                             last;
 2453:                         }
 2454:                     }
 2455:                 }
 2456:             }
 2457: 	    my ($partid,$foo) = split(/submission$/,$key);
 2458: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
 2459: 		'<span class="LC_warning">Draft Copy</span> ' : '';
 2460: 	    push(@string, join(':', $key, $hide, $draft.$lasthash{$key}));
 2461: 	}
 2462:     }
 2463:     if (!@string) {
 2464: 	$string[0] =
 2465: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
 2466:     }
 2467:     return (\@string,\$timestamp);
 2468: }
 2469: 
 2470: #--- High light keywords, with style choosen by user.
 2471: sub keywords_highlight {
 2472:     my $string    = shift;
 2473:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2474:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2475:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2476:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2477:     foreach my $keyword (@keylist) {
 2478: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2479:     }
 2480:     return $string;
 2481: }
 2482: 
 2483: #--- Called from submission routine
 2484: sub processHandGrade {
 2485:     my ($request,$symb) = @_;
 2486:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2487:     my $button = $env{'form.gradeOpt'};
 2488:     my $ngrade = $env{'form.NCT'};
 2489:     my $ntstu  = $env{'form.NTSTU'};
 2490:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2491:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 2492: 
 2493:     if ($button eq 'Save & Next') {
 2494: 	my $ctr = 0;
 2495: 	while ($ctr < $ngrade) {
 2496: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 2497: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 2498: 	    if ($errorflag eq 'no_score') {
 2499: 		$ctr++;
 2500: 		next;
 2501: 	    }
 2502: 	    if ($errorflag eq 'not_allowed') {
 2503: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
 2504: 		$ctr++;
 2505: 		next;
 2506: 	    }
 2507: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 2508: 	    my ($subject,$message,$msgstatus) = ('','','');
 2509: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 2510:             my ($feedurl,$showsymb) =
 2511: 		&get_feedurl_and_symb($symb,$uname,$udom);
 2512: 	    my $messagetail;
 2513: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 2514: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 2515: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 2516: 		$subject.=' ['.$restitle.']';
 2517: 		my (@msgnum) = split(/,/,$includemsg);
 2518: 		foreach (@msgnum) {
 2519: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 2520: 		}
 2521: 		$message =&Apache::lonfeedback::clear_out_html($message);
 2522: 		if ($env{'form.withgrades'.$ctr}) {
 2523: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 2524: 		    $messagetail = " for <a href=\"".
 2525: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
 2526: 		}
 2527: 		$msgstatus = 
 2528:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 2529: 						     $message.$messagetail,
 2530:                                                      undef,$feedurl,undef,
 2531:                                                      undef,undef,$showsymb,
 2532:                                                      $restitle);
 2533: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
 2534: 				$msgstatus);
 2535: 	    }
 2536: 	    if ($env{'form.collaborator'.$ctr}) {
 2537: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 2538: 		foreach my $collabstr (@collabstrs) {
 2539: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 2540: 		    foreach my $collaborator (@collaborators) {
 2541: 			my ($errorflag,$pts,$wgt) = 
 2542: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 2543: 					   $env{'form.unamedom'.$ctr},$part);
 2544: 			if ($errorflag eq 'not_allowed') {
 2545: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 2546: 			    next;
 2547: 			} elsif ($message ne '') {
 2548: 			    my ($baseurl,$showsymb) = 
 2549: 				&get_feedurl_and_symb($symb,$collaborator,
 2550: 						      $udom);
 2551: 			    if ($env{'form.withgrades'.$ctr}) {
 2552: 				$messagetail = " for <a href=\"".
 2553:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
 2554: 			    }
 2555: 			    $msgstatus = 
 2556: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 2557: 			}
 2558: 		    }
 2559: 		}
 2560: 	    }
 2561: 	    $ctr++;
 2562: 	}
 2563:     }
 2564: 
 2565: #    if ($env{'form.handgrade'} eq 'yes') {
 2566:     if (1) {
 2567: 	# Keywords sorted in alphabatical order
 2568: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2569: 	my %keyhash = ();
 2570: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 2571: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 2572: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 2573: 	$env{'form.keywords'} = join(' ',@keywords);
 2574: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 2575: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 2576: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 2577: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 2578: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 2579: 
 2580: 	# message center - Order of message gets changed. Blank line is eliminated.
 2581: 	# New messages are saved in env for the next student.
 2582: 	# All messages are saved in nohist_handgrade.db
 2583: 	my ($ctr,$idx) = (1,1);
 2584: 	while ($ctr <= $env{'form.savemsgN'}) {
 2585: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 2586: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 2587: 		$idx++;
 2588: 	    }
 2589: 	    $ctr++;
 2590: 	}
 2591: 	$ctr = 0;
 2592: 	while ($ctr < $ngrade) {
 2593: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 2594: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2595: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2596: 		$idx++;
 2597: 	    }
 2598: 	    $ctr++;
 2599: 	}
 2600: 	$env{'form.savemsgN'} = --$idx;
 2601: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 2602: 	my $putresult = &Apache::lonnet::put
 2603: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 2604:     }
 2605:     # Called by Save & Refresh from Highlight Attribute Window
 2606:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 2607:     if ($env{'form.refresh'} eq 'on') {
 2608: 	my ($ctr,$total) = (0,0);
 2609: 	while ($ctr < $ngrade) {
 2610: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 2611: 	    $ctr++;
 2612: 	}
 2613: 	$env{'form.NTSTU'}=$ngrade;
 2614: 	$ctr = 0;
 2615: 	while ($ctr < $total) {
 2616: 	    my $processUser = $env{'form.unamedom'.$ctr};
 2617: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2618: 	    $env{'form.fullname'} = $$fullname{$processUser};
 2619: 	    &submission($request,$ctr,$total-1,$symb);
 2620: 	    $ctr++;
 2621: 	}
 2622: 	return '';
 2623:     }
 2624: 
 2625:     # Get the next/previous one or group of students
 2626:     my $firststu = $env{'form.unamedom0'};
 2627:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 2628:     my $ctr = 2;
 2629:     while ($laststu eq '') {
 2630: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 2631: 	$ctr++;
 2632: 	$laststu = $firststu if ($ctr > $ngrade);
 2633:     }
 2634: 
 2635:     my (@parsedlist,@nextlist);
 2636:     my ($nextflg) = 0;
 2637:     foreach my $item (sort 
 2638: 	     {
 2639: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 2640: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 2641: 		 }
 2642: 		 return $a cmp $b;
 2643: 	     } (keys(%$fullname))) {
 2644: # FIXME: this is fishy, looks like the button label
 2645: 	if ($nextflg == 1 && $button =~ /Next$/) {
 2646: 	    push(@parsedlist,$item);
 2647: 	}
 2648: 	$nextflg = 1 if ($item eq $laststu);
 2649: 	if ($button eq 'Previous') {
 2650: 	    last if ($item eq $firststu);
 2651: 	    push(@parsedlist,$item);
 2652: 	}
 2653:     }
 2654:     $ctr = 0;
 2655: # FIXME: this is fishy, looks like the button label
 2656:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 2657:     my $res_error;
 2658:     my ($partlist) = &response_type($symb,\$res_error);
 2659:     if ($res_error) {
 2660:         $request->print(&navmap_errormsg());
 2661:         return;
 2662:     }
 2663:     foreach my $student (@parsedlist) {
 2664: 	my $submitonly=$env{'form.submitonly'};
 2665: 	my ($uname,$udom) = split(/:/,$student);
 2666: 	
 2667: 	if ($submitonly eq 'queued') {
 2668: 	    my %queue_status = 
 2669: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 2670: 							$udom,$uname);
 2671: 	    next if (!defined($queue_status{'gradingqueue'}));
 2672: 	}
 2673: 
 2674: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 2675: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2676: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 2677: 	    my $submitted = 0;
 2678: 	    my $ungraded = 0;
 2679: 	    my $incorrect = 0;
 2680: 	    foreach my $item (keys(%status)) {
 2681: 		$submitted = 1 if ($status{$item} ne 'nothing');
 2682: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 2683: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 2684: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 2685: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 2686: 		    $submitted = 0;
 2687: 		}
 2688: 	    }
 2689: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 2690: 				     $submitonly eq 'incorrect' ||
 2691: 				     $submitonly eq 'graded'));
 2692: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 2693: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 2694: 	}
 2695: 	push(@nextlist,$student) if ($ctr < $ntstu);
 2696: 	last if ($ctr == $ntstu);
 2697: 	$ctr++;
 2698:     }
 2699: 
 2700:     $ctr = 0;
 2701:     my $total = scalar(@nextlist)-1;
 2702: 
 2703:     foreach (sort(@nextlist)) {
 2704: 	my ($uname,$udom,$submitter) = split(/:/);
 2705: 	$env{'form.student'}  = $uname;
 2706: 	$env{'form.userdom'}  = $udom;
 2707: 	$env{'form.fullname'} = $$fullname{$_};
 2708: 	&submission($request,$ctr,$total,$symb);
 2709: 	$ctr++;
 2710:     }
 2711:     if ($total < 0) {
 2712: 	my $the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
 2713: 	$request->print($the_end);
 2714:     }
 2715:     return '';
 2716: }
 2717: 
 2718: #---- Save the score and award for each student, if changed
 2719: sub saveHandGrade {
 2720:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 2721:     my @version_parts;
 2722:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 2723: 					   $env{'request.course.id'});
 2724:     if (!&canmodify($usec)) { return('not_allowed'); }
 2725:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 2726:     my @parts_graded;
 2727:     my %newrecord  = ();
 2728:     my ($pts,$wgt) = ('','');
 2729:     my %aggregate = ();
 2730:     my $aggregateflag = 0;
 2731:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 2732:     foreach my $new_part (@parts) {
 2733: 	#collaborator ($submi may vary for different parts
 2734: 	if ($submitter && $new_part ne $part) { next; }
 2735: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 2736: 	if ($dropMenu eq 'excused') {
 2737: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 2738: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 2739: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 2740: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 2741: 		}
 2742: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 2743: 	    }
 2744: 	} elsif ($dropMenu eq 'reset status'
 2745: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 2746: 	    foreach my $key (keys(%record)) {
 2747: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 2748: 	    }
 2749: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2750: 		"$env{'user.name'}:$env{'user.domain'}";
 2751:             my $totaltries = $record{'resource.'.$part.'.tries'};
 2752: 
 2753:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 2754: 					       [$new_part]);
 2755:             my $aggtries =$totaltries;
 2756:             if ($last_resets{$new_part}) {
 2757:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 2758: 					   $new_part);
 2759:             }
 2760: 
 2761:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 2762:             if ($aggtries > 0) {
 2763:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 2764:                 $aggregateflag = 1;
 2765:             }
 2766: 	} elsif ($dropMenu eq '') {
 2767: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 2768: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 2769: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 2770: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 2771: 		next;
 2772: 	    }
 2773: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 2774: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 2775: 	    my $partial= $pts/$wgt;
 2776: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 2777: 		#do not update score for part if not changed.
 2778:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 2779: 		next;
 2780: 	    } else {
 2781: 	        push(@parts_graded,$new_part);
 2782: 	    }
 2783: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 2784: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 2785: 	    }
 2786: 	    my $reckey = 'resource.'.$new_part.'.solved';
 2787: 	    if ($partial == 0) {
 2788: 		if ($record{$reckey} ne 'incorrect_by_override') {
 2789: 		    $newrecord{$reckey} = 'incorrect_by_override';
 2790: 		}
 2791: 	    } else {
 2792: 		if ($record{$reckey} ne 'correct_by_override') {
 2793: 		    $newrecord{$reckey} = 'correct_by_override';
 2794: 		}
 2795: 	    }	    
 2796: 	    if ($submitter && 
 2797: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 2798: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 2799: 	    }
 2800: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2801: 		"$env{'user.name'}:$env{'user.domain'}";
 2802: 	}
 2803: 	# unless problem has been graded, set flag to version the submitted files
 2804: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 2805: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 2806: 	        $dropMenu eq 'reset status')
 2807: 	   {
 2808: 	    push(@version_parts,$new_part);
 2809: 	}
 2810:     }
 2811:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2812:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2813: 
 2814:     if (%newrecord) {
 2815:         if (@version_parts) {
 2816:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 2817:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 2818: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 2819: 	    foreach my $new_part (@version_parts) {
 2820: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 2821: 				$new_part,\%newrecord);
 2822: 	    }
 2823:         }
 2824: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 2825: 				$env{'request.course.id'},$domain,$stuname);
 2826: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 2827: 				     $cdom,$cnum,$domain,$stuname);
 2828:     }
 2829:     if ($aggregateflag) {
 2830:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 2831: 			      $cdom,$cnum);
 2832:     }
 2833:     return ('',$pts,$wgt);
 2834: }
 2835: 
 2836: sub check_and_remove_from_queue {
 2837:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 2838:     my @ungraded_parts;
 2839:     foreach my $part (@{$parts}) {
 2840: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 2841: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 2842: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 2843: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 2844: 		) {
 2845: 	    push(@ungraded_parts, $part);
 2846: 	}
 2847:     }
 2848:     if ( !@ungraded_parts ) {
 2849: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 2850: 					       $cnum,$domain,$stuname);
 2851:     }
 2852: }
 2853: 
 2854: sub handback_files {
 2855:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 2856:     my $portfolio_root = '/userfiles/portfolio';
 2857:     my $res_error;
 2858:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2859:     if ($res_error) {
 2860:         $request->print('<br />'.&navmap_errormsg().'<br />');
 2861:         return;
 2862:     }
 2863:     my @part_response_id = &flatten_responseType($responseType);
 2864:     foreach my $part_response_id (@part_response_id) {
 2865:     	my ($part_id,$resp_id) = @{ $part_response_id };
 2866: 	my $part_resp = join('_',@{ $part_response_id });
 2867:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
 2868:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
 2869:                 my $file_counter = 1;
 2870: 		my $file_msg;
 2871:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
 2872:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
 2873:                     my ($directory,$answer_file) = 
 2874:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
 2875:                     my ($answer_name,$answer_ver,$answer_ext) =
 2876: 		        &file_name_version_ext($answer_file);
 2877: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 2878:                     my $getpropath = 1;
 2879: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
 2880: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 2881:                     # fix file name
 2882:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 2883:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 2884:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
 2885:             	                                $save_file_name);
 2886:                     if ($result !~ m|^/uploaded/|) {
 2887:                         $request->print('<br /><span class="LC_error">'.
 2888:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 2889:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$file_counter).
 2890:                                         '</span>');
 2891:                     } else {
 2892:                         # mark the file as read only
 2893:                         my @files = ($save_file_name);
 2894:                         my @what = ($symb,$env{'request.course.id'},'handback');
 2895:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
 2896: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 2897: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 2898: 			}
 2899:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 2900: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
 2901: 
 2902:                     }
 2903:                     $request->print("<br />".$fname." will be the uploaded file name");
 2904:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
 2905:                     $file_counter++;
 2906:                 }
 2907: 		my $subject = "File Handed Back by Instructor ";
 2908: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
 2909: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
 2910: 		$message .= ' The returned file(s) are named: '. $file_msg;
 2911: 		$message .= " and can be found in your portfolio space.";
 2912: 		my ($feedurl,$showsymb) = 
 2913: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
 2914:                 my $restitle = &Apache::lonnet::gettitle($symb);
 2915: 		my $msgstatus = 
 2916:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
 2917: 			 ' (File Returned) ['.$restitle.']',$message,undef,
 2918:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
 2919:             }
 2920:         }
 2921:     return;
 2922: }
 2923: 
 2924: sub get_feedurl_and_symb {
 2925:     my ($symb,$uname,$udom) = @_;
 2926:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2927:     $url = &Apache::lonnet::clutter($url);
 2928:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 2929: 					$symb,$udom,$uname);
 2930:     if ($encrypturl =~ /^yes$/i) {
 2931: 	&Apache::lonenc::encrypted(\$url,1);
 2932: 	&Apache::lonenc::encrypted(\$symb,1);
 2933:     }
 2934:     return ($url,$symb);
 2935: }
 2936: 
 2937: sub get_submitted_files {
 2938:     my ($udom,$uname,$partid,$respid,$record) = @_;
 2939:     my @files;
 2940:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 2941:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 2942:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 2943:     	    push(@files,$file_url.$file);
 2944:         }
 2945:     }
 2946:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 2947:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 2948:     }
 2949:     return (\@files);
 2950: }
 2951: 
 2952: # ----------- Provides number of tries since last reset.
 2953: sub get_num_tries {
 2954:     my ($record,$last_reset,$part) = @_;
 2955:     my $timestamp = '';
 2956:     my $num_tries = 0;
 2957:     if ($$record{'version'}) {
 2958:         for (my $version=$$record{'version'};$version>=1;$version--) {
 2959:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 2960:                 $timestamp = $$record{$version.':timestamp'};
 2961:                 if ($timestamp > $last_reset) {
 2962:                     $num_tries ++;
 2963:                 } else {
 2964:                     last;
 2965:                 }
 2966:             }
 2967:         }
 2968:     }
 2969:     return $num_tries;
 2970: }
 2971: 
 2972: # ----------- Determine decrements required in aggregate totals 
 2973: sub decrement_aggs {
 2974:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 2975:     my %decrement = (
 2976:                         attempts => 0,
 2977:                         users => 0,
 2978:                         correct => 0
 2979:                     );
 2980:     $decrement{'attempts'} = $aggtries;
 2981:     if ($solvedstatus =~ /^correct/) {
 2982:         $decrement{'correct'} = 1;
 2983:     }
 2984:     if ($aggtries == $totaltries) {
 2985:         $decrement{'users'} = 1;
 2986:     }
 2987:     foreach my $type (keys(%decrement)) {
 2988:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 2989:     }
 2990:     return;
 2991: }
 2992: 
 2993: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 2994: sub get_last_resets {
 2995:     my ($symb,$courseid,$partids) =@_;
 2996:     my %last_resets;
 2997:     my $cdom = $env{'course.'.$courseid.'.domain'};
 2998:     my $cname = $env{'course.'.$courseid.'.num'};
 2999:     my @keys;
 3000:     foreach my $part (@{$partids}) {
 3001: 	push(@keys,"$symb\0$part\0resettime");
 3002:     }
 3003:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 3004: 				     $cdom,$cname);
 3005:     foreach my $part (@{$partids}) {
 3006: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 3007:     }
 3008:     return %last_resets;
 3009: }
 3010: 
 3011: # ----------- Handles creating versions for portfolio files as answers
 3012: sub version_portfiles {
 3013:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 3014:     my $version_parts = join('|',@$v_flag);
 3015:     my @returned_keys;
 3016:     my $parts = join('|', @$parts_graded);
 3017:     my $portfolio_root = '/userfiles/portfolio';
 3018:     foreach my $key (keys(%$record)) {
 3019:         my $new_portfiles;
 3020:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 3021:             my @versioned_portfiles;
 3022:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 3023:             foreach my $file (@portfiles) {
 3024:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 3025:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 3026: 		my ($answer_name,$answer_ver,$answer_ext) =
 3027: 		    &file_name_version_ext($answer_file);
 3028:                 my $getpropath = 1;    
 3029:                 my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
 3030:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 3031:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
 3032:                 if ($new_answer ne 'problem getting file') {
 3033:                     push(@versioned_portfiles, $directory.$new_answer);
 3034:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
 3035:                         [$directory.$new_answer],
 3036:                         [$symb,$env{'request.course.id'},'graded']);
 3037:                 }
 3038:             }
 3039:             $$record{$key} = join(',',@versioned_portfiles);
 3040:             push(@returned_keys,$key);
 3041:         }
 3042:     } 
 3043:     return (@returned_keys);   
 3044: }
 3045: 
 3046: sub get_next_version {
 3047:     my ($answer_name, $answer_ext, $dir_list) = @_;
 3048:     my $version;
 3049:     foreach my $row (@$dir_list) {
 3050:         my ($file) = split(/\&/,$row,2);
 3051:         my ($file_name,$file_version,$file_ext) =
 3052: 	    &file_name_version_ext($file);
 3053:         if (($file_name eq $answer_name) && 
 3054: 	    ($file_ext eq $answer_ext)) {
 3055:                 # gets here if filename and extension match, regardless of version
 3056:                 if ($file_version ne '') {
 3057:                 # a versioned file is found  so save it for later
 3058:                 if ($file_version > $version) {
 3059: 		    $version = $file_version;
 3060: 	        }
 3061:             }
 3062:         }
 3063:     } 
 3064:     $version ++;
 3065:     return($version);
 3066: }
 3067: 
 3068: sub version_selected_portfile {
 3069:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 3070:     my ($answer_name,$answer_ver,$answer_ext) =
 3071:         &file_name_version_ext($file_name);
 3072:     my $new_answer;
 3073:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 3074:     if($env{'form.copy'} eq '-1') {
 3075:         $new_answer = 'problem getting file';
 3076:     } else {
 3077:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 3078:         my $copy_result = &Apache::lonnet::finishuserfileupload(
 3079:                             $stu_name,$domain,'copy',
 3080: 		        '/portfolio'.$directory.$new_answer);
 3081:     }    
 3082:     return ($new_answer);
 3083: }
 3084: 
 3085: sub file_name_version_ext {
 3086:     my ($file)=@_;
 3087:     my @file_parts = split(/\./, $file);
 3088:     my ($name,$version,$ext);
 3089:     if (@file_parts > 1) {
 3090: 	$ext=pop(@file_parts);
 3091: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 3092: 	    $version=pop(@file_parts);
 3093: 	}
 3094: 	$name=join('.',@file_parts);
 3095:     } else {
 3096: 	$name=join('.',@file_parts);
 3097:     }
 3098:     return($name,$version,$ext);
 3099: }
 3100: 
 3101: #--------------------------------------------------------------------------------------
 3102: #
 3103: #-------------------------- Next few routines handles grading by section or whole class
 3104: #
 3105: #--- Javascript to handle grading by section or whole class
 3106: sub viewgrades_js {
 3107:     my ($request) = shift;
 3108: 
 3109:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3110:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
 3111:    function writePoint(partid,weight,point) {
 3112: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3113: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3114: 	if (point == "textval") {
 3115: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3116: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3117: 		alert("$alertmsg"+parseFloat(point));
 3118: 		var resetbox = false;
 3119: 		for (var i=0; i<radioButton.length; i++) {
 3120: 		    if (radioButton[i].checked) {
 3121: 			textbox.value = i;
 3122: 			resetbox = true;
 3123: 		    }
 3124: 		}
 3125: 		if (!resetbox) {
 3126: 		    textbox.value = "";
 3127: 		}
 3128: 		return;
 3129: 	    }
 3130: 	    if (parseFloat(point) > parseFloat(weight)) {
 3131: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3132: 				   ") greater than the weight for the part. Accept?");
 3133: 		if (resp == false) {
 3134: 		    textbox.value = "";
 3135: 		    return;
 3136: 		}
 3137: 	    }
 3138: 	    for (var i=0; i<radioButton.length; i++) {
 3139: 		radioButton[i].checked=false;
 3140: 		if (parseFloat(point) == i) {
 3141: 		    radioButton[i].checked=true;
 3142: 		}
 3143: 	    }
 3144: 
 3145: 	} else {
 3146: 	    textbox.value = parseFloat(point);
 3147: 	}
 3148: 	for (i=0;i<document.classgrade.total.value;i++) {
 3149: 	    var user = document.classgrade["ctr"+i].value;
 3150: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3151: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3152: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3153: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3154: 	    if (saveval != "correct") {
 3155: 		scorename.value = point;
 3156: 		if (selname[0].selected != true) {
 3157: 		    selname[0].selected = true;
 3158: 		}
 3159: 	    }
 3160: 	}
 3161: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3162:     }
 3163: 
 3164:     function writeRadText(partid,weight) {
 3165: 	var selval   = document.classgrade["SELVAL_"+partid];
 3166: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3167:         var override = document.classgrade["FORCE_"+partid].checked;
 3168: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3169: 	if (selval[1].selected || selval[2].selected) {
 3170: 	    for (var i=0; i<radioButton.length; i++) {
 3171: 		radioButton[i].checked=false;
 3172: 
 3173: 	    }
 3174: 	    textbox.value = "";
 3175: 
 3176: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3177: 		var user = document.classgrade["ctr"+i].value;
 3178: 		user = user.replace(new RegExp(':', 'g'),"_");
 3179: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3180: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3181: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3182: 		if ((saveval != "correct") || override) {
 3183: 		    scorename.value = "";
 3184: 		    if (selval[1].selected) {
 3185: 			selname[1].selected = true;
 3186: 		    } else {
 3187: 			selname[2].selected = true;
 3188: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3189: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3190: 		    }
 3191: 		}
 3192: 	    }
 3193: 	} else {
 3194: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3195: 		var user = document.classgrade["ctr"+i].value;
 3196: 		user = user.replace(new RegExp(':', 'g'),"_");
 3197: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3198: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3199: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3200: 		if ((saveval != "correct") || override) {
 3201: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3202: 		    selname[0].selected = true;
 3203: 		}
 3204: 	    }
 3205: 	}	    
 3206:     }
 3207: 
 3208:     function changeSelect(partid,user) {
 3209: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3210: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3211: 	var point  = textbox.value;
 3212: 	var weight = document.classgrade["weight_"+partid].value;
 3213: 
 3214: 	if (isNaN(point) || parseFloat(point) < 0) {
 3215: 	    alert("$alertmsg"+parseFloat(point));
 3216: 	    textbox.value = "";
 3217: 	    return;
 3218: 	}
 3219: 	if (parseFloat(point) > parseFloat(weight)) {
 3220: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3221: 			       ") greater than the weight of the part. Accept?");
 3222: 	    if (resp == false) {
 3223: 		textbox.value = "";
 3224: 		return;
 3225: 	    }
 3226: 	}
 3227: 	selval[0].selected = true;
 3228:     }
 3229: 
 3230:     function changeOneScore(partid,user) {
 3231: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3232: 	if (selval[1].selected || selval[2].selected) {
 3233: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3234: 	    if (selval[2].selected) {
 3235: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3236: 	    }
 3237:         }
 3238:     }
 3239: 
 3240:     function resetEntry(numpart) {
 3241: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3242: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3243: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3244: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3245: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3246: 	    for (var i=0; i<radioButton.length; i++) {
 3247: 		radioButton[i].checked=false;
 3248: 
 3249: 	    }
 3250: 	    textbox.value = "";
 3251: 	    selval[0].selected = true;
 3252: 
 3253: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3254: 		var user = document.classgrade["ctr"+i].value;
 3255: 		user = user.replace(new RegExp(':', 'g'),"_");
 3256: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3257: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3258: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3259: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3260: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3261: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3262: 		if (saveselval == "excused") {
 3263: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3264: 		} else {
 3265: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3266: 		}
 3267: 	    }
 3268: 	}
 3269:     }
 3270: 
 3271: VIEWJAVASCRIPT
 3272: }
 3273: 
 3274: #--- show scores for a section or whole class w/ option to change/update a score
 3275: sub viewgrades {
 3276:     my ($request,$symb) = @_;
 3277:     &viewgrades_js($request);
 3278: 
 3279:     #need to make sure we have the correct data for later EXT calls, 
 3280:     #thus invalidate the cache
 3281:     &Apache::lonnet::devalidatecourseresdata(
 3282:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3283:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3284:     &Apache::lonnet::clear_EXT_cache_status();
 3285: 
 3286:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3287: 
 3288:     #view individual student submission form - called using Javascript viewOneStudent
 3289:     $result.=&jscriptNform($symb);
 3290: 
 3291:     #beginning of class grading form
 3292:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3293:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3294: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3295: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3296: 	&build_section_inputs().
 3297: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3298: 
 3299:     my ($common_header,$specific_header);
 3300:     if ($env{'form.section'} eq 'all') {
 3301: 	$common_header = &mt('Assign Common Grade to Class');
 3302:         $specific_header = &mt('Assign Grade to Specific Students in Class');
 3303:     } elsif ($env{'form.section'} eq 'none') {
 3304:         $common_header = &mt('Assign Common Grade to Students in no Section');
 3305: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
 3306:     } else {
 3307:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3308:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
 3309: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
 3310:     }
 3311:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
 3312:     #radio buttons/text box for assigning points for a section or class.
 3313:     #handles different parts of a problem
 3314:     my $res_error;
 3315:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3316:     if ($res_error) {
 3317:         return &navmap_errormsg();
 3318:     }
 3319:     my %weight = ();
 3320:     my $ctsparts = 0;
 3321:     my %seen = ();
 3322:     my @part_response_id = &flatten_responseType($responseType);
 3323:     foreach my $part_response_id (@part_response_id) {
 3324:     	my ($partid,$respid) = @{ $part_response_id };
 3325: 	my $part_resp = join('_',@{ $part_response_id });
 3326: 	next if $seen{$partid};
 3327: 	$seen{$partid}++;
 3328: 	my $handgrade=$$handgrade{$part_resp};
 3329: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 3330: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 3331: 
 3332: 	my $display_part=&get_display_part($partid,$symb);
 3333: 	my $radio.='<table border="0"><tr>';  
 3334: 	my $ctr = 0;
 3335: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 3336: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 3337: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 3338: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 3339: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 3340: 	    $ctr++;
 3341: 	}
 3342: 	$radio.='</tr></table>';
 3343: 	my $line = '<input type="text" name="TEXTVAL_'.
 3344: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
 3345: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 3346: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 3347: 	$line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
 3348: 	    'onchange="javascript:writeRadText(\''.$partid.'\','.
 3349: 		$weight{$partid}.')"> '.
 3350: 	    '<option selected="selected"> </option>'.
 3351: 	    '<option value="excused">'.&mt('excused').'</option>'.
 3352: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 3353: 	    '</select></td>'.
 3354:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 3355: 	$line.='<input type="hidden" name="partid_'.
 3356: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 3357: 	$line.='<input type="hidden" name="weight_'.
 3358: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 3359: 
 3360: 	$result.=
 3361: 	    &Apache::loncommon::start_data_table_row()."\n".
 3362: 	    '<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>'.
 3363: 	    &Apache::loncommon::end_data_table_row()."\n";
 3364: 	$ctsparts++;
 3365:     }
 3366:     $result.=&Apache::loncommon::end_data_table()."\n".
 3367: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 3368:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 3369: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
 3370: 
 3371:     #table listing all the students in a section/class
 3372:     #header of table
 3373:     $result.= '<h3>'.$specific_header.'</h3>'.
 3374:               &Apache::loncommon::start_data_table().
 3375: 	      &Apache::loncommon::start_data_table_header_row().
 3376: 	      '<th>'.&mt('No.').'</th>'.
 3377: 	      '<th>'.&nameUserString('header')."</th>\n";
 3378:     my $partserror;
 3379:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3380:     if ($partserror) {
 3381:         return &navmap_errormsg();
 3382:     }
 3383:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 3384:     my @partids = ();
 3385:     foreach my $part (@parts) {
 3386: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3387:         my $narrowtext = &mt('Tries');
 3388: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 3389: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 3390: 	my ($partid) = &split_part_type($part);
 3391:         push(@partids,$partid);
 3392: #
 3393: # FIXME: Looks like $display looks at English text
 3394: #
 3395: 	my $display_part=&get_display_part($partid,$symb);
 3396: 	if ($display =~ /^Partial Credit Factor/) {
 3397: 	    $result.='<th>'.
 3398: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
 3399: 		    $display_part,$weight{$partid}).'</th>'."\n";
 3400: 	    next;
 3401: 	    
 3402: 	} else {
 3403: 	    if ($display =~ /Problem Status/) {
 3404: 		my $grade_status_mt = &mt('Grade Status');
 3405: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 3406: 	    }
 3407: 	    my $part_mt = &mt('Part:');
 3408: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 3409: 	}
 3410: 
 3411: 	$result.='<th>'.$display.'</th>'."\n";
 3412:     }
 3413:     $result.=&Apache::loncommon::end_data_table_header_row();
 3414: 
 3415:     my %last_resets = 
 3416: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 3417: 
 3418:     #get info for each student
 3419:     #list all the students - with points and grade status
 3420:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3421:     my $ctr = 0;
 3422:     foreach (sort 
 3423: 	     {
 3424: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3425: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3426: 		 }
 3427: 		 return $a cmp $b;
 3428: 	     } (keys(%$fullname))) {
 3429: 	$ctr++;
 3430: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 3431: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
 3432:     }
 3433:     $result.=&Apache::loncommon::end_data_table();
 3434:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 3435:     $result.='<input type="button" value="'.&mt('Save').'" '.
 3436: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
 3437:     if (scalar(%$fullname) eq 0) {
 3438: 	my $colspan=3+scalar(@parts);
 3439: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3440:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 3441: 	$result='<span class="LC_warning">'.
 3442: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 3443: 	        $section_display, $stu_status).
 3444: 	    '</span>';
 3445:     }
 3446:     return $result;
 3447: }
 3448: 
 3449: #--- call by previous routine to display each student
 3450: sub viewstudentgrade {
 3451:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 3452:     my ($uname,$udom) = split(/:/,$student);
 3453:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 3454:     my %aggregates = (); 
 3455:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 3456: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
 3457: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
 3458: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 3459: 	'\');" target="_self">'.$fullname.'</a> '.
 3460: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 3461:     $student=~s/:/_/; # colon doen't work in javascript for names
 3462:     foreach my $apart (@$parts) {
 3463: 	my ($part,$type) = &split_part_type($apart);
 3464: 	my $score=$record{"resource.$part.$type"};
 3465:         $result.='<td align="center">';
 3466:         my ($aggtries,$totaltries);
 3467:         unless (exists($aggregates{$part})) {
 3468: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 3469: 
 3470: 	    $aggtries = $totaltries;
 3471:             if ($$last_resets{$part}) {  
 3472:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 3473: 					   $part);
 3474:             }
 3475:             $result.='<input type="hidden" name="'.
 3476:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 3477:             $result.='<input type="hidden" name="'.
 3478:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 3479:             $aggregates{$part} = 1;
 3480:         }
 3481: 	if ($type eq 'awarded') {
 3482: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 3483: 	    $result.='<input type="hidden" name="'.
 3484: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 3485: 	    $result.='<input type="text" name="'.
 3486: 		'GD_'.$student.'_'.$part.'_awarded" '.
 3487:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
 3488: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 3489: 	} elsif ($type eq 'solved') {
 3490: 	    my ($status,$foo)=split(/_/,$score,2);
 3491: 	    $status = 'nothing' if ($status eq '');
 3492: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 3493: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 3494: 	    $result.='&nbsp;<select name="'.
 3495: 		'GD_'.$student.'_'.$part.'_solved" '.
 3496:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 3497: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 3498: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 3499: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 3500: 	    $result.="</select>&nbsp;</td>\n";
 3501: 	} else {
 3502: 	    $result.='<input type="hidden" name="'.
 3503: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 3504: 		    "\n";
 3505: 	    $result.='<input type="text" name="'.
 3506: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 3507: 		'value="'.$score.'" size="4" /></td>'."\n";
 3508: 	}
 3509:     }
 3510:     $result.=&Apache::loncommon::end_data_table_row();
 3511:     return $result;
 3512: }
 3513: 
 3514: #--- change scores for all the students in a section/class
 3515: #    record does not get update if unchanged
 3516: sub editgrades {
 3517:     my ($request,$symb) = @_;
 3518: 
 3519:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3520:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 3521:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
 3522: 
 3523:     my $result= &Apache::loncommon::start_data_table().
 3524: 	&Apache::loncommon::start_data_table_header_row().
 3525: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 3526: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 3527:     my %scoreptr = (
 3528: 		    'correct'  =>'correct_by_override',
 3529: 		    'incorrect'=>'incorrect_by_override',
 3530: 		    'excused'  =>'excused',
 3531: 		    'ungraded' =>'ungraded_attempted',
 3532:                     'credited' =>'credit_attempted',
 3533: 		    'nothing'  => '',
 3534: 		    );
 3535:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 3536: 
 3537:     my (@partid);
 3538:     my %weight = ();
 3539:     my %columns = ();
 3540:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 3541: 
 3542:     my $partserror;
 3543:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3544:     if ($partserror) {
 3545:         return &navmap_errormsg();
 3546:     }
 3547:     my $header;
 3548:     while ($ctr < $env{'form.totalparts'}) {
 3549: 	my $partid = $env{'form.partid_'.$ctr};
 3550: 	push(@partid,$partid);
 3551: 	$weight{$partid} = $env{'form.weight_'.$partid};
 3552: 	$ctr++;
 3553:     }
 3554:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3555:     foreach my $partid (@partid) {
 3556: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 3557: 	    '<th align="center">'.&mt('New Score').'</th>';
 3558: 	$columns{$partid}=2;
 3559: 	foreach my $stores (@parts) {
 3560: 	    my ($part,$type) = &split_part_type($stores);
 3561: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 3562: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 3563: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 3564: 	    $display =~ s/\[Part: \Q$part\E\]//;
 3565:             my $narrowtext = &mt('Tries');
 3566: 	    $display =~ s/Number of Attempts/$narrowtext/;
 3567: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 3568: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 3569: 	    $columns{$partid}+=2;
 3570: 	}
 3571:     }
 3572:     foreach my $partid (@partid) {
 3573: 	my $display_part=&get_display_part($partid,$symb);
 3574: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 3575: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 3576: 	    '</th>';
 3577: 
 3578:     }
 3579:     $result .= &Apache::loncommon::end_data_table_header_row().
 3580: 	&Apache::loncommon::start_data_table_header_row().
 3581: 	$header.
 3582: 	&Apache::loncommon::end_data_table_header_row();
 3583:     my @noupdate;
 3584:     my ($updateCtr,$noupdateCtr) = (1,1);
 3585:     for ($i=0; $i<$env{'form.total'}; $i++) {
 3586: 	my $line;
 3587: 	my $user = $env{'form.ctr'.$i};
 3588: 	my ($uname,$udom)=split(/:/,$user);
 3589: 	my %newrecord;
 3590: 	my $updateflag = 0;
 3591: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 3592: 	my $usec=$classlist->{"$uname:$udom"}[5];
 3593: 	if (!&canmodify($usec)) {
 3594: 	    my $numcols=scalar(@partid)*4+2;
 3595: 	    push(@noupdate,
 3596: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
 3597: 		 &mt('Not allowed to modify student')."</span></td></tr>");
 3598: 	    next;
 3599: 	}
 3600:         my %aggregate = ();
 3601:         my $aggregateflag = 0;
 3602: 	$user=~s/:/_/; # colon doen't work in javascript for names
 3603: 	foreach (@partid) {
 3604: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 3605: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 3606: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 3607: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3608: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 3609: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 3610: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 3611: 	    my $score;
 3612: 	    if ($partial eq '') {
 3613: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3614: 	    } elsif ($partial > 0) {
 3615: 		$score = 'correct_by_override';
 3616: 	    } elsif ($partial == 0) {
 3617: 		$score = 'incorrect_by_override';
 3618: 	    }
 3619: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 3620: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 3621: 
 3622: 	    $newrecord{'resource.'.$_.'.regrader'}=
 3623: 		"$env{'user.name'}:$env{'user.domain'}";
 3624: 	    if ($dropMenu eq 'reset status' &&
 3625: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 3626: 		$newrecord{'resource.'.$_.'.tries'} = '';
 3627: 		$newrecord{'resource.'.$_.'.solved'} = '';
 3628: 		$newrecord{'resource.'.$_.'.award'} = '';
 3629: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 3630: 		$updateflag = 1;
 3631:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 3632:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 3633:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 3634:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 3635:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3636:                     $aggregateflag = 1;
 3637:                 }
 3638: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 3639: 		$updateflag = 1;
 3640: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 3641: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 3642: 		$rec_update++;
 3643: 	    }
 3644: 
 3645: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3646: 		'<td align="center">'.$awarded.
 3647: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 3648: 
 3649: 
 3650: 	    my $partid=$_;
 3651: 	    foreach my $stores (@parts) {
 3652: 		my ($part,$type) = &split_part_type($stores);
 3653: 		if ($part !~ m/^\Q$partid\E/) { next;}
 3654: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 3655: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 3656: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 3657: 		if ($awarded ne '' && $awarded ne $old_aw) {
 3658: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 3659: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3660: 		    $updateflag=1;
 3661: 		}
 3662: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3663: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 3664: 	    }
 3665: 	}
 3666: 	$line.="\n";
 3667: 
 3668: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3669: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3670: 
 3671: 	if ($updateflag) {
 3672: 	    $count++;
 3673: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 3674: 				    $udom,$uname);
 3675: 
 3676: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 3677: 					      $cnum,$udom,$uname)) {
 3678: 		# need to figure out if should be in queue.
 3679: 		my %record =  
 3680: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 3681: 					     $udom,$uname);
 3682: 		my $all_graded = 1;
 3683: 		my $none_graded = 1;
 3684: 		foreach my $part (@parts) {
 3685: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 3686: 			$all_graded = 0;
 3687: 		    } else {
 3688: 			$none_graded = 0;
 3689: 		    }
 3690: 		}
 3691: 
 3692: 		if ($all_graded || $none_graded) {
 3693: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 3694: 							   $symb,$cdom,$cnum,
 3695: 							   $udom,$uname);
 3696: 		}
 3697: 	    }
 3698: 
 3699: 	    $result.=&Apache::loncommon::start_data_table_row().
 3700: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 3701: 		&Apache::loncommon::end_data_table_row();
 3702: 	    $updateCtr++;
 3703: 	} else {
 3704: 	    push(@noupdate,
 3705: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 3706: 	    $noupdateCtr++;
 3707: 	}
 3708:         if ($aggregateflag) {
 3709:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3710: 				  $cdom,$cnum);
 3711:         }
 3712:     }
 3713:     if (@noupdate) {
 3714: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
 3715: 	my $numcols=scalar(@partid)*4+2;
 3716: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 3717: 	    '<td align="center" colspan="'.$numcols.'">'.
 3718: 	    &mt('No Changes Occurred For the Students Below').
 3719: 	    '</td>'.
 3720: 	    &Apache::loncommon::end_data_table_row();
 3721: 	foreach my $line (@noupdate) {
 3722: 	    $result.=
 3723: 		&Apache::loncommon::start_data_table_row().
 3724: 		$line.
 3725: 		&Apache::loncommon::end_data_table_row();
 3726: 	}
 3727:     }
 3728:     $result .= &Apache::loncommon::end_data_table();
 3729:     my $msg = '<p><b>'.
 3730: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 3731: 	    $rec_update,$count).'</b><br />'.
 3732: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 3733: 	'</b></p>';
 3734:     return $title.$msg.$result;
 3735: }
 3736: 
 3737: sub split_part_type {
 3738:     my ($partstr) = @_;
 3739:     my ($temp,@allparts)=split(/_/,$partstr);
 3740:     my $type=pop(@allparts);
 3741:     my $part=join('_',@allparts);
 3742:     return ($part,$type);
 3743: }
 3744: 
 3745: #------------- end of section for handling grading by section/class ---------
 3746: #
 3747: #----------------------------------------------------------------------------
 3748: 
 3749: 
 3750: #----------------------------------------------------------------------------
 3751: #
 3752: #-------------------------- Next few routines handles grading by csv upload
 3753: #
 3754: #--- Javascript to handle csv upload
 3755: sub csvupload_javascript_reverse_associate {
 3756:     my $error1=&mt('You need to specify the username or the student/employee ID');
 3757:     my $error2=&mt('You need to specify at least one grading field');
 3758:   return(<<ENDPICK);
 3759:   function verify(vf) {
 3760:     var foundsomething=0;
 3761:     var founduname=0;
 3762:     var foundID=0;
 3763:     for (i=0;i<=vf.nfields.value;i++) {
 3764:       tw=eval('vf.f'+i+'.selectedIndex');
 3765:       if (i==0 && tw!=0) { foundID=1; }
 3766:       if (i==1 && tw!=0) { founduname=1; }
 3767:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 3768:     }
 3769:     if (founduname==0 && foundID==0) {
 3770: 	alert('$error1');
 3771: 	return;
 3772:     }
 3773:     if (foundsomething==0) {
 3774: 	alert('$error2');
 3775: 	return;
 3776:     }
 3777:     vf.submit();
 3778:   }
 3779:   function flip(vf,tf) {
 3780:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3781:     var i;
 3782:     for (i=0;i<=vf.nfields.value;i++) {
 3783:       //can not pick the same destination field for both name and domain
 3784:       if (((i ==0)||(i ==1)) && 
 3785:           ((tf==0)||(tf==1)) && 
 3786:           (i!=tf) &&
 3787:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3788:         eval('vf.f'+i+'.selectedIndex=0;')
 3789:       }
 3790:     }
 3791:   }
 3792: ENDPICK
 3793: }
 3794: 
 3795: sub csvupload_javascript_forward_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 (tw==1) { foundID=1; }
 3806:       if (tw==2) { founduname=1; }
 3807:       if (tw>3) { 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:     //can not pick the same destination field twice
 3823:     for (i=0;i<=vf.nfields.value;i++) {
 3824:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3825:         eval('vf.f'+i+'.selectedIndex=0;')
 3826:       }
 3827:     }
 3828:   }
 3829: ENDPICK
 3830: }
 3831: 
 3832: sub csvuploadmap_header {
 3833:     my ($request,$symb,$datatoken,$distotal)= @_;
 3834:     my $javascript;
 3835:     if ($env{'form.upfile_associate'} eq 'reverse') {
 3836: 	$javascript=&csvupload_javascript_reverse_associate();
 3837:     } else {
 3838: 	$javascript=&csvupload_javascript_forward_associate();
 3839:     }
 3840: 
 3841:     $symb = &Apache::lonenc::check_encrypt($symb);
 3842:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
 3843:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
 3844:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
 3845:     my $reverse=&mt("Reverse Association");
 3846:     $request->print(<<ENDPICK);
 3847: <br />
 3848: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 3849: <input type="hidden" name="associate"  value="" />
 3850: <input type="hidden" name="phase"      value="three" />
 3851: <input type="hidden" name="datatoken"  value="$datatoken" />
 3852: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 3853: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 3854: <input type="hidden" name="upfile_associate" 
 3855:                                        value="$env{'form.upfile_associate'}" />
 3856: <input type="hidden" name="symb"       value="$symb" />
 3857: <input type="hidden" name="command"    value="csvuploadoptions" />
 3858: <hr />
 3859: ENDPICK
 3860:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
 3861:     return '';
 3862: 
 3863: }
 3864: 
 3865: sub csvupload_fields {
 3866:     my ($symb,$errorref) = @_;
 3867:     my (@parts) = &getpartlist($symb,$errorref);
 3868:     if (ref($errorref)) {
 3869:         if ($$errorref) {
 3870:             return;
 3871:         }
 3872:     }
 3873: 
 3874:     my @fields=(['ID','Student/Employee ID'],
 3875: 		['username','Student Username'],
 3876: 		['domain','Student Domain']);
 3877:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3878:     foreach my $part (sort(@parts)) {
 3879: 	my @datum;
 3880: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3881: 	my $name=$part;
 3882: 	if  (!$display) { $display = $name; }
 3883: 	@datum=($name,$display);
 3884: 	if ($name=~/^stores_(.*)_awarded/) {
 3885: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 3886: 	}
 3887: 	push(@fields,\@datum);
 3888:     }
 3889:     return (@fields);
 3890: }
 3891: 
 3892: sub csvuploadmap_footer {
 3893:     my ($request,$i,$keyfields) =@_;
 3894:     $request->print(<<ENDPICK);
 3895: </table>
 3896: <input type="hidden" name="nfields" value="$i" />
 3897: <input type="hidden" name="keyfields" value="$keyfields" />
 3898: <input type="button" onclick="javascript:verify(this.form)" value="Assign Grades" /><br />
 3899: </form>
 3900: ENDPICK
 3901: }
 3902: 
 3903: sub checkforfile_js {
 3904:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 3905:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
 3906:     function checkUpload(formname) {
 3907: 	if (formname.upfile.value == "") {
 3908: 	    alert("$alertmsg");
 3909: 	    return false;
 3910: 	}
 3911: 	formname.submit();
 3912:     }
 3913: CSVFORMJS
 3914:     return $result;
 3915: }
 3916: 
 3917: sub upcsvScores_form {
 3918:     my ($request,$symb) = @_;
 3919:     if (!$symb) {return '';}
 3920:     my $result=&checkforfile_js();
 3921:     $result.=&Apache::loncommon::start_data_table().
 3922:              &Apache::loncommon::start_data_table_header_row().
 3923:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
 3924:              &Apache::loncommon::end_data_table_header_row().
 3925:              &Apache::loncommon::start_data_table_row().'<td>';
 3926:     my $upload=&mt("Upload Scores");
 3927:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 3928:     my $ignore=&mt('Ignore First Line');
 3929:     $symb = &Apache::lonenc::check_encrypt($symb);
 3930:     $result.=<<ENDUPFORM;
 3931: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3932: <input type="hidden" name="symb" value="$symb" />
 3933: <input type="hidden" name="command" value="csvuploadmap" />
 3934: $upfile_select
 3935: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 3936: </form>
 3937: ENDUPFORM
 3938:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 3939:                            &mt("How do I create a CSV file from a spreadsheet")).
 3940:              '</td>'.
 3941:             &Apache::loncommon::end_data_table_row().
 3942:             &Apache::loncommon::end_data_table();
 3943:     return $result;
 3944: }
 3945: 
 3946: 
 3947: sub csvuploadmap {
 3948:     my ($request,$symb)= @_;
 3949:     if (!$symb) {return '';}
 3950: 
 3951:     my $datatoken;
 3952:     if (!$env{'form.datatoken'}) {
 3953: 	$datatoken=&Apache::loncommon::upfile_store($request);
 3954:     } else {
 3955: 	$datatoken=$env{'form.datatoken'};
 3956: 	&Apache::loncommon::load_tmp_file($request);
 3957:     }
 3958:     my @records=&Apache::loncommon::upfile_record_sep();
 3959:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 3960:     my ($i,$keyfields);
 3961:     if (@records) {
 3962:         my $fieldserror;
 3963: 	my @fields=&csvupload_fields($symb,\$fieldserror);
 3964:         if ($fieldserror) {
 3965:             $request->print(&navmap_errormsg());
 3966:             return;
 3967:         }
 3968: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 3969: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 3970: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 3971: 							  \@fields);
 3972: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 3973: 	    chop($keyfields);
 3974: 	} else {
 3975: 	    unshift(@fields,['none','']);
 3976: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 3977: 							    \@fields);
 3978:             foreach my $rec (@records) {
 3979:                 my %temp = &Apache::loncommon::record_sep($rec);
 3980:                 if (%temp) {
 3981:                     $keyfields=join(',',sort(keys(%temp)));
 3982:                     last;
 3983:                 }
 3984:             }
 3985: 	}
 3986:     }
 3987:     &csvuploadmap_footer($request,$i,$keyfields);
 3988: 
 3989:     return '';
 3990: }
 3991: 
 3992: sub csvuploadoptions {
 3993:     my ($request,$symb)= @_;
 3994:     my $overwrite=&mt('Overwrite any existing score');
 3995:     $request->print(<<ENDPICK);
 3996: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3997: <input type="hidden" name="command"    value="csvuploadassign" />
 3998: <p>
 3999: <label>
 4000:    <input type="checkbox" name="overwite_scores" checked="checked" />
 4001:    $overwrite
 4002: </label>
 4003: </p>
 4004: ENDPICK
 4005:     my %fields=&get_fields();
 4006:     if (!defined($fields{'domain'})) {
 4007: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 4008: 	$request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
 4009:     }
 4010:     foreach my $key (sort(keys(%env))) {
 4011: 	if ($key !~ /^form\.(.*)$/) { next; }
 4012: 	my $cleankey=$1;
 4013: 	if ($cleankey eq 'command') { next; }
 4014: 	$request->print('<input type="hidden" name="'.$cleankey.
 4015: 			'"  value="'.$env{$key}.'" />'."\n");
 4016:     }
 4017:     # FIXME do a check for any duplicated user ids...
 4018:     # FIXME do a check for any invalid user ids?...
 4019:     $request->print('<input type="submit" value="Assign Grades" /><br />
 4020: <hr /></form>'."\n");
 4021:     return '';
 4022: }
 4023: 
 4024: sub get_fields {
 4025:     my %fields;
 4026:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 4027:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 4028: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 4029: 	    if ($env{'form.f'.$i} ne 'none') {
 4030: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 4031: 	    }
 4032: 	} else {
 4033: 	    if ($env{'form.f'.$i} ne 'none') {
 4034: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 4035: 	    }
 4036: 	}
 4037:     }
 4038:     return %fields;
 4039: }
 4040: 
 4041: sub csvuploadassign {
 4042:     my ($request,$symb)= @_;
 4043:     if (!$symb) {return '';}
 4044:     my $error_msg = '';
 4045:     &Apache::loncommon::load_tmp_file($request);
 4046:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 4047:     my %fields=&get_fields();
 4048:     my $courseid=$env{'request.course.id'};
 4049:     my ($classlist) = &getclasslist('all',0);
 4050:     my @notallowed;
 4051:     my @skipped;
 4052:     my $countdone=0;
 4053:     foreach my $grade (@gradedata) {
 4054: 	my %entries=&Apache::loncommon::record_sep($grade);
 4055: 	my $domain;
 4056: 	if ($entries{$fields{'domain'}}) {
 4057: 	    $domain=$entries{$fields{'domain'}};
 4058: 	} else {
 4059: 	    $domain=$env{'form.default_domain'};
 4060: 	}
 4061: 	$domain=~s/\s//g;
 4062: 	my $username=$entries{$fields{'username'}};
 4063: 	$username=~s/\s//g;
 4064: 	if (!$username) {
 4065: 	    my $id=$entries{$fields{'ID'}};
 4066: 	    $id=~s/\s//g;
 4067: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 4068: 	    $username=$ids{$id};
 4069: 	}
 4070: 	if (!exists($$classlist{"$username:$domain"})) {
 4071: 	    my $id=$entries{$fields{'ID'}};
 4072: 	    $id=~s/\s//g;
 4073: 	    if ($id) {
 4074: 		push(@skipped,"$id:$domain");
 4075: 	    } else {
 4076: 		push(@skipped,"$username:$domain");
 4077: 	    }
 4078: 	    next;
 4079: 	}
 4080: 	my $usec=$classlist->{"$username:$domain"}[5];
 4081: 	if (!&canmodify($usec)) {
 4082: 	    push(@notallowed,"$username:$domain");
 4083: 	    next;
 4084: 	}
 4085: 	my %points;
 4086: 	my %grades;
 4087: 	foreach my $dest (keys(%fields)) {
 4088: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 4089: 		$dest eq 'domain') { next; }
 4090: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 4091: 	    if ($dest=~/stores_(.*)_points/) {
 4092: 		my $part=$1;
 4093: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 4094: 					      $symb,$domain,$username);
 4095:                 if ($wgt) {
 4096:                     $entries{$fields{$dest}}=~s/\s//g;
 4097:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 4098:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 4099:                                           : 'correct_by_override';
 4100:                     if ($pcr>1) {
 4101:                        push(@skipped,&mt("[_1]: point value larger than weight","$username:$domain"));
 4102:                     }
 4103:                     $grades{"resource.$part.awarded"}=$pcr;
 4104:                     $grades{"resource.$part.solved"}=$award;
 4105:                     $points{$part}=1;
 4106:                 } else {
 4107:                     $error_msg = "<br />" .
 4108:                         &mt("Some point values were assigned"
 4109:                             ." for problems with a weight "
 4110:                             ."of zero. These values were "
 4111:                             ."ignored.");
 4112:                 }
 4113: 	    } else {
 4114: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 4115: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 4116: 		my $store_key=$dest;
 4117: 		$store_key=~s/^stores/resource/;
 4118: 		$store_key=~s/_/\./g;
 4119: 		$grades{$store_key}=$entries{$fields{$dest}};
 4120: 	    }
 4121: 	}
 4122: 	if (! %grades) { 
 4123:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 4124:         } else {
 4125: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 4126: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 4127: 					   $env{'request.course.id'},
 4128: 					   $domain,$username);
 4129: 	   if ($result eq 'ok') {
 4130: # Successfully stored
 4131: 	      $request->print('.');
 4132: # Remove from grading queue
 4133:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
 4134:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
 4135:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
 4136:                                              $domain,$username);
 4137:               $countdone++;
 4138:            } else {
 4139: 	      $request->print("<p><span class=\"LC_error\">".
 4140:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 4141:                                   "$username:$domain",$result)."</span></p>");
 4142: 	   }
 4143: 	   $request->rflush();
 4144:         }
 4145:     }
 4146:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
 4147:     if (@skipped) {
 4148: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
 4149:         $request->print(join(', ',@skipped));
 4150:     }
 4151:     if (@notallowed) {
 4152: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
 4153: 	$request->print(join(', ',@notallowed));
 4154:     }
 4155:     $request->print("<br />\n");
 4156:     return $error_msg;
 4157: }
 4158: #------------- end of section for handling csv file upload ---------
 4159: #
 4160: #-------------------------------------------------------------------
 4161: #
 4162: #-------------- Next few routines handle grading by page/sequence
 4163: #
 4164: #--- Select a page/sequence and a student to grade
 4165: sub pickStudentPage {
 4166:     my ($request,$symb) = @_;
 4167: 
 4168:     my $alertmsg = &mt('Please select the student you wish to grade.');
 4169:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
 4170: 
 4171: function checkPickOne(formname) {
 4172:     if (radioSelection(formname.student) == null) {
 4173: 	alert("$alertmsg");
 4174: 	return;
 4175:     }
 4176:     ptr = pullDownSelection(formname.selectpage);
 4177:     formname.page.value = formname["page"+ptr].value;
 4178:     formname.title.value = formname["title"+ptr].value;
 4179:     formname.submit();
 4180: }
 4181: 
 4182: LISTJAVASCRIPT
 4183:     &commonJSfunctions($request);
 4184: 
 4185:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4186:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4187:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4188: 
 4189:     my $result='<h3><span class="LC_info">&nbsp;'.
 4190: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 4191: 
 4192:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 4193:     my $map_error;
 4194:     my ($titles,$symbx) = &getSymbMap($map_error);
 4195:     if ($map_error) {
 4196:         $request->print(&navmap_errormsg());
 4197:         return; 
 4198:     }
 4199:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 4200: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 4201: #    my $type=($curpage =~ /\.(page|sequence)/);
 4202:     my $select = '<select name="selectpage">'."\n";
 4203:     my $ctr=0;
 4204:     foreach (@$titles) {
 4205: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4206: 	$select.='<option value="'.$ctr.'" '.
 4207: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4208: 	    '>'.$showtitle.'</option>'."\n";
 4209: 	$ctr++;
 4210:     }
 4211:     $select.= '</select>';
 4212:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
 4213: 
 4214:     $ctr=0;
 4215:     foreach (@$titles) {
 4216: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4217: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 4218: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 4219: 	$ctr++;
 4220:     }
 4221:     $result.='<input type="hidden" name="page" />'."\n".
 4222: 	'<input type="hidden" name="title" />'."\n";
 4223: 
 4224:     my $options =
 4225: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
 4226: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
 4227:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
 4228: 
 4229:     $options =
 4230: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
 4231: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
 4232: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
 4233:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
 4234:     
 4235:     $result.=&build_section_inputs();
 4236:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4237:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 4238: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 4239: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."<br />\n";
 4240: 
 4241:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
 4242: 
 4243:     $result.='&nbsp;<input type="button" '.
 4244:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 4245: 
 4246:     $request->print($result);
 4247: 
 4248:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 4249: 	&Apache::loncommon::start_data_table().
 4250: 	&Apache::loncommon::start_data_table_header_row().
 4251: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4252: 	'<th>'.&nameUserString('header').'</th>'.
 4253: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4254: 	'<th>'.&nameUserString('header').'</th>'.
 4255: 	&Apache::loncommon::end_data_table_header_row();
 4256:  
 4257:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 4258:     my $ptr = 1;
 4259:     foreach my $student (sort 
 4260: 			 {
 4261: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4262: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4263: 			     }
 4264: 			     return $a cmp $b;
 4265: 			 } (keys(%$fullname))) {
 4266: 	my ($uname,$udom) = split(/:/,$student);
 4267: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 4268:                                   : '</td>');
 4269: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 4270: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 4271: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 4272: 	$studentTable.=
 4273: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 4274:                          : '');
 4275: 	$ptr++;
 4276:     }
 4277:     if ($ptr%2 == 0) {
 4278: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 4279: 	    &Apache::loncommon::end_data_table_row();
 4280:     }
 4281:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 4282:     $studentTable.='<input type="button" '.
 4283:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 4284: 
 4285:     $request->print($studentTable);
 4286: 
 4287:     return '';
 4288: }
 4289: 
 4290: sub getSymbMap {
 4291:     my ($map_error) = @_;
 4292:     my $navmap = Apache::lonnavmaps::navmap->new();
 4293:     unless (ref($navmap)) {
 4294:         if (ref($map_error)) {
 4295:             $$map_error = 'navmap';
 4296:         }
 4297:         return;
 4298:     }
 4299:     my %symbx = ();
 4300:     my @titles = ();
 4301:     my $minder = 0;
 4302: 
 4303:     # Gather every sequence that has problems.
 4304:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 4305: 					       1,0,1);
 4306:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 4307: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 4308: 	    my $title = $minder.'.'.
 4309: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 4310: 	    push(@titles, $title); # minder in case two titles are identical
 4311: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 4312: 	    $minder++;
 4313: 	}
 4314:     }
 4315:     return \@titles,\%symbx;
 4316: }
 4317: 
 4318: #
 4319: #--- Displays a page/sequence w/wo problems, w/wo submissions
 4320: sub displayPage {
 4321:     my ($request,$symb) = @_;
 4322:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4323:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4324:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4325:     my $pageTitle = $env{'form.page'};
 4326:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4327:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4328:     my $usec=$classlist->{$env{'form.student'}}[5];
 4329: 
 4330:     #need to make sure we have the correct data for later EXT calls, 
 4331:     #thus invalidate the cache
 4332:     &Apache::lonnet::devalidatecourseresdata(
 4333:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 4334:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 4335:     &Apache::lonnet::clear_EXT_cache_status();
 4336: 
 4337:     if (!&canview($usec)) {
 4338: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
 4339: 	return;
 4340:     }
 4341:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4342:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 4343: 	'</h3>'."\n";
 4344:     $env{'form.CODE'} = uc($env{'form.CODE'});
 4345:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 4346: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 4347:     } else {
 4348: 	delete($env{'form.CODE'});
 4349:     }
 4350:     &sub_page_js($request);
 4351:     $request->print($result);
 4352: 
 4353:     my $navmap = Apache::lonnavmaps::navmap->new();
 4354:     unless (ref($navmap)) {
 4355:         $request->print(&navmap_errormsg());
 4356:         return;
 4357:     }
 4358:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 4359:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4360:     if (!$map) {
 4361: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 4362: 	return; 
 4363:     }
 4364:     my $iterator = $navmap->getIterator($map->map_start(),
 4365: 					$map->map_finish());
 4366: 
 4367:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 4368: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 4369: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 4370: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 4371: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 4372: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 4373: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4374: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
 4375: 
 4376:     if (defined($env{'form.CODE'})) {
 4377: 	$studentTable.=
 4378: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 4379:     }
 4380:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 4381: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 4382: 
 4383:     $studentTable.='&nbsp;<span class="LC_info">'.
 4384:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
 4385:         '</span>'."\n".
 4386: 	&Apache::loncommon::start_data_table().
 4387: 	&Apache::loncommon::start_data_table_header_row().
 4388: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
 4389: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 4390: 	&Apache::loncommon::end_data_table_header_row();
 4391: 
 4392:     &Apache::lonxml::clear_problem_counter();
 4393:     my ($depth,$question,$prob) = (1,1,1);
 4394:     $iterator->next(); # skip the first BEGIN_MAP
 4395:     my $curRes = $iterator->next(); # for "current resource"
 4396:     while ($depth > 0) {
 4397:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4398:         if($curRes == $iterator->END_MAP) { $depth--; }
 4399: 
 4400:         if (ref($curRes) && $curRes->is_problem()) {
 4401: 	    my $parts = $curRes->parts();
 4402:             my $title = $curRes->compTitle();
 4403: 	    my $symbx = $curRes->symb();
 4404: 	    $studentTable.=
 4405: 		&Apache::loncommon::start_data_table_row().
 4406: 		'<td align="center" valign="top" >'.$prob.
 4407: 		(scalar(@{$parts}) == 1 ? '' 
 4408: 		                        : '<br />('.&mt('[_1]parts)',
 4409: 							scalar(@{$parts}).'&nbsp;')
 4410: 		 ).
 4411: 		 '</td>';
 4412: 	    $studentTable.='<td valign="top">';
 4413: 	    my %form = ('CODE' => $env{'form.CODE'},);
 4414: 	    if ($env{'form.vProb'} eq 'yes' ) {
 4415: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 4416: 					     undef,'both',\%form);
 4417: 	    } else {
 4418: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 4419: 		$companswer =~ s|<form(.*?)>||g;
 4420: 		$companswer =~ s|</form>||g;
 4421: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 4422: #		    $companswer =~ s/$1/ /ms;
 4423: #		    $request->print('match='.$1."<br />\n");
 4424: #		}
 4425: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 4426: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 4427: 	    }
 4428: 
 4429: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 4430: 
 4431: 	    if ($env{'form.lastSub'} eq 'datesub') {
 4432: 		if ($record{'version'} eq '') {
 4433: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
 4434: 		} else {
 4435: 		    my %responseType = ();
 4436: 		    foreach my $partid (@{$parts}) {
 4437: 			my @responseIds =$curRes->responseIds($partid);
 4438: 			my @responseType =$curRes->responseType($partid);
 4439: 			my %responseIds;
 4440: 			for (my $i=0;$i<=$#responseIds;$i++) {
 4441: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 4442: 			}
 4443: 			$responseType{$partid} = \%responseIds;
 4444: 		    }
 4445: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 4446: 
 4447: 		}
 4448: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 4449: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 4450: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 4451: 									$env{'request.course.id'},
 4452: 									'','.submission');
 4453:  
 4454: 	    }
 4455: 	    if (&canmodify($usec)) {
 4456:             $studentTable.=&gradeBox_start();
 4457: 		foreach my $partid (@{$parts}) {
 4458: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 4459: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 4460: 		    $question++;
 4461: 		}
 4462:             $studentTable.=&gradeBox_end();
 4463: 		$prob++;
 4464: 	    }
 4465: 	    $studentTable.='</td></tr>';
 4466: 
 4467: 	}
 4468:         $curRes = $iterator->next();
 4469:     }
 4470: 
 4471:     $studentTable.=
 4472:         '</table>'."\n".
 4473:         '<input type="button" value="'.&mt('Save').'" '.
 4474:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 4475:         '</form>'."\n";
 4476:     $request->print($studentTable);
 4477: 
 4478:     return '';
 4479: }
 4480: 
 4481: sub displaySubByDates {
 4482:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 4483:     my $isCODE=0;
 4484:     my $isTask = ($symb =~/\.task$/);
 4485:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 4486:     my $studentTable=&Apache::loncommon::start_data_table().
 4487: 	&Apache::loncommon::start_data_table_header_row().
 4488: 	'<th>'.&mt('Date/Time').'</th>'.
 4489: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 4490: 	'<th>'.&mt('Submission').'</th>'.
 4491: 	'<th>'.&mt('Status').'</th>'.
 4492: 	&Apache::loncommon::end_data_table_header_row();
 4493:     my ($version);
 4494:     my %mark;
 4495:     my %orders;
 4496:     $mark{'correct_by_student'} = $checkIcon;
 4497:     if (!exists($$record{'1:timestamp'})) {
 4498: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 4499:     }
 4500: 
 4501:     my $interaction;
 4502:     my $no_increment = 1;
 4503:     my %lastrndseed;
 4504:     for ($version=1;$version<=$$record{'version'};$version++) {
 4505: 	my $timestamp = 
 4506: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 4507: 	if (exists($$record{$version.':resource.0.version'})) {
 4508: 	    $interaction = $$record{$version.':resource.0.version'};
 4509: 	}
 4510: 
 4511: 	my $where = ($isTask ? "$version:resource.$interaction"
 4512: 		             : "$version:resource");
 4513: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 4514: 	    '<td>'.$timestamp.'</td>';
 4515: 	if ($isCODE) {
 4516: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 4517: 	}
 4518: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 4519: 	my @displaySub = ();
 4520: 	foreach my $partid (@{$parts}) {
 4521:             my ($hidden,$type);
 4522:             $type = $$record{$version.':resource.'.$partid.'.type'};
 4523:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
 4524:                 $hidden = 1;
 4525:             }
 4526: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
 4527: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 4528: 	    
 4529: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 4530: 	    my $display_part=&get_display_part($partid,$symb);
 4531: 	    foreach my $matchKey (@matchKey) {
 4532: 		if (exists($$record{$version.':'.$matchKey}) &&
 4533: 		    $$record{$version.':'.$matchKey} ne '') {
 4534:                     
 4535: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 4536: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 4537:                     $displaySub[0].='<span class="LC_nobreak"';
 4538:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
 4539:                                    .' <span class="LC_internal_info">'
 4540:                                    .'('.&mt('Response ID: [_1]',$responseId).')'
 4541:                                    .'</span>'
 4542:                                    .' <b>';
 4543:                     if ($hidden) {
 4544:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
 4545:                     } else {
 4546:                         my ($trial,$rndseed,$newvariation);
 4547:                         if ($type eq 'randomizetry') {
 4548:                             $trial = $$record{"$where.$partid.tries"};
 4549:                             $rndseed = $$record{"$where.$partid.rndseed"};
 4550:                         }
 4551: 		        if ($$record{"$where.$partid.tries"} eq '') {
 4552: 			    $displaySub[0].=&mt('Trial not counted');
 4553: 		        } else {
 4554: 			    $displaySub[0].=&mt('Trial: [_1]',
 4555: 					    $$record{"$where.$partid.tries"});
 4556:                             if ($rndseed || $lastrndseed{$partid}) {
 4557:                                 if ($rndseed ne $lastrndseed{$partid}) {
 4558:                                     $newvariation = '&nbsp;('.&mt('New variation this try').')';
 4559:                                 }
 4560:                             }
 4561:                             $lastrndseed{$partid} = $rndseed;
 4562: 		        }
 4563: 		        my $responseType=($isTask ? 'Task'
 4564:                                               : $responseType->{$partid}->{$responseId});
 4565: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
 4566: 		        if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
 4567: 			    $orders{$partid}->{$responseId}=
 4568: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
 4569:                                            $no_increment,$type,$trial,$rndseed);
 4570: 		        }
 4571: 		        $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
 4572: 		        $displaySub[0].='&nbsp; '.
 4573: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
 4574:                     }
 4575: 		}
 4576: 	    }
 4577: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 4578: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 4579: 				    $$record{"$where.$partid.checkedin"},
 4580: 				    $$record{"$where.$partid.checkedin.slot"}).
 4581: 					'<br />';
 4582: 	    }
 4583: 	    if (exists $$record{"$where.$partid.award"}) {
 4584: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 4585: 		    lc($$record{"$where.$partid.award"}).' '.
 4586: 		    $mark{$$record{"$where.$partid.solved"}}.
 4587: 		    '<br />';
 4588: 	    }
 4589: 	    if (exists $$record{"$where.$partid.regrader"}) {
 4590: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 4591: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4592: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 4593: 		$displaySub[2].=
 4594: 		    $$record{"$version:resource.$partid.regrader"}.
 4595: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4596: 	    }
 4597: 	}
 4598: 	# needed because old essay regrader has not parts info
 4599: 	if (exists $$record{"$version:resource.regrader"}) {
 4600: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 4601: 	}
 4602: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 4603: 	if ($displaySub[2]) {
 4604: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 4605: 	}
 4606: 	$studentTable.='&nbsp;</td>'.
 4607: 	    &Apache::loncommon::end_data_table_row();
 4608:     }
 4609:     $studentTable.=&Apache::loncommon::end_data_table();
 4610:     return $studentTable;
 4611: }
 4612: 
 4613: sub updateGradeByPage {
 4614:     my ($request,$symb) = @_;
 4615: 
 4616:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4617:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4618:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4619:     my $pageTitle = $env{'form.page'};
 4620:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4621:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4622:     my $usec=$classlist->{$env{'form.student'}}[5];
 4623:     if (!&canmodify($usec)) {
 4624: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 4625: 	return;
 4626:     }
 4627:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4628:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 4629: 	'</h3>'."\n";
 4630: 
 4631:     $request->print($result);
 4632: 
 4633: 
 4634:     my $navmap = Apache::lonnavmaps::navmap->new();
 4635:     unless (ref($navmap)) {
 4636:         $request->print(&navmap_errormsg());
 4637:         return;
 4638:     }
 4639:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 4640:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4641:     if (!$map) {
 4642: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 4643: 	return; 
 4644:     }
 4645:     my $iterator = $navmap->getIterator($map->map_start(),
 4646: 					$map->map_finish());
 4647: 
 4648:     my $studentTable=
 4649: 	&Apache::loncommon::start_data_table().
 4650: 	&Apache::loncommon::start_data_table_header_row().
 4651: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 4652: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 4653: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 4654: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 4655: 	&Apache::loncommon::end_data_table_header_row();
 4656: 
 4657:     $iterator->next(); # skip the first BEGIN_MAP
 4658:     my $curRes = $iterator->next(); # for "current resource"
 4659:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
 4660:     while ($depth > 0) {
 4661:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4662:         if($curRes == $iterator->END_MAP) { $depth--; }
 4663: 
 4664:         if (ref($curRes) && $curRes->is_problem()) {
 4665: 	    my $parts = $curRes->parts();
 4666:             my $title = $curRes->compTitle();
 4667: 	    my $symbx = $curRes->symb();
 4668: 	    $studentTable.=
 4669: 		&Apache::loncommon::start_data_table_row().
 4670: 		'<td align="center" valign="top" >'.$prob.
 4671: 		(scalar(@{$parts}) == 1 ? '' 
 4672:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
 4673: 		.')').'</td>';
 4674: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 4675: 
 4676: 	    my %newrecord=();
 4677: 	    my @displayPts=();
 4678:             my %aggregate = ();
 4679:             my $aggregateflag = 0;
 4680: 	    foreach my $partid (@{$parts}) {
 4681: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 4682: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 4683: 
 4684: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 4685: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 4686: 		my $partial = $newpts/$wgt;
 4687: 		my $score;
 4688: 		if ($partial > 0) {
 4689: 		    $score = 'correct_by_override';
 4690: 		} elsif ($newpts ne '') { #empty is taken as 0
 4691: 		    $score = 'incorrect_by_override';
 4692: 		}
 4693: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 4694: 		if ($dropMenu eq 'excused') {
 4695: 		    $partial = '';
 4696: 		    $score = 'excused';
 4697: 		} elsif ($dropMenu eq 'reset status'
 4698: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 4699: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 4700: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 4701: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 4702: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 4703: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 4704: 		    $changeflag++;
 4705: 		    $newpts = '';
 4706:                     
 4707:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 4708:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 4709:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 4710:                     if ($aggtries > 0) {
 4711:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4712:                         $aggregateflag = 1;
 4713:                     }
 4714: 		}
 4715: 		my $display_part=&get_display_part($partid,$curRes->symb());
 4716: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 4717: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4718: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 4719: 		    '&nbsp;<br />';
 4720: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4721: 		     (($score eq 'excused') ? 'excused' : $newpts).
 4722: 		    '&nbsp;<br />';
 4723: 		$question++;
 4724: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 4725: 
 4726: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 4727: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 4728: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 4729: 		    if (scalar(keys(%newrecord)) > 0);
 4730: 
 4731: 		$changeflag++;
 4732: 	    }
 4733: 	    if (scalar(keys(%newrecord)) > 0) {
 4734: 		my %record = 
 4735: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 4736: 					     $udom,$uname);
 4737: 
 4738: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 4739: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 4740: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 4741: 		    $newrecord{'resource.CODE'} = '';
 4742: 		}
 4743: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 4744: 					$udom,$uname);
 4745: 		%record = &Apache::lonnet::restore($symbx,
 4746: 						   $env{'request.course.id'},
 4747: 						   $udom,$uname);
 4748: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 4749: 					     $cdom,$cnum,$udom,$uname);
 4750: 	    }
 4751: 	    
 4752:             if ($aggregateflag) {
 4753:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4754:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 4755:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 4756:             }
 4757: 
 4758: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 4759: 		'<td valign="top">'.$displayPts[1].'</td>'.
 4760: 		&Apache::loncommon::end_data_table_row();
 4761: 
 4762: 	    $prob++;
 4763: 	}
 4764:         $curRes = $iterator->next();
 4765:     }
 4766: 
 4767:     $studentTable.=&Apache::loncommon::end_data_table();
 4768:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 4769: 		  &mt('The scores were changed for [quant,_1,problem].',
 4770: 		  $changeflag));
 4771:     $request->print($grademsg.$studentTable);
 4772: 
 4773:     return '';
 4774: }
 4775: 
 4776: #-------- end of section for handling grading by page/sequence ---------
 4777: #
 4778: #-------------------------------------------------------------------
 4779: 
 4780: #-------------------- Bubblesheet (Scantron) Grading -------------------
 4781: #
 4782: #------ start of section for handling grading by page/sequence ---------
 4783: 
 4784: =pod
 4785: 
 4786: =head1 Bubble sheet grading routines
 4787: 
 4788:   For this documentation:
 4789: 
 4790:    'scanline' refers to the full line of characters
 4791:    from the file that we are parsing that represents one entire sheet
 4792: 
 4793:    'bubble line' refers to the data
 4794:    representing the line of bubbles that are on the physical bubble sheet
 4795: 
 4796: 
 4797: The overall process is that a scanned in bubble sheet data is uploaded
 4798: into a course. When a user wants to grade, they select a
 4799: sequence/folder of resources, a file of bubble sheet info, and pick
 4800: one of the predefined configurations for what each scanline looks
 4801: like.
 4802: 
 4803: Next each scanline is checked for any errors of either 'missing
 4804: bubbles' (it's an error because it may have been mis-scanned
 4805: because too light bubbling), 'double bubble' (each bubble line should
 4806: have no more that one letter picked), invalid or duplicated CODE,
 4807: invalid student/employee ID
 4808: 
 4809: If the CODE option is used that determines the randomization of the
 4810: homework problems, either way the student/employee ID is looked up into a
 4811: username:domain.
 4812: 
 4813: During the validation phase the instructor can choose to skip scanlines. 
 4814: 
 4815: After the validation phase, there are now 3 bubble sheet files
 4816: 
 4817:   scantron_original_filename (unmodified original file)
 4818:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 4819:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 4820: 
 4821: Also there is a separate hash nohist_scantrondata that contains extra
 4822: correction information that isn't representable in the bubble sheet
 4823: file (see &scantron_getfile() for more information)
 4824: 
 4825: After all scanlines are either valid, marked as valid or skipped, then
 4826: foreach line foreach problem in the picked sequence, an ssi request is
 4827: made that simulates a user submitting their selected letter(s) against
 4828: the homework problem.
 4829: 
 4830: =over 4
 4831: 
 4832: 
 4833: 
 4834: =item defaultFormData
 4835: 
 4836:   Returns html hidden inputs used to hold context/default values.
 4837: 
 4838:  Arguments:
 4839:   $symb - $symb of the current resource 
 4840: 
 4841: =cut
 4842: 
 4843: sub defaultFormData {
 4844:     my ($symb)=@_;
 4845:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />';
 4846: }
 4847: 
 4848: 
 4849: =pod 
 4850: 
 4851: =item getSequenceDropDown
 4852: 
 4853:    Return html dropdown of possible sequences to grade
 4854:  
 4855:  Arguments:
 4856:    $symb - $symb of the current resource
 4857:    $map_error - ref to scalar which will container error if
 4858:                 $navmap object is unavailable in &getSymbMap().
 4859: 
 4860: =cut
 4861: 
 4862: sub getSequenceDropDown {
 4863:     my ($symb,$map_error)=@_;
 4864:     my $result='<select name="selectpage">'."\n";
 4865:     my ($titles,$symbx) = &getSymbMap($map_error);
 4866:     if (ref($map_error)) {
 4867:         return if ($$map_error);
 4868:     }
 4869:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 4870:     my $ctr=0;
 4871:     foreach (@$titles) {
 4872: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4873: 	$result.='<option value="'.$$symbx{$_}.'" '.
 4874: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4875: 	    '>'.$showtitle.'</option>'."\n";
 4876: 	$ctr++;
 4877:     }
 4878:     $result.= '</select>';
 4879:     return $result;
 4880: }
 4881: 
 4882: my %bubble_lines_per_response;     # no. bubble lines for each response.
 4883:                                    # key is zero-based index - 0, 1, 2 ...
 4884: 
 4885: my %first_bubble_line;             # First bubble line no. for each bubble.
 4886: 
 4887: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 4888:                                    # matchresponse or rankresponse, where 
 4889:                                    # an individual response can have multiple 
 4890:                                    # lines
 4891: 
 4892: my %responsetype_per_response;     # responsetype for each response
 4893: 
 4894: # Save and restore the bubble lines array to the form env.
 4895: 
 4896: 
 4897: sub save_bubble_lines {
 4898:     foreach my $line (keys(%bubble_lines_per_response)) {
 4899: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 4900: 	$env{"form.scantron.first_bubble_line.$line"} =
 4901: 	    $first_bubble_line{$line};
 4902:         $env{"form.scantron.sub_bubblelines.$line"} = 
 4903:             $subdivided_bubble_lines{$line};
 4904:         $env{"form.scantron.responsetype.$line"} =
 4905:             $responsetype_per_response{$line};
 4906:     }
 4907: }
 4908: 
 4909: 
 4910: sub restore_bubble_lines {
 4911:     my $line = 0;
 4912:     %bubble_lines_per_response = ();
 4913:     while ($env{"form.scantron.bubblelines.$line"}) {
 4914: 	my $value = $env{"form.scantron.bubblelines.$line"};
 4915: 	$bubble_lines_per_response{$line} = $value;
 4916: 	$first_bubble_line{$line}  =
 4917: 	    $env{"form.scantron.first_bubble_line.$line"};
 4918:         $subdivided_bubble_lines{$line} =
 4919:             $env{"form.scantron.sub_bubblelines.$line"};
 4920:         $responsetype_per_response{$line} =
 4921:             $env{"form.scantron.responsetype.$line"};
 4922: 	$line++;
 4923:     }
 4924: }
 4925: 
 4926: #  Given the parsed scanline, get the response for 
 4927: #  'answer' number n:
 4928: 
 4929: sub get_response_bubbles {
 4930:     my ($parsed_line, $response)  = @_;
 4931: 
 4932:     my $bubble_line = $first_bubble_line{$response-1} +1;
 4933:     my $bubble_lines= $bubble_lines_per_response{$response-1};
 4934:     
 4935:     my $selected = "";
 4936: 
 4937:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
 4938: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
 4939: 	$bubble_line++;
 4940:     }
 4941:     return $selected;
 4942: }
 4943: 
 4944: =pod 
 4945: 
 4946: =item scantron_filenames
 4947: 
 4948:    Returns a list of the scantron files in the current course 
 4949: 
 4950: =cut
 4951: 
 4952: sub scantron_filenames {
 4953:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4954:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4955:     my $getpropath = 1;
 4956:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
 4957:                                        $getpropath);
 4958:     my @possiblenames;
 4959:     foreach my $filename (sort(@files)) {
 4960: 	($filename)=split(/&/,$filename);
 4961: 	if ($filename!~/^scantron_orig_/) { next ; }
 4962: 	$filename=~s/^scantron_orig_//;
 4963: 	push(@possiblenames,$filename);
 4964:     }
 4965:     return @possiblenames;
 4966: }
 4967: 
 4968: =pod 
 4969: 
 4970: =item scantron_uploads
 4971: 
 4972:    Returns  html drop-down list of scantron files in current course.
 4973: 
 4974:  Arguments:
 4975:    $file2grade - filename to set as selected in the dropdown
 4976: 
 4977: =cut
 4978: 
 4979: sub scantron_uploads {
 4980:     my ($file2grade) = @_;
 4981:     my $result=	'<select name="scantron_selectfile">';
 4982:     $result.="<option></option>";
 4983:     foreach my $filename (sort(&scantron_filenames())) {
 4984: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 4985:     }
 4986:     $result.="</select>";
 4987:     return $result;
 4988: }
 4989: 
 4990: =pod 
 4991: 
 4992: =item scantron_scantab
 4993: 
 4994:   Returns html drop down of the scantron formats in the scantronformat.tab
 4995:   file.
 4996: 
 4997: =cut
 4998: 
 4999: sub scantron_scantab {
 5000:     my $result='<select name="scantron_format">'."\n";
 5001:     $result.='<option></option>'."\n";
 5002:     my @lines = &get_scantronformat_file();
 5003:     if (@lines > 0) {
 5004:         foreach my $line (@lines) {
 5005:             next if (($line =~ /^\#/) || ($line eq ''));
 5006: 	    my ($name,$descrip)=split(/:/,$line);
 5007: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 5008:         }
 5009:     }
 5010:     $result.='</select>'."\n";
 5011:     return $result;
 5012: }
 5013: 
 5014: =pod
 5015: 
 5016: =item get_scantronformat_file
 5017: 
 5018:   Returns an array containing lines from the scantron format file for
 5019:   the domain of the course.
 5020: 
 5021:   If a url for a custom.tab file is listed in domain's configuration.db, 
 5022:   lines are from this file.
 5023: 
 5024:   Otherwise, if a default.tab has been published in RES space by the 
 5025:   domainconfig user, lines are from this file.
 5026: 
 5027:   Otherwise, fall back to getting lines from the legacy file on the
 5028:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
 5029: 
 5030: =cut
 5031: 
 5032: sub get_scantronformat_file {
 5033:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5034:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
 5035:     my $gottab = 0;
 5036:     my @lines;
 5037:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 5038:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 5039:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 5040:             if ($formatfile ne '-1') {
 5041:                 @lines = split("\n",$formatfile,-1);
 5042:                 $gottab = 1;
 5043:             }
 5044:         }
 5045:     }
 5046:     if (!$gottab) {
 5047:         my $confname = $cdom.'-domainconfig';
 5048:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 5049:         my $formatfile =  &Apache::lonnet::getfile($default);
 5050:         if ($formatfile ne '-1') {
 5051:             @lines = split("\n",$formatfile,-1);
 5052:             $gottab = 1;
 5053:         }
 5054:     }
 5055:     if (!$gottab) {
 5056:         my @domains = &Apache::lonnet::current_machine_domains();
 5057:         if (grep(/^\Q$cdom\E$/,@domains)) {
 5058:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 5059:             @lines = <$fh>;
 5060:             close($fh);
 5061:         } else {
 5062:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
 5063:             @lines = <$fh>;
 5064:             close($fh);
 5065:         }
 5066:     }
 5067:     return @lines;
 5068: }
 5069: 
 5070: =pod 
 5071: 
 5072: =item scantron_CODElist
 5073: 
 5074:   Returns html drop down of the saved CODE lists from current course,
 5075:   generated from earlier printings.
 5076: 
 5077: =cut
 5078: 
 5079: sub scantron_CODElist {
 5080:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5081:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5082:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 5083:     my $namechoice='<option></option>';
 5084:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 5085: 	if ($name =~ /^error: 2 /) { next; }
 5086: 	if ($name =~ /^type\0/) { next; }
 5087: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 5088:     }
 5089:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 5090:     return $namechoice;
 5091: }
 5092: 
 5093: =pod 
 5094: 
 5095: =item scantron_CODEunique
 5096: 
 5097:   Returns the html for "Each CODE to be used once" radio.
 5098: 
 5099: =cut
 5100: 
 5101: sub scantron_CODEunique {
 5102:     my $result='<span class="LC_nobreak">
 5103:                  <label><input type="radio" name="scantron_CODEunique"
 5104:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 5105:                 </span>
 5106:                 <span class="LC_nobreak">
 5107:                  <label><input type="radio" name="scantron_CODEunique"
 5108:                         value="no" />'.&mt('No').' </label>
 5109:                 </span>';
 5110:     return $result;
 5111: }
 5112: 
 5113: =pod 
 5114: 
 5115: =item scantron_selectphase
 5116: 
 5117:   Generates the initial screen to start the bubble sheet process.
 5118:   Allows for - starting a grading run.
 5119:              - downloading existing scan data (original, corrected
 5120:                                                 or skipped info)
 5121: 
 5122:              - uploading new scan data
 5123: 
 5124:  Arguments:
 5125:   $r          - The Apache request object
 5126:   $file2grade - name of the file that contain the scanned data to score
 5127: 
 5128: =cut
 5129: 
 5130: sub scantron_selectphase {
 5131:     my ($r,$file2grade,$symb) = @_;
 5132:     if (!$symb) {return '';}
 5133:     my $map_error;
 5134:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
 5135:     if ($map_error) {
 5136:         $r->print('<br />'.&navmap_errormsg().'<br />');
 5137:         return;
 5138:     }
 5139:     my $default_form_data=&defaultFormData($symb);
 5140:     my $file_selector=&scantron_uploads($file2grade);
 5141:     my $format_selector=&scantron_scantab();
 5142:     my $CODE_selector=&scantron_CODElist();
 5143:     my $CODE_unique=&scantron_CODEunique();
 5144:     my $result;
 5145: 
 5146:     $ssi_error = 0;
 5147: 
 5148:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 5149:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 5150: 
 5151: 	# Chunk of form to prompt for a scantron file upload.
 5152: 
 5153:         $r->print('
 5154:     <br />
 5155:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5156:        '.&Apache::loncommon::start_data_table_header_row().'
 5157:             <th>
 5158:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
 5159:             </th>
 5160:        '.&Apache::loncommon::end_data_table_header_row().'
 5161:        '.&Apache::loncommon::start_data_table_row().'
 5162:             <td>
 5163: ');
 5164:     my $default_form_data=&defaultFormData($symb);
 5165:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5166:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 5167:     $r->print(&Apache::lonhtmlcommon::scripttag('
 5168:     function checkUpload(formname) {
 5169: 	if (formname.upfile.value == "") {
 5170: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
 5171: 	    return false;
 5172: 	}
 5173: 	formname.submit();
 5174:     }'));
 5175:     $r->print('
 5176:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 5177:                 '.$default_form_data.'
 5178:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 5179:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 5180:                 <input name="command" value="scantronupload_save" type="hidden" />
 5181:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
 5182:                 <br />
 5183:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 5184:               </form>
 5185: ');
 5186: 
 5187:         $r->print('
 5188:             </td>
 5189:        '.&Apache::loncommon::end_data_table_row().'
 5190:        '.&Apache::loncommon::end_data_table().'
 5191: ');
 5192:     }
 5193: 
 5194:     # Chunk of form to prompt for a file to grade and how:
 5195: 
 5196:     $result.= '
 5197:     <br />
 5198:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 5199:     <input type="hidden" name="command" value="scantron_warning" />
 5200:     '.$default_form_data.'
 5201:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5202:        '.&Apache::loncommon::start_data_table_header_row().'
 5203:             <th colspan="2">
 5204:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 5205:             </th>
 5206:        '.&Apache::loncommon::end_data_table_header_row().'
 5207:        '.&Apache::loncommon::start_data_table_row().'
 5208:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 5209:        '.&Apache::loncommon::end_data_table_row().'
 5210:        '.&Apache::loncommon::start_data_table_row().'
 5211:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
 5212:        '.&Apache::loncommon::end_data_table_row().'
 5213:        '.&Apache::loncommon::start_data_table_row().'
 5214:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
 5215:        '.&Apache::loncommon::end_data_table_row().'
 5216:        '.&Apache::loncommon::start_data_table_row().'
 5217:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 5218:        '.&Apache::loncommon::end_data_table_row().'
 5219:        '.&Apache::loncommon::start_data_table_row().'
 5220:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 5221:        '.&Apache::loncommon::end_data_table_row().'
 5222:        '.&Apache::loncommon::start_data_table_row().'
 5223: 	    <td> '.&mt('Options:').' </td>
 5224:             <td>
 5225: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 5226:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 5227:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 5228: 	    </td>
 5229:        '.&Apache::loncommon::end_data_table_row().'
 5230:        '.&Apache::loncommon::start_data_table_row().'
 5231:             <td colspan="2">
 5232:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
 5233:             </td>
 5234:        '.&Apache::loncommon::end_data_table_row().'
 5235:     '.&Apache::loncommon::end_data_table().'
 5236:     </form>
 5237: ';
 5238:    
 5239:     $r->print($result);
 5240: 
 5241: 
 5242: 
 5243:     # Chunk of the form that prompts to view a scoring office file,
 5244:     # corrected file, skipped records in a file.
 5245: 
 5246:     $r->print('
 5247:    <br />
 5248:    <form action="/adm/grades" name="scantron_download">
 5249:      '.$default_form_data.'
 5250:      <input type="hidden" name="command" value="scantron_download" />
 5251:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5252:        '.&Apache::loncommon::start_data_table_header_row().'
 5253:               <th>
 5254:                 &nbsp;'.&mt('Download a scoring office file').'
 5255:               </th>
 5256:        '.&Apache::loncommon::end_data_table_header_row().'
 5257:        '.&Apache::loncommon::start_data_table_row().'
 5258:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 5259:                 <br />
 5260:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 5261:        '.&Apache::loncommon::end_data_table_row().'
 5262:      '.&Apache::loncommon::end_data_table().'
 5263:    </form>
 5264:    <br />
 5265: ');
 5266: 
 5267:     &Apache::lonpickcode::code_list($r,2);
 5268: 
 5269:     $r->print('<br /><form method="post" name="checkscantron">'.
 5270:              $default_form_data."\n".
 5271:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 5272:              &Apache::loncommon::start_data_table_header_row()."\n".
 5273:              '<th colspan="2">
 5274:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
 5275:              '</th>'."\n".
 5276:               &Apache::loncommon::end_data_table_header_row()."\n".
 5277:               &Apache::loncommon::start_data_table_row()."\n".
 5278:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 5279:               '<td> '.$sequence_selector.' </td>'.
 5280:               &Apache::loncommon::end_data_table_row()."\n".
 5281:               &Apache::loncommon::start_data_table_row()."\n".
 5282:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 5283:               '<td> '.$file_selector.' </td>'."\n".
 5284:               &Apache::loncommon::end_data_table_row()."\n".
 5285:               &Apache::loncommon::start_data_table_row()."\n".
 5286:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 5287:               '<td> '.$format_selector.' </td>'."\n".
 5288:               &Apache::loncommon::end_data_table_row()."\n".
 5289:               &Apache::loncommon::start_data_table_row()."\n".
 5290:               '<td> '.&mt('Options').' </td>'."\n".
 5291:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
 5292:               &Apache::loncommon::end_data_table_row()."\n".
 5293:               &Apache::loncommon::start_data_table_row()."\n".
 5294:               '<td colspan="2">'."\n".
 5295:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 5296:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
 5297:               '</td>'."\n".
 5298:               &Apache::loncommon::end_data_table_row()."\n".
 5299:               &Apache::loncommon::end_data_table()."\n".
 5300:               '</form><br />');
 5301:     return;
 5302: }
 5303: 
 5304: =pod
 5305: 
 5306: =item get_scantron_config
 5307: 
 5308:    Parse and return the scantron configuration line selected as a
 5309:    hash of configuration file fields.
 5310: 
 5311:  Arguments:
 5312:     which - the name of the configuration to parse from the file.
 5313: 
 5314: 
 5315:  Returns:
 5316:             If the named configuration is not in the file, an empty
 5317:             hash is returned.
 5318:     a hash with the fields
 5319:       name         - internal name for the this configuration setup
 5320:       description  - text to display to operator that describes this config
 5321:       CODElocation - if 0 or the string 'none'
 5322:                           - no CODE exists for this config
 5323:                      if -1 || the string 'letter'
 5324:                           - a CODE exists for this config and is
 5325:                             a string of letters
 5326:                      Unsupported value (but planned for future support)
 5327:                           if a positive integer
 5328:                                - The CODE exists as the first n items from
 5329:                                  the question section of the form
 5330:                           if the string 'number'
 5331:                                - The CODE exists for this config and is
 5332:                                  a string of numbers
 5333:       CODEstart   - (only matter if a CODE exists) column in the line where
 5334:                      the CODE starts
 5335:       CODElength  - length of the CODE
 5336:       IDstart     - column where the student/employee ID starts
 5337:       IDlength    - length of the student/employee ID info
 5338:       Qstart      - column where the information from the bubbled
 5339:                     'questions' start
 5340:       Qlength     - number of columns comprising a single bubble line from
 5341:                     the sheet. (usually either 1 or 10)
 5342:       Qon         - either a single character representing the character used
 5343:                     to signal a bubble was chosen in the positional setup, or
 5344:                     the string 'letter' if the letter of the chosen bubble is
 5345:                     in the final, or 'number' if a number representing the
 5346:                     chosen bubble is in the file (1->A 0->J)
 5347:       Qoff        - the character used to represent that a bubble was
 5348:                     left blank
 5349:       PaperID     - if the scanning process generates a unique number for each
 5350:                     sheet scanned the column that this ID number starts in
 5351:       PaperIDlength - number of columns that comprise the unique ID number
 5352:                       for the sheet of paper
 5353:       FirstName   - column that the first name starts in
 5354:       FirstNameLength - number of columns that the first name spans
 5355:  
 5356:       LastName    - column that the last name starts in
 5357:       LastNameLength - number of columns that the last name spans
 5358:       BubblesPerRow - number of bubbles available in each row used to 
 5359:                       bubble an answer. (If not specified, 10 assumed).
 5360: =cut
 5361: 
 5362: sub get_scantron_config {
 5363:     my ($which) = @_;
 5364:     my @lines = &get_scantronformat_file();
 5365:     my %config;
 5366:     #FIXME probably should move to XML it has already gotten a bit much now
 5367:     foreach my $line (@lines) {
 5368: 	my ($name,$descrip)=split(/:/,$line);
 5369: 	if ($name ne $which ) { next; }
 5370: 	chomp($line);
 5371: 	my @config=split(/:/,$line);
 5372: 	$config{'name'}=$config[0];
 5373: 	$config{'description'}=$config[1];
 5374: 	$config{'CODElocation'}=$config[2];
 5375: 	$config{'CODEstart'}=$config[3];
 5376: 	$config{'CODElength'}=$config[4];
 5377: 	$config{'IDstart'}=$config[5];
 5378: 	$config{'IDlength'}=$config[6];
 5379: 	$config{'Qstart'}=$config[7];
 5380:  	$config{'Qlength'}=$config[8];
 5381: 	$config{'Qoff'}=$config[9];
 5382: 	$config{'Qon'}=$config[10];
 5383: 	$config{'PaperID'}=$config[11];
 5384: 	$config{'PaperIDlength'}=$config[12];
 5385: 	$config{'FirstName'}=$config[13];
 5386: 	$config{'FirstNamelength'}=$config[14];
 5387: 	$config{'LastName'}=$config[15];
 5388: 	$config{'LastNamelength'}=$config[16];
 5389:         $config{'BubblesPerRow'}=$config[17];
 5390: 	last;
 5391:     }
 5392:     return %config;
 5393: }
 5394: 
 5395: =pod 
 5396: 
 5397: =item username_to_idmap
 5398: 
 5399:     creates a hash keyed by student/employee ID with values of the corresponding
 5400:     student username:domain.
 5401: 
 5402:   Arguments:
 5403: 
 5404:     $classlist - reference to the class list hash. This is a hash
 5405:                  keyed by student name:domain  whose elements are references
 5406:                  to arrays containing various chunks of information
 5407:                  about the student. (See loncoursedata for more info).
 5408: 
 5409:   Returns
 5410:     %idmap - the constructed hash
 5411: 
 5412: =cut
 5413: 
 5414: sub username_to_idmap {
 5415:     my ($classlist)= @_;
 5416:     my %idmap;
 5417:     foreach my $student (keys(%$classlist)) {
 5418: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
 5419: 	    $student;
 5420:     }
 5421:     return %idmap;
 5422: }
 5423: 
 5424: =pod
 5425: 
 5426: =item scantron_fixup_scanline
 5427: 
 5428:    Process a requested correction to a scanline.
 5429: 
 5430:   Arguments:
 5431:     $scantron_config   - hash from &get_scantron_config()
 5432:     $scan_data         - hash of correction information 
 5433:                           (see &scantron_getfile())
 5434:     $line              - existing scanline
 5435:     $whichline         - line number of the passed in scanline
 5436:     $field             - type of change to process 
 5437:                          (either 
 5438:                           'ID'     -> correct the student/employee ID
 5439:                           'CODE'   -> correct the CODE
 5440:                           'answer' -> fixup the submitted answers)
 5441:     
 5442:    $args               - hash of additional info,
 5443:                           - 'ID' 
 5444:                                'newid' -> studentID to use in replacement
 5445:                                           of existing one
 5446:                           - 'CODE' 
 5447:                                'CODE_ignore_dup' - set to true if duplicates
 5448:                                                    should be ignored.
 5449: 	                       'CODE' - is new code or 'use_unfound'
 5450:                                         if the existing unfound code should
 5451:                                         be used as is
 5452:                           - 'answer'
 5453:                                'response' - new answer or 'none' if blank
 5454:                                'question' - the bubble line to change
 5455:                                'questionnum' - the question identifier,
 5456:                                                may include subquestion. 
 5457: 
 5458:   Returns:
 5459:     $line - the modified scanline
 5460: 
 5461:   Side effects: 
 5462:     $scan_data - may be updated
 5463: 
 5464: =cut
 5465: 
 5466: 
 5467: sub scantron_fixup_scanline {
 5468:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 5469:     if ($field eq 'ID') {
 5470: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 5471: 	    return ($line,1,'New value too large');
 5472: 	}
 5473: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 5474: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 5475: 				     $args->{'newid'});
 5476: 	}
 5477: 	substr($line,$$scantron_config{'IDstart'}-1,
 5478: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 5479: 	if ($args->{'newid'}=~/^\s*$/) {
 5480: 	    &scan_data($scan_data,"$whichline.user",
 5481: 		       $args->{'username'}.':'.$args->{'domain'});
 5482: 	}
 5483:     } elsif ($field eq 'CODE') {
 5484: 	if ($args->{'CODE_ignore_dup'}) {
 5485: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 5486: 	}
 5487: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 5488: 	if ($args->{'CODE'} ne 'use_unfound') {
 5489: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 5490: 		return ($line,1,'New CODE value too large');
 5491: 	    }
 5492: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 5493: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 5494: 	    }
 5495: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 5496: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 5497: 	}
 5498:     } elsif ($field eq 'answer') {
 5499: 	my $length=$scantron_config->{'Qlength'};
 5500: 	my $off=$scantron_config->{'Qoff'};
 5501: 	my $on=$scantron_config->{'Qon'};
 5502: 	my $answer=${off}x$length;
 5503: 	if ($args->{'response'} eq 'none') {
 5504: 	    &scan_data($scan_data,
 5505: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 5506: 	} else {
 5507: 	    if ($on eq 'letter') {
 5508: 		my @alphabet=('A'..'Z');
 5509: 		$answer=$alphabet[$args->{'response'}];
 5510: 	    } elsif ($on eq 'number') {
 5511: 		$answer=$args->{'response'}+1;
 5512: 		if ($answer == 10) { $answer = '0'; }
 5513: 	    } else {
 5514: 		substr($answer,$args->{'response'},1)=$on;
 5515: 	    }
 5516: 	    &scan_data($scan_data,
 5517: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 5518: 	}
 5519: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 5520: 	substr($line,$where-1,$length)=$answer;
 5521:     }
 5522:     return $line;
 5523: }
 5524: 
 5525: =pod
 5526: 
 5527: =item scan_data
 5528: 
 5529:     Edit or look up  an item in the scan_data hash.
 5530: 
 5531:   Arguments:
 5532:     $scan_data  - The hash (see scantron_getfile)
 5533:     $key        - shorthand of the key to edit (actual key is
 5534:                   scantronfilename_key).
 5535:     $data        - New value of the hash entry.
 5536:     $delete      - If true, the entry is removed from the hash.
 5537: 
 5538:   Returns:
 5539:     The new value of the hash table field (undefined if deleted).
 5540: 
 5541: =cut
 5542: 
 5543: 
 5544: sub scan_data {
 5545:     my ($scan_data,$key,$value,$delete)=@_;
 5546:     my $filename=$env{'form.scantron_selectfile'};
 5547:     if (defined($value)) {
 5548: 	$scan_data->{$filename.'_'.$key} = $value;
 5549:     }
 5550:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 5551:     return $scan_data->{$filename.'_'.$key};
 5552: }
 5553: 
 5554: # ----- These first few routines are general use routines.----
 5555: 
 5556: # Return the number of occurences of a pattern in a string.
 5557: 
 5558: sub occurence_count {
 5559:     my ($string, $pattern) = @_;
 5560: 
 5561:     my @matches = ($string =~ /$pattern/g);
 5562: 
 5563:     return scalar(@matches);
 5564: }
 5565: 
 5566: 
 5567: # Take a string known to have digits and convert all the
 5568: # digits into letters in the range J,A..I.
 5569: 
 5570: sub digits_to_letters {
 5571:     my ($input) = @_;
 5572: 
 5573:     my @alphabet = ('J', 'A'..'I');
 5574: 
 5575:     my @input    = split(//, $input);
 5576:     my $output ='';
 5577:     for (my $i = 0; $i < scalar(@input); $i++) {
 5578: 	if ($input[$i] =~ /\d/) {
 5579: 	    $output .= $alphabet[$input[$i]];
 5580: 	} else {
 5581: 	    $output .= $input[$i];
 5582: 	}
 5583:     }
 5584:     return $output;
 5585: }
 5586: 
 5587: =pod 
 5588: 
 5589: =item scantron_parse_scanline
 5590: 
 5591:   Decodes a scanline from the selected scantron file
 5592: 
 5593:  Arguments:
 5594:     line             - The text of the scantron file line to process
 5595:     whichline        - Line number
 5596:     scantron_config  - Hash describing the format of the scantron lines.
 5597:     scan_data        - Hash of extra information about the scanline
 5598:                        (see scantron_getfile for more information)
 5599:     just_header      - True if should not process question answers but only
 5600:                        the stuff to the left of the answers.
 5601:  Returns:
 5602:    Hash containing the result of parsing the scanline
 5603: 
 5604:    Keys are all proceeded by the string 'scantron.'
 5605: 
 5606:        CODE    - the CODE in use for this scanline
 5607:        useCODE - 1 if the CODE is invalid but it usage has been forced
 5608:                  by the operator
 5609:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 5610:                             CODEs were selected, but the usage has been
 5611:                             forced by the operator
 5612:        ID  - student/employee ID
 5613:        PaperID - if used, the ID number printed on the sheet when the 
 5614:                  paper was scanned
 5615:        FirstName - first name from the sheet
 5616:        LastName  - last name from the sheet
 5617: 
 5618:      if just_header was not true these key may also exist
 5619: 
 5620:        missingerror - a list of bubble ranges that are considered to be answers
 5621:                       to a single question that don't have any bubbles filled in.
 5622:                       Of the form questionnumber:firstbubblenumber:count.
 5623:        doubleerror  - a list of bubble ranges that are considered to be answers
 5624:                       to a single question that have more than one bubble filled in.
 5625:                       Of the form questionnumber::firstbubblenumber:count
 5626:    
 5627:                 In the above, count is the number of bubble responses in the
 5628:                 input line needed to represent the possible answers to the question.
 5629:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 5630:                 per line would have count = 2.
 5631: 
 5632:        maxquest     - the number of the last bubble line that was parsed
 5633: 
 5634:        (<number> starts at 1)
 5635:        <number>.answer - zero or more letters representing the selected
 5636:                          letters from the scanline for the bubble line 
 5637:                          <number>.
 5638:                          if blank there was either no bubble or there where
 5639:                          multiple bubbles, (consult the keys missingerror and
 5640:                          doubleerror if this is an error condition)
 5641: 
 5642: =cut
 5643: 
 5644: sub scantron_parse_scanline {
 5645:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
 5646: 
 5647:     my %record;
 5648:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 5649:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 5650:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
 5651:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 5652: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 5653: 	if ($$scantron_config{'CODElocation'} < 0 ||
 5654: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 5655: 	    $$scantron_config{'CODElocation'} eq 'number') {
 5656: 	    $record{'scantron.CODE'}=substr($data,
 5657: 					    $$scantron_config{'CODEstart'}-1,
 5658: 					    $$scantron_config{'CODElength'});
 5659: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 5660: 		$record{'scantron.useCODE'}=1;
 5661: 	    }
 5662: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 5663: 		$record{'scantron.CODE_ignore_dup'}=1;
 5664: 	    }
 5665: 	} else {
 5666: 	    #FIXME interpret first N questions
 5667: 	}
 5668:     }
 5669:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 5670: 				  $$scantron_config{'IDlength'});
 5671:     $record{'scantron.PaperID'}=
 5672: 	substr($data,$$scantron_config{'PaperID'}-1,
 5673: 	       $$scantron_config{'PaperIDlength'});
 5674:     $record{'scantron.FirstName'}=
 5675: 	substr($data,$$scantron_config{'FirstName'}-1,
 5676: 	       $$scantron_config{'FirstNamelength'});
 5677:     $record{'scantron.LastName'}=
 5678: 	substr($data,$$scantron_config{'LastName'}-1,
 5679: 	       $$scantron_config{'LastNamelength'});
 5680:     if ($just_header) { return \%record; }
 5681: 
 5682:     my @alphabet=('A'..'Z');
 5683:     my $questnum=0;
 5684:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 5685: 
 5686:     chomp($questions);		# Get rid of any trailing \n.
 5687:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 5688:     while (length($questions)) {
 5689: 	my $answers_needed = $bubble_lines_per_response{$questnum};
 5690:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 5691:                              || 1;
 5692:         $questnum++;
 5693:         my $quest_id = $questnum;
 5694:         my $currentquest = substr($questions,0,$answer_length);
 5695:         $questions       = substr($questions,$answer_length);
 5696:         if (length($currentquest) < $answer_length) { next; }
 5697: 
 5698:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
 5699:             my $subquestnum = 1;
 5700:             my $subquestions = $currentquest;
 5701:             my @subanswers_needed = 
 5702:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
 5703:             foreach my $subans (@subanswers_needed) {
 5704:                 my $subans_length =
 5705:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 5706:                 my $currsubquest = substr($subquestions,0,$subans_length);
 5707:                 $subquestions   = substr($subquestions,$subans_length);
 5708:                 $quest_id = "$questnum.$subquestnum";
 5709:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 5710:                     ($$scantron_config{'Qon'} eq 'number')) {
 5711:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 5712:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 5713:                         \@alphabet,\%record,$scantron_config,$scan_data);
 5714:                 } else {
 5715:                     $ansnum = &scantron_validator_positional($ansnum,
 5716:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
 5717:                 }
 5718:                 $subquestnum ++;
 5719:             }
 5720:         } else {
 5721:             if (($$scantron_config{'Qon'} eq 'letter') ||
 5722:                 ($$scantron_config{'Qon'} eq 'number')) {
 5723:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 5724:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5725:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5726:             } else {
 5727:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 5728:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5729:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5730:             }
 5731:         }
 5732:     }
 5733:     $record{'scantron.maxquest'}=$questnum;
 5734:     return \%record;
 5735: }
 5736: 
 5737: sub scantron_validator_lettnum {
 5738:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 5739:         $alphabet,$record,$scantron_config,$scan_data) = @_;
 5740: 
 5741:     # Qon 'letter' implies for each slot in currquest we have:
 5742:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 5743:     #    about anything else (esp. a value of Qoff) for missing
 5744:     #    bubbles.
 5745:     #
 5746:     # Qon 'number' implies each slot gives a digit that indexes the
 5747:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 5748:     #    and * or ? for double bubbles on a single line.
 5749:     #
 5750: 
 5751:     my $matchon;
 5752:     if ($$scantron_config{'Qon'} eq 'letter') {
 5753:         $matchon = '[A-Z]';
 5754:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 5755:         $matchon = '\d';
 5756:     }
 5757:     my $occurrences = 0;
 5758:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5759:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5760:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5761:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5762:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5763:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5764:         my @singlelines = split('',$currquest);
 5765:         foreach my $entry (@singlelines) {
 5766:             $occurrences = &occurence_count($entry,$matchon);
 5767:             if ($occurrences > 1) {
 5768:                 last;
 5769:             }
 5770:         } 
 5771:     } else {
 5772:         $occurrences = &occurence_count($currquest,$matchon); 
 5773:     }
 5774:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 5775:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5776:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5777:             my $bubble = substr($currquest,$ans,1);
 5778:             if ($bubble =~ /$matchon/ ) {
 5779:                 if ($$scantron_config{'Qon'} eq 'number') {
 5780:                     if ($bubble == 0) {
 5781:                         $bubble = 10; 
 5782:                     }
 5783:                     $record->{"scantron.$ansnum.answer"} = 
 5784:                         $alphabet->[$bubble-1];
 5785:                 } else {
 5786:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 5787:                 }
 5788:             } else {
 5789:                 $record->{"scantron.$ansnum.answer"}='';
 5790:             }
 5791:             $ansnum++;
 5792:         }
 5793:     } elsif (!defined($currquest)
 5794:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 5795:             || (&occurence_count($currquest,$matchon) == 0)) {
 5796:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5797:             $record->{"scantron.$ansnum.answer"}='';
 5798:             $ansnum++;
 5799:         }
 5800:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5801:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 5802:         }
 5803:     } else {
 5804:         if ($$scantron_config{'Qon'} eq 'number') {
 5805:             $currquest = &digits_to_letters($currquest);            
 5806:         }
 5807:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5808:             my $bubble = substr($currquest,$ans,1);
 5809:             $record->{"scantron.$ansnum.answer"} = $bubble;
 5810:             $ansnum++;
 5811:         }
 5812:     }
 5813:     return $ansnum;
 5814: }
 5815: 
 5816: sub scantron_validator_positional {
 5817:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 5818:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
 5819: 
 5820:     # Otherwise there's a positional notation;
 5821:     # each bubble line requires Qlength items, and there are filled in
 5822:     # bubbles for each case where there 'Qon' characters.
 5823:     #
 5824: 
 5825:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 5826: 
 5827:     # If the split only gives us one element.. the full length of the
 5828:     # answer string, no bubbles are filled in:
 5829: 
 5830:     if ($answers_needed eq '') {
 5831:         return;
 5832:     }
 5833: 
 5834:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 5835:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5836:             $record->{"scantron.$ansnum.answer"}='';
 5837:             $ansnum++;
 5838:         }
 5839:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5840:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 5841:         }
 5842:     } elsif (scalar(@array) == 2) {
 5843:         my $location = length($array[0]);
 5844:         my $line_num = int($location / $$scantron_config{'Qlength'});
 5845:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 5846:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5847:             if ($ans eq $line_num) {
 5848:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 5849:             } else {
 5850:                 $record->{"scantron.$ansnum.answer"} = ' ';
 5851:             }
 5852:             $ansnum++;
 5853:          }
 5854:     } else {
 5855:         #  If there's more than one instance of a bubble character
 5856:         #  That's a double bubble; with positional notation we can
 5857:         #  record all the bubbles filled in as well as the
 5858:         #  fact this response consists of multiple bubbles.
 5859:         #
 5860:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5861:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5862:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5863:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5864:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5865:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5866:             my $doubleerror = 0;
 5867:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 5868:                    (!$doubleerror)) {
 5869:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 5870:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 5871:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 5872:                if (length(@currarray) > 2) {
 5873:                    $doubleerror = 1;
 5874:                } 
 5875:             }
 5876:             if ($doubleerror) {
 5877:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5878:             }
 5879:         } else {
 5880:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5881:         }
 5882:         my $item = $ansnum;
 5883:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5884:             $record->{"scantron.$item.answer"} = '';
 5885:             $item ++;
 5886:         }
 5887: 
 5888:         my @ans=@array;
 5889:         my $i=0;
 5890:         my $increment = 0;
 5891:         while ($#ans) {
 5892:             $i+=length($ans[0]) + $increment;
 5893:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 5894:             my $bubble = $i%$$scantron_config{'Qlength'};
 5895:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 5896:             shift(@ans);
 5897:             $increment = 1;
 5898:         }
 5899:         $ansnum += $answers_needed;
 5900:     }
 5901:     return $ansnum;
 5902: }
 5903: 
 5904: =pod
 5905: 
 5906: =item scantron_add_delay
 5907: 
 5908:    Adds an error message that occurred during the grading phase to a
 5909:    queue of messages to be shown after grading pass is complete
 5910: 
 5911:  Arguments:
 5912:    $delayqueue  - arrary ref of hash ref of error messages
 5913:    $scanline    - the scanline that caused the error
 5914:    $errormesage - the error message
 5915:    $errorcode   - a numeric code for the error
 5916: 
 5917:  Side Effects:
 5918:    updates the $delayqueue to have a new hash ref of the error
 5919: 
 5920: =cut
 5921: 
 5922: sub scantron_add_delay {
 5923:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 5924:     push(@$delayqueue,
 5925: 	 {'line' => $scanline, 'emsg' => $errormessage,
 5926: 	  'ecode' => $errorcode }
 5927: 	 );
 5928: }
 5929: 
 5930: =pod
 5931: 
 5932: =item scantron_find_student
 5933: 
 5934:    Finds the username for the current scanline
 5935: 
 5936:   Arguments:
 5937:    $scantron_record - hash result from scantron_parse_scanline
 5938:    $scan_data       - hash of correction information 
 5939:                       (see &scantron_getfile() form more information)
 5940:    $idmap           - hash from &username_to_idmap()
 5941:    $line            - number of current scanline
 5942:  
 5943:   Returns:
 5944:    Either 'username:domain' or undef if unknown
 5945: 
 5946: =cut
 5947: 
 5948: sub scantron_find_student {
 5949:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 5950:     my $scanID=$$scantron_record{'scantron.ID'};
 5951:     if ($scanID =~ /^\s*$/) {
 5952:  	return &scan_data($scan_data,"$line.user");
 5953:     }
 5954:     foreach my $id (keys(%$idmap)) {
 5955:  	if (lc($id) eq lc($scanID)) {
 5956:  	    return $$idmap{$id};
 5957:  	}
 5958:     }
 5959:     return undef;
 5960: }
 5961: 
 5962: =pod
 5963: 
 5964: =item scantron_filter
 5965: 
 5966:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 5967:    hidden resources was selected
 5968: 
 5969: =cut
 5970: 
 5971: sub scantron_filter {
 5972:     my ($curres)=@_;
 5973: 
 5974:     if (ref($curres) && $curres->is_problem()) {
 5975: 	# if the user has asked to not have either hidden
 5976: 	# or 'randomout' controlled resources to be graded
 5977: 	# don't include them
 5978: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 5979: 	    && $curres->randomout) {
 5980: 	    return 0;
 5981: 	}
 5982: 	return 1;
 5983:     }
 5984:     return 0;
 5985: }
 5986: 
 5987: =pod
 5988: 
 5989: =item scantron_process_corrections
 5990: 
 5991:    Gets correction information out of submitted form data and corrects
 5992:    the scanline
 5993: 
 5994: =cut
 5995: 
 5996: sub scantron_process_corrections {
 5997:     my ($r) = @_;
 5998:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 5999:     my ($scanlines,$scan_data)=&scantron_getfile();
 6000:     my $classlist=&Apache::loncoursedata::get_classlist();
 6001:     my $which=$env{'form.scantron_line'};
 6002:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 6003:     my ($skip,$err,$errmsg);
 6004:     if ($env{'form.scantron_skip_record'}) {
 6005: 	$skip=1;
 6006:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 6007: 	my $newstudent=$env{'form.scantron_username'}.':'.
 6008: 	    $env{'form.scantron_domain'};
 6009: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 6010: 	($line,$err,$errmsg)=
 6011: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6012: 				     'ID',{'newid'=>$newid,
 6013: 				    'username'=>$env{'form.scantron_username'},
 6014: 				    'domain'=>$env{'form.scantron_domain'}});
 6015:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 6016: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 6017: 	my $newCODE;
 6018: 	my %args;
 6019: 	if      ($resolution eq 'use_unfound') {
 6020: 	    $newCODE='use_unfound';
 6021: 	} elsif ($resolution eq 'use_found') {
 6022: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 6023: 	} elsif ($resolution eq 'use_typed') {
 6024: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 6025: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 6026: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 6027: 	}
 6028: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 6029: 	    $args{'CODE_ignore_dup'}=1;
 6030: 	}
 6031: 	$args{'CODE'}=$newCODE;
 6032: 	($line,$err,$errmsg)=
 6033: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6034: 				     'CODE',\%args);
 6035:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 6036: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 6037: 	    ($line,$err,$errmsg)=
 6038: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 6039: 					 $which,'answer',
 6040: 					 { 'question'=>$question,
 6041: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 6042:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 6043: 	    if ($err) { last; }
 6044: 	}
 6045:     }
 6046:     if ($err) {
 6047: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
 6048:     } else {
 6049: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 6050: 	&scantron_putfile($scanlines,$scan_data);
 6051:     }
 6052: }
 6053: 
 6054: =pod
 6055: 
 6056: =item reset_skipping_status
 6057: 
 6058:    Forgets the current set of remember skipped scanlines (and thus
 6059:    reverts back to considering all lines in the
 6060:    scantron_skipped_<filename> file)
 6061: 
 6062: =cut
 6063: 
 6064: sub reset_skipping_status {
 6065:     my ($scanlines,$scan_data)=&scantron_getfile();
 6066:     &scan_data($scan_data,'remember_skipping',undef,1);
 6067:     &scantron_putfile(undef,$scan_data);
 6068: }
 6069: 
 6070: =pod
 6071: 
 6072: =item start_skipping
 6073: 
 6074:    Marks a scanline to be skipped. 
 6075: 
 6076: =cut
 6077: 
 6078: sub start_skipping {
 6079:     my ($scan_data,$i)=@_;
 6080:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6081:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 6082: 	$remembered{$i}=2;
 6083:     } else {
 6084: 	$remembered{$i}=1;
 6085:     }
 6086:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 6087: }
 6088: 
 6089: =pod
 6090: 
 6091: =item should_be_skipped
 6092: 
 6093:    Checks whether a scanline should be skipped.
 6094: 
 6095: =cut
 6096: 
 6097: sub should_be_skipped {
 6098:     my ($scanlines,$scan_data,$i)=@_;
 6099:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 6100: 	# not redoing old skips
 6101: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 6102: 	return 0;
 6103:     }
 6104:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6105: 
 6106:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 6107: 	return 0;
 6108:     }
 6109:     return 1;
 6110: }
 6111: 
 6112: =pod
 6113: 
 6114: =item remember_current_skipped
 6115: 
 6116:    Discovers what scanlines are in the scantron_skipped_<filename>
 6117:    file and remembers them into scan_data for later use.
 6118: 
 6119: =cut
 6120: 
 6121: sub remember_current_skipped {
 6122:     my ($scanlines,$scan_data)=&scantron_getfile();
 6123:     my %to_remember;
 6124:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6125: 	if ($scanlines->{'skipped'}[$i]) {
 6126: 	    $to_remember{$i}=1;
 6127: 	}
 6128:     }
 6129: 
 6130:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 6131:     &scantron_putfile(undef,$scan_data);
 6132: }
 6133: 
 6134: =pod
 6135: 
 6136: =item check_for_error
 6137: 
 6138:     Checks if there was an error when attempting to remove a specific
 6139:     scantron_.. bubble sheet data file. Prints out an error if
 6140:     something went wrong.
 6141: 
 6142: =cut
 6143: 
 6144: sub check_for_error {
 6145:     my ($r,$result)=@_;
 6146:     if ($result ne 'ok' && $result ne 'not_found' ) {
 6147: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 6148:     }
 6149: }
 6150: 
 6151: =pod
 6152: 
 6153: =item scantron_warning_screen
 6154: 
 6155:    Interstitial screen to make sure the operator has selected the
 6156:    correct options before we start the validation phase.
 6157: 
 6158: =cut
 6159: 
 6160: sub scantron_warning_screen {
 6161:     my ($button_text,$symb)=@_;
 6162:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 6163:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6164:     my $CODElist;
 6165:     if ($scantron_config{'CODElocation'} &&
 6166: 	$scantron_config{'CODEstart'} &&
 6167: 	$scantron_config{'CODElength'}) {
 6168: 	$CODElist=$env{'form.scantron_CODElist'};
 6169: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
 6170: 	$CODElist=
 6171: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 6172: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 6173:     }
 6174:     return ('
 6175: <p>
 6176: <span class="LC_warning">
 6177: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
 6178: </p>
 6179: <table>
 6180: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 6181: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 6182: '.$CODElist.'
 6183: </table>
 6184: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'<br />
 6185: '.&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>
 6186: 
 6187: <br />
 6188: ');
 6189: }
 6190: 
 6191: =pod
 6192: 
 6193: =item scantron_do_warning
 6194: 
 6195:    Check if the operator has picked something for all required
 6196:    fields. Error out if something is missing.
 6197: 
 6198: =cut
 6199: 
 6200: sub scantron_do_warning {
 6201:     my ($r,$symb)=@_;
 6202:     if (!$symb) {return '';}
 6203:     my $default_form_data=&defaultFormData($symb);
 6204:     $r->print(&scantron_form_start().$default_form_data);
 6205:     if ( $env{'form.selectpage'} eq '' ||
 6206: 	 $env{'form.scantron_selectfile'} eq '' ||
 6207: 	 $env{'form.scantron_format'} eq '' ) {
 6208: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
 6209: 	if ( $env{'form.selectpage'} eq '') {
 6210: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 6211: 	} 
 6212: 	if ( $env{'form.scantron_selectfile'} eq '') {
 6213: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected a file that contains the student's response data.").'</span></p>');
 6214: 	} 
 6215: 	if ( $env{'form.scantron_format'} eq '') {
 6216: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected the format of the student's response data.").'</span></p>');
 6217: 	} 
 6218:     } else {
 6219: 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
 6220: 	$r->print('
 6221: '.$warning.'
 6222: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 6223: <input type="hidden" name="command" value="scantron_validate" />
 6224: ');
 6225:     }
 6226:     $r->print("</form><br />");
 6227:     return '';
 6228: }
 6229: 
 6230: =pod
 6231: 
 6232: =item scantron_form_start
 6233: 
 6234:     html hidden input for remembering all selected grading options
 6235: 
 6236: =cut
 6237: 
 6238: sub scantron_form_start {
 6239:     my ($max_bubble)=@_;
 6240:     my $result= <<SCANTRONFORM;
 6241: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 6242:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 6243:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 6244:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 6245:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 6246:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 6247:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 6248:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 6249:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 6250:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 6251: SCANTRONFORM
 6252: 
 6253:   my $line = 0;
 6254:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 6255:        my $chunk =
 6256: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 6257:        $chunk .=
 6258: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 6259:        $chunk .= 
 6260:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 6261:        $chunk .=
 6262:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 6263:        $result .= $chunk;
 6264:        $line++;
 6265:    }
 6266:     return $result;
 6267: }
 6268: 
 6269: =pod
 6270: 
 6271: =item scantron_validate_file
 6272: 
 6273:     Dispatch routine for doing validation of a bubble sheet data file.
 6274: 
 6275:     Also processes any necessary information resets that need to
 6276:     occur before validation begins (ignore previous corrections,
 6277:     restarting the skipped records processing)
 6278: 
 6279: =cut
 6280: 
 6281: sub scantron_validate_file {
 6282:     my ($r,$symb) = @_;
 6283:     if (!$symb) {return '';}
 6284:     my $default_form_data=&defaultFormData($symb);
 6285:     
 6286:     # do the detection of only doing skipped records first befroe we delete
 6287:     # them when doing the corrections reset
 6288:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 6289: 	&reset_skipping_status();
 6290:     }
 6291:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 6292: 	&remember_current_skipped();
 6293: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 6294:     }
 6295: 
 6296:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 6297: 	&check_for_error($r,&scantron_remove_file('corrected'));
 6298: 	&check_for_error($r,&scantron_remove_file('skipped'));
 6299: 	&check_for_error($r,&scantron_remove_scan_data());
 6300: 	$env{'form.scantron_options_ignore'}='done';
 6301:     }
 6302: 
 6303:     if ($env{'form.scantron_corrections'}) {
 6304: 	&scantron_process_corrections($r);
 6305:     }
 6306:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 6307:     #get the student pick code ready
 6308:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 6309:     my $nav_error;
 6310:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6311:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 6312:     if ($nav_error) {
 6313:         $r->print(&navmap_errormsg());
 6314:         return '';
 6315:     }
 6316:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 6317:     $r->print($result);
 6318:     
 6319:     my @validate_phases=( 'sequence',
 6320: 			  'ID',
 6321: 			  'CODE',
 6322: 			  'doublebubble',
 6323: 			  'missingbubbles');
 6324:     if (!$env{'form.validatepass'}) {
 6325: 	$env{'form.validatepass'} = 0;
 6326:     }
 6327:     my $currentphase=$env{'form.validatepass'};
 6328: 
 6329: 
 6330:     my $stop=0;
 6331:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 6332: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 6333: 	$r->rflush();
 6334: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 6335: 	{
 6336: 	    no strict 'refs';
 6337: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 6338: 	}
 6339:     }
 6340:     if (!$stop) {
 6341: 	my $warning=&scantron_warning_screen('Start Grading',$symb);
 6342: 	$r->print(&mt('Validation process complete.').'<br />'.
 6343:                   $warning.
 6344:                   &mt('Perform verification for each student after storage of submissions?').
 6345:                   '&nbsp;<span class="LC_nobreak"><label>'.
 6346:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 6347:                   ('&nbsp;'x3).'<label>'.
 6348:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 6349:                   '</label></span><br />'.
 6350:                   &mt('Grading will take longer if you use verification.').'<br />'.
 6351:                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
 6352:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 6353:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 6354:     } else {
 6355: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 6356: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 6357:     }
 6358:     if ($stop) {
 6359: 	if ($validate_phases[$currentphase] eq 'sequence') {
 6360: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 6361: 	    $r->print(' '.&mt('this error').' <br />');
 6362: 
 6363: 	    $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>');
 6364: 	} else {
 6365:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 6366: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 6367:             } else {
 6368:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 6369:             }
 6370: 	    $r->print(' '.&mt('using corrected info').' <br />');
 6371: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 6372: 	    $r->print(" ".&mt("this scanline saving it for later."));
 6373: 	}
 6374:     }
 6375:     $r->print(" </form><br />");
 6376:     return '';
 6377: }
 6378: 
 6379: 
 6380: =pod
 6381: 
 6382: =item scantron_remove_file
 6383: 
 6384:    Removes the requested bubble sheet data file, makes sure that
 6385:    scantron_original_<filename> is never removed
 6386: 
 6387: 
 6388: =cut
 6389: 
 6390: sub scantron_remove_file {
 6391:     my ($which)=@_;
 6392:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6393:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6394:     my $file='scantron_';
 6395:     if ($which eq 'corrected' || $which eq 'skipped') {
 6396: 	$file.=$which.'_';
 6397:     } else {
 6398: 	return 'refused';
 6399:     }
 6400:     $file.=$env{'form.scantron_selectfile'};
 6401:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 6402: }
 6403: 
 6404: 
 6405: =pod
 6406: 
 6407: =item scantron_remove_scan_data
 6408: 
 6409:    Removes all scan_data correction for the requested bubble sheet
 6410:    data file.  (In the case that both the are doing skipped records we need
 6411:    to remember the old skipped lines for the time being so that element
 6412:    persists for a while.)
 6413: 
 6414: =cut
 6415: 
 6416: sub scantron_remove_scan_data {
 6417:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6418:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6419:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 6420:     my @todelete;
 6421:     my $filename=$env{'form.scantron_selectfile'};
 6422:     foreach my $key (@keys) {
 6423: 	if ($key=~/^\Q$filename\E_/) {
 6424: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 6425: 		$key=~/remember_skipping/) {
 6426: 		next;
 6427: 	    }
 6428: 	    push(@todelete,$key);
 6429: 	}
 6430:     }
 6431:     my $result;
 6432:     if (@todelete) {
 6433: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 6434: 				       \@todelete,$cdom,$cname);
 6435:     } else {
 6436: 	$result = 'ok';
 6437:     }
 6438:     return $result;
 6439: }
 6440: 
 6441: 
 6442: =pod
 6443: 
 6444: =item scantron_getfile
 6445: 
 6446:     Fetches the requested bubble sheet data file (all 3 versions), and
 6447:     the scan_data hash
 6448:   
 6449:   Arguments:
 6450:     None
 6451: 
 6452:   Returns:
 6453:     2 hash references
 6454: 
 6455:      - first one has 
 6456:          orig      -
 6457:          corrected -
 6458:          skipped   -  each of which points to an array ref of the specified
 6459:                       file broken up into individual lines
 6460:          count     - number of scanlines
 6461:  
 6462:      - second is the scan_data hash possible keys are
 6463:        ($number refers to scanline numbered $number and thus the key affects
 6464:         only that scanline
 6465:         $bubline refers to the specific bubble line element and the aspects
 6466:         refers to that specific bubble line element)
 6467: 
 6468:        $number.user - username:domain to use
 6469:        $number.CODE_ignore_dup 
 6470:                     - ignore the duplicate CODE error 
 6471:        $number.useCODE
 6472:                     - use the CODE in the scanline as is
 6473:        $number.no_bubble.$bubline
 6474:                     - it is valid that there is no bubbled in bubble
 6475:                       at $number $bubline
 6476:        remember_skipping
 6477:                     - a frozen hash containing keys of $number and values
 6478:                       of either 
 6479:                         1 - we are on a 'do skipped records pass' and plan
 6480:                             on processing this line
 6481:                         2 - we are on a 'do skipped records pass' and this
 6482:                             scanline has been marked to skip yet again
 6483: 
 6484: =cut
 6485: 
 6486: sub scantron_getfile {
 6487:     #FIXME really would prefer a scantron directory
 6488:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6489:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6490:     my $lines;
 6491:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6492: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 6493:     my %scanlines;
 6494:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 6495:     my $temp=$scanlines{'orig'};
 6496:     $scanlines{'count'}=$#$temp;
 6497: 
 6498:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6499: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 6500:     if ($lines eq '-1') {
 6501: 	$scanlines{'corrected'}=[];
 6502:     } else {
 6503: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 6504:     }
 6505:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6506: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 6507:     if ($lines eq '-1') {
 6508: 	$scanlines{'skipped'}=[];
 6509:     } else {
 6510: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 6511:     }
 6512:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 6513:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 6514:     my %scan_data = @tmp;
 6515:     return (\%scanlines,\%scan_data);
 6516: }
 6517: 
 6518: =pod
 6519: 
 6520: =item lonnet_putfile
 6521: 
 6522:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 6523: 
 6524:  Arguments:
 6525:    $contents - data to store
 6526:    $filename - filename to store $contents into
 6527: 
 6528:  Returns:
 6529:    result value from &Apache::lonnet::finishuserfileupload
 6530: 
 6531: =cut
 6532: 
 6533: sub lonnet_putfile {
 6534:     my ($contents,$filename)=@_;
 6535:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6536:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6537:     $env{'form.sillywaytopassafilearound'}=$contents;
 6538:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 6539: 
 6540: }
 6541: 
 6542: =pod
 6543: 
 6544: =item scantron_putfile
 6545: 
 6546:     Stores the current version of the bubble sheet data files, and the
 6547:     scan_data hash. (Does not modify the original version only the
 6548:     corrected and skipped versions.
 6549: 
 6550:  Arguments:
 6551:     $scanlines - hash ref that looks like the first return value from
 6552:                  &scantron_getfile()
 6553:     $scan_data - hash ref that looks like the second return value from
 6554:                  &scantron_getfile()
 6555: 
 6556: =cut
 6557: 
 6558: sub scantron_putfile {
 6559:     my ($scanlines,$scan_data) = @_;
 6560:     #FIXME really would prefer a scantron directory
 6561:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6562:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6563:     if ($scanlines) {
 6564: 	my $prefix='scantron_';
 6565: # no need to update orig, shouldn't change
 6566: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 6567: #		    $env{'form.scantron_selectfile'});
 6568: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 6569: 			$prefix.'corrected_'.
 6570: 			$env{'form.scantron_selectfile'});
 6571: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 6572: 			$prefix.'skipped_'.
 6573: 			$env{'form.scantron_selectfile'});
 6574:     }
 6575:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 6576: }
 6577: 
 6578: =pod
 6579: 
 6580: =item scantron_get_line
 6581: 
 6582:    Returns the correct version of the scanline
 6583: 
 6584:  Arguments:
 6585:     $scanlines - hash ref that looks like the first return value from
 6586:                  &scantron_getfile()
 6587:     $scan_data - hash ref that looks like the second return value from
 6588:                  &scantron_getfile()
 6589:     $i         - number of the requested line (starts at 0)
 6590: 
 6591:  Returns:
 6592:    A scanline, (either the original or the corrected one if it
 6593:    exists), or undef if the requested scanline should be
 6594:    skipped. (Either because it's an skipped scanline, or it's an
 6595:    unskipped scanline and we are not doing a 'do skipped scanlines'
 6596:    pass.
 6597: 
 6598: =cut
 6599: 
 6600: sub scantron_get_line {
 6601:     my ($scanlines,$scan_data,$i)=@_;
 6602:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 6603:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 6604:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 6605:     return $scanlines->{'orig'}[$i]; 
 6606: }
 6607: 
 6608: =pod
 6609: 
 6610: =item scantron_todo_count
 6611: 
 6612:     Counts the number of scanlines that need processing.
 6613: 
 6614:  Arguments:
 6615:     $scanlines - hash ref that looks like the first return value from
 6616:                  &scantron_getfile()
 6617:     $scan_data - hash ref that looks like the second return value from
 6618:                  &scantron_getfile()
 6619: 
 6620:  Returns:
 6621:     $count - number of scanlines to process
 6622: 
 6623: =cut
 6624: 
 6625: sub get_todo_count {
 6626:     my ($scanlines,$scan_data)=@_;
 6627:     my $count=0;
 6628:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6629: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6630: 	if ($line=~/^[\s\cz]*$/) { next; }
 6631: 	$count++;
 6632:     }
 6633:     return $count;
 6634: }
 6635: 
 6636: =pod
 6637: 
 6638: =item scantron_put_line
 6639: 
 6640:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
 6641:     data file.
 6642: 
 6643:  Arguments:
 6644:     $scanlines - hash ref that looks like the first return value from
 6645:                  &scantron_getfile()
 6646:     $scan_data - hash ref that looks like the second return value from
 6647:                  &scantron_getfile()
 6648:     $i         - line number to update
 6649:     $newline   - contents of the updated scanline
 6650:     $skip      - if true make the line for skipping and update the
 6651:                  'skipped' file
 6652: 
 6653: =cut
 6654: 
 6655: sub scantron_put_line {
 6656:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 6657:     if ($skip) {
 6658: 	$scanlines->{'skipped'}[$i]=$newline;
 6659: 	&start_skipping($scan_data,$i);
 6660: 	return;
 6661:     }
 6662:     $scanlines->{'corrected'}[$i]=$newline;
 6663: }
 6664: 
 6665: =pod
 6666: 
 6667: =item scantron_clear_skip
 6668: 
 6669:    Remove a line from the 'skipped' file
 6670: 
 6671:  Arguments:
 6672:     $scanlines - hash ref that looks like the first return value from
 6673:                  &scantron_getfile()
 6674:     $scan_data - hash ref that looks like the second return value from
 6675:                  &scantron_getfile()
 6676:     $i         - line number to update
 6677: 
 6678: =cut
 6679: 
 6680: sub scantron_clear_skip {
 6681:     my ($scanlines,$scan_data,$i)=@_;
 6682:     if (exists($scanlines->{'skipped'}[$i])) {
 6683: 	undef($scanlines->{'skipped'}[$i]);
 6684: 	return 1;
 6685:     }
 6686:     return 0;
 6687: }
 6688: 
 6689: =pod
 6690: 
 6691: =item scantron_filter_not_exam
 6692: 
 6693:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 6694:    filter out resources that are not marked as 'exam' mode
 6695: 
 6696: =cut
 6697: 
 6698: sub scantron_filter_not_exam {
 6699:     my ($curres)=@_;
 6700:     
 6701:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 6702: 	# if the user has asked to not have either hidden
 6703: 	# or 'randomout' controlled resources to be graded
 6704: 	# don't include them
 6705: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6706: 	    && $curres->randomout) {
 6707: 	    return 0;
 6708: 	}
 6709: 	return 1;
 6710:     }
 6711:     return 0;
 6712: }
 6713: 
 6714: =pod
 6715: 
 6716: =item scantron_validate_sequence
 6717: 
 6718:     Validates the selected sequence, checking for resource that are
 6719:     not set to exam mode.
 6720: 
 6721: =cut
 6722: 
 6723: sub scantron_validate_sequence {
 6724:     my ($r,$currentphase) = @_;
 6725: 
 6726:     my $navmap=Apache::lonnavmaps::navmap->new();
 6727:     unless (ref($navmap)) {
 6728:         $r->print(&navmap_errormsg());
 6729:         return (1,$currentphase);
 6730:     }
 6731:     my (undef,undef,$sequence)=
 6732: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 6733: 
 6734:     my $map=$navmap->getResourceByUrl($sequence);
 6735: 
 6736:     $r->print('<input type="hidden" name="validate_sequence_exam"
 6737:                                     value="ignore" />');
 6738:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 6739: 	my @resources=
 6740: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 6741: 	if (@resources) {
 6742: 	    $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>");
 6743: 	    return (1,$currentphase);
 6744: 	}
 6745:     }
 6746: 
 6747:     return (0,$currentphase+1);
 6748: }
 6749: 
 6750: 
 6751: 
 6752: sub scantron_validate_ID {
 6753:     my ($r,$currentphase) = @_;
 6754:     
 6755:     #get student info
 6756:     my $classlist=&Apache::loncoursedata::get_classlist();
 6757:     my %idmap=&username_to_idmap($classlist);
 6758: 
 6759:     #get scantron line setup
 6760:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6761:     my ($scanlines,$scan_data)=&scantron_getfile();
 6762: 
 6763:     my $nav_error;
 6764:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
 6765:     if ($nav_error) {
 6766:         $r->print(&navmap_errormsg());
 6767:         return(1,$currentphase);
 6768:     }
 6769: 
 6770:     my %found=('ids'=>{},'usernames'=>{});
 6771:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6772: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6773: 	if ($line=~/^[\s\cz]*$/) { next; }
 6774: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 6775: 						 $scan_data);
 6776: 	my $id=$$scan_record{'scantron.ID'};
 6777: 	my $found;
 6778: 	foreach my $checkid (keys(%idmap)) {
 6779: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 6780: 	}
 6781: 	if ($found) {
 6782: 	    my $username=$idmap{$found};
 6783: 	    if ($found{'ids'}{$found}) {
 6784: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6785: 					 $line,'duplicateID',$found);
 6786: 		return(1,$currentphase);
 6787: 	    } elsif ($found{'usernames'}{$username}) {
 6788: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6789: 					 $line,'duplicateID',$username);
 6790: 		return(1,$currentphase);
 6791: 	    }
 6792: 	    #FIXME store away line we previously saw the ID on to use above
 6793: 	    $found{'ids'}{$found}++;
 6794: 	    $found{'usernames'}{$username}++;
 6795: 	} else {
 6796: 	    if ($id =~ /^\s*$/) {
 6797: 		my $username=&scan_data($scan_data,"$i.user");
 6798: 		if (defined($username) && $found{'usernames'}{$username}) {
 6799: 		    &scantron_get_correction($r,$i,$scan_record,
 6800: 					     \%scantron_config,
 6801: 					     $line,'duplicateID',$username);
 6802: 		    return(1,$currentphase);
 6803: 		} elsif (!defined($username)) {
 6804: 		    &scantron_get_correction($r,$i,$scan_record,
 6805: 					     \%scantron_config,
 6806: 					     $line,'incorrectID');
 6807: 		    return(1,$currentphase);
 6808: 		}
 6809: 		$found{'usernames'}{$username}++;
 6810: 	    } else {
 6811: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6812: 					 $line,'incorrectID');
 6813: 		return(1,$currentphase);
 6814: 	    }
 6815: 	}
 6816:     }
 6817: 
 6818:     return (0,$currentphase+1);
 6819: }
 6820: 
 6821: 
 6822: sub scantron_get_correction {
 6823:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
 6824: #FIXME in the case of a duplicated ID the previous line, probably need
 6825: #to show both the current line and the previous one and allow skipping
 6826: #the previous one or the current one
 6827: 
 6828:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 6829: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6830: 			    " for PaperID <tt>[_1]</tt>",
 6831: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
 6832:     } else {
 6833: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6834: 			    " in scanline [_1] <pre>[_2]</pre>",
 6835: 			    $i,$line)."</p> \n");
 6836:     }
 6837:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
 6838: 			  "The name on the paper is [_2],[_3]",
 6839: 			  $$scan_record{'scantron.ID'},
 6840: 			  $$scan_record{'scantron.LastName'},
 6841: 			  $$scan_record{'scantron.FirstName'})."</p>";
 6842: 
 6843:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 6844:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 6845:                            # Array populated for doublebubble or
 6846:     my @lines_to_correct;  # missingbubble errors to build javascript
 6847:                            # to validate radio button checking   
 6848: 
 6849:     if ($error =~ /ID$/) {
 6850: 	if ($error eq 'incorrectID') {
 6851: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
 6852: 		      "</p>\n");
 6853: 	} elsif ($error eq 'duplicateID') {
 6854: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 6855: 	}
 6856: 	$r->print($message);
 6857: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6858: 	$r->print("\n<ul><li> ");
 6859: 	#FIXME it would be nice if this sent back the user ID and
 6860: 	#could do partial userID matches
 6861: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 6862: 				       'scantron_username','scantron_domain'));
 6863: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 6864: 	$r->print("\n@".
 6865: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 6866: 
 6867: 	$r->print('</li>');
 6868:     } elsif ($error =~ /CODE$/) {
 6869: 	if ($error eq 'incorrectCODE') {
 6870: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 6871: 	} elsif ($error eq 'duplicateCODE') {
 6872: 	    $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");
 6873: 	}
 6874: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
 6875: 			    $$scan_record{'scantron.CODE'})."<br />\n");
 6876: 	$r->print($message);
 6877: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6878: 	$r->print("\n<br /> ");
 6879: 	my $i=0;
 6880: 	if ($error eq 'incorrectCODE' 
 6881: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 6882: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 6883: 	    if ($closest > 0) {
 6884: 		foreach my $testcode (@{$closest}) {
 6885: 		    my $checked='';
 6886: 		    if (!$i) { $checked=' checked="checked"'; }
 6887: 		    $r->print("
 6888:    <label>
 6889:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
 6890:        ".&mt("Use the similar CODE [_1] instead.",
 6891: 	    "<b><tt>".$testcode."</tt></b>")."
 6892:     </label>
 6893:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 6894: 		    $r->print("\n<br />");
 6895: 		    $i++;
 6896: 		}
 6897: 	    }
 6898: 	}
 6899: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 6900: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
 6901: 	    $r->print("
 6902:     <label>
 6903:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
 6904:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
 6905: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 6906:     </label>");
 6907: 	    $r->print("\n<br />");
 6908: 	}
 6909: 
 6910: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
 6911: function change_radio(field) {
 6912:     var slct=document.scantronupload.scantron_CODE_resolution;
 6913:     var i;
 6914:     for (i=0;i<slct.length;i++) {
 6915:         if (slct[i].value==field) { slct[i].checked=true; }
 6916:     }
 6917: }
 6918: ENDSCRIPT
 6919: 	my $href="/adm/pickcode?".
 6920: 	   "form=".&escape("scantronupload").
 6921: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 6922: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 6923: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 6924: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 6925: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 6926: 	    $r->print("
 6927:     <label>
 6928:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 6929:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 6930: 	     "<a target='_blank' href='$href'>","</a>")."
 6931:     </label> 
 6932:     ".&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\')" />'));
 6933: 	    $r->print("\n<br />");
 6934: 	}
 6935: 	$r->print("
 6936:     <label>
 6937:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 6938:        ".&mt("Use [_1] as the CODE.",
 6939: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 6940: 	$r->print("\n<br /><br />");
 6941:     } elsif ($error eq 'doublebubble') {
 6942: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 6943: 
 6944: 	# The form field scantron_questions is acutally a list of line numbers.
 6945: 	# represented by this form so:
 6946: 
 6947: 	my $line_list = &questions_to_line_list($arg);
 6948: 
 6949: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 6950: 		  $line_list.'" />');
 6951: 	$r->print($message);
 6952: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 6953: 	foreach my $question (@{$arg}) {
 6954: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 6955:                                                    $scan_record, $error);
 6956:             push(@lines_to_correct,@linenums);
 6957: 	}
 6958:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 6959:     } elsif ($error eq 'missingbubble') {
 6960: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
 6961: 	$r->print($message);
 6962: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 6963: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 6964: 
 6965: 	# The form field scantron_questions is actually a list of line numbers not
 6966: 	# a list of question numbers. Therefore:
 6967: 	#
 6968: 	
 6969: 	my $line_list = &questions_to_line_list($arg);
 6970: 
 6971: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 6972: 		  $line_list.'" />');
 6973: 	foreach my $question (@{$arg}) {
 6974: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 6975:                                                    $scan_record, $error);
 6976:             push(@lines_to_correct,@linenums);
 6977: 	}
 6978:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 6979:     } else {
 6980: 	$r->print("\n<ul>");
 6981:     }
 6982:     $r->print("\n</li></ul>");
 6983: }
 6984: 
 6985: sub verify_bubbles_checked {
 6986:     my (@ansnums) = @_;
 6987:     my $ansnumstr = join('","',@ansnums);
 6988:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 6989:     my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
 6990: function verify_bubble_radio(form) {
 6991:     var ansnumArray = new Array ("$ansnumstr");
 6992:     var need_bubble_count = 0;
 6993:     for (var i=0; i<ansnumArray.length; i++) {
 6994:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 6995:             var bubble_picked = 0; 
 6996:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 6997:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 6998:                     bubble_picked = 1;
 6999:                 }
 7000:             }
 7001:             if (bubble_picked == 0) {
 7002:                 need_bubble_count ++;
 7003:             }
 7004:         }
 7005:     }
 7006:     if (need_bubble_count) {
 7007:         alert("$warning");
 7008:         return;
 7009:     }
 7010:     form.submit(); 
 7011: }
 7012: ENDSCRIPT
 7013:     return $output;
 7014: }
 7015: 
 7016: =pod
 7017: 
 7018: =item  questions_to_line_list
 7019: 
 7020: Converts a list of questions into a string of comma separated
 7021: line numbers in the answer sheet used by the questions.  This is
 7022: used to fill in the scantron_questions form field.
 7023: 
 7024:   Arguments:
 7025:      questions    - Reference to an array of questions.
 7026: 
 7027: =cut
 7028: 
 7029: 
 7030: sub questions_to_line_list {
 7031:     my ($questions) = @_;
 7032:     my @lines;
 7033: 
 7034:     foreach my $item (@{$questions}) {
 7035:         my $question = $item;
 7036:         my ($first,$count,$last);
 7037:         if ($item =~ /^(\d+)\.(\d+)$/) {
 7038:             $question = $1;
 7039:             my $subquestion = $2;
 7040:             $first = $first_bubble_line{$question-1} + 1;
 7041:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7042:             my $subcount = 1;
 7043:             while ($subcount<$subquestion) {
 7044:                 $first += $subans[$subcount-1];
 7045:                 $subcount ++;
 7046:             }
 7047:             $count = $subans[$subquestion-1];
 7048:         } else {
 7049: 	    $first   = $first_bubble_line{$question-1} + 1;
 7050: 	    $count   = $bubble_lines_per_response{$question-1};
 7051:         }
 7052:         $last = $first+$count-1;
 7053:         push(@lines, ($first..$last));
 7054:     }
 7055:     return join(',', @lines);
 7056: }
 7057: 
 7058: =pod 
 7059: 
 7060: =item prompt_for_corrections
 7061: 
 7062: Prompts for a potentially multiline correction to the
 7063: user's bubbling (factors out common code from scantron_get_correction
 7064: for multi and missing bubble cases).
 7065: 
 7066:  Arguments:
 7067:    $r           - Apache request object.
 7068:    $question    - The question number to prompt for.
 7069:    $scan_config - The scantron file configuration hash.
 7070:    $scan_record - Reference to the hash that has the the parsed scanlines.
 7071:    $error       - Type of error
 7072: 
 7073:  Implicit inputs:
 7074:    %bubble_lines_per_response   - Starting line numbers for each question.
 7075:                                   Numbered from 0 (but question numbers are from
 7076:                                   1.
 7077:    %first_bubble_line           - Starting bubble line for each question.
 7078:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 7079:                                   type problems render as separate sub-questions, 
 7080:                                   in exam mode. This hash contains a 
 7081:                                   comma-separated list of the lines per 
 7082:                                   sub-question.
 7083:    %responsetype_per_response   - essayresponse, formularesponse,
 7084:                                   stringresponse, imageresponse, reactionresponse,
 7085:                                   and organicresponse type problem parts can have
 7086:                                   multiple lines per response if the weight
 7087:                                   assigned exceeds 10.  In this case, only
 7088:                                   one bubble per line is permitted, but more 
 7089:                                   than one line might contain bubbles, e.g.
 7090:                                   bubbling of: line 1 - J, line 2 - J, 
 7091:                                   line 3 - B would assign 22 points.  
 7092: 
 7093: =cut
 7094: 
 7095: sub prompt_for_corrections {
 7096:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
 7097:     my ($current_line,$lines);
 7098:     my @linenums;
 7099:     my $questionnum = $question;
 7100:     if ($question =~ /^(\d+)\.(\d+)$/) {
 7101:         $question = $1;
 7102:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7103:         my $subquestion = $2;
 7104:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7105:         my $subcount = 1;
 7106:         while ($subcount<$subquestion) {
 7107:             $current_line += $subans[$subcount-1];
 7108:             $subcount ++;
 7109:         }
 7110:         $lines = $subans[$subquestion-1];
 7111:     } else {
 7112:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7113:         $lines        = $bubble_lines_per_response{$question-1};
 7114:     }
 7115:     if ($lines > 1) {
 7116:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 7117:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
 7118:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
 7119:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
 7120:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
 7121:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
 7122:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
 7123:             $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 />');
 7124:         } else {
 7125:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 7126:         }
 7127:     }
 7128:     for (my $i =0; $i < $lines; $i++) {
 7129:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 7130: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
 7131: 	        		  $questionnum,$error,split('', $selected));
 7132:         push(@linenums,$current_line);
 7133: 	$current_line++;
 7134:     }
 7135:     if ($lines > 1) {
 7136: 	$r->print("<hr /><br />");
 7137:     }
 7138:     return @linenums;
 7139: }
 7140: 
 7141: =pod
 7142: 
 7143: =item scantron_bubble_selector
 7144:   
 7145:    Generates the html radiobuttons to correct a single bubble line
 7146:    possibly showing the existing the selected bubbles if known
 7147: 
 7148:  Arguments:
 7149:     $r           - Apache request object
 7150:     $scan_config - hash from &get_scantron_config()
 7151:     $line        - Number of the line being displayed.
 7152:     $questionnum - Question number (may include subquestion)
 7153:     $error       - Type of error.
 7154:     @selected    - Array of bubbles picked on this line.
 7155: 
 7156: =cut
 7157: 
 7158: sub scantron_bubble_selector {
 7159:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 7160:     my $max=$$scan_config{'Qlength'};
 7161: 
 7162:     my $scmode=$$scan_config{'Qon'};
 7163:     if ($scmode eq 'number' || $scmode eq 'letter') { 
 7164:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
 7165:             ($$scan_config{'BubblesPerRow'} > 0)) {
 7166:             $max=$$scan_config{'BubblesPerRow'};
 7167:             if (($scmode eq 'number') && ($max > 10)) {
 7168:                 $max = 10;
 7169:             } elsif (($scmode eq 'letter') && $max > 26) {
 7170:                 $max = 26;
 7171:             }
 7172:         } else {
 7173:             $max = 10;
 7174:         }
 7175:     }
 7176: 
 7177:     my @alphabet=('A'..'Z');
 7178:     $r->print(&Apache::loncommon::start_data_table().
 7179:               &Apache::loncommon::start_data_table_row());
 7180:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 7181:     for (my $i=0;$i<$max+1;$i++) {
 7182: 	$r->print("\n".'<td align="center">');
 7183: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 7184: 	else { $r->print('&nbsp;'); }
 7185: 	$r->print('</td>');
 7186:     }
 7187:     $r->print(&Apache::loncommon::end_data_table_row().
 7188:               &Apache::loncommon::start_data_table_row());
 7189:     for (my $i=0;$i<$max;$i++) {
 7190: 	$r->print("\n".
 7191: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 7192: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 7193:     }
 7194:     my $nobub_checked = ' ';
 7195:     if ($error eq 'missingbubble') {
 7196:         $nobub_checked = ' checked = "checked" ';
 7197:     }
 7198:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 7199: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 7200:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 7201:               $line.'" value="'.$questionnum.'" /></td>');
 7202:     $r->print(&Apache::loncommon::end_data_table_row().
 7203:               &Apache::loncommon::end_data_table());
 7204: }
 7205: 
 7206: =pod
 7207: 
 7208: =item num_matches
 7209: 
 7210:    Counts the number of characters that are the same between the two arguments.
 7211: 
 7212:  Arguments:
 7213:    $orig - CODE from the scanline
 7214:    $code - CODE to match against
 7215: 
 7216:  Returns:
 7217:    $count - integer count of the number of same characters between the
 7218:             two arguments
 7219: 
 7220: =cut
 7221: 
 7222: sub num_matches {
 7223:     my ($orig,$code) = @_;
 7224:     my @code=split(//,$code);
 7225:     my @orig=split(//,$orig);
 7226:     my $same=0;
 7227:     for (my $i=0;$i<scalar(@code);$i++) {
 7228: 	if ($code[$i] eq $orig[$i]) { $same++; }
 7229:     }
 7230:     return $same;
 7231: }
 7232: 
 7233: =pod
 7234: 
 7235: =item scantron_get_closely_matching_CODEs
 7236: 
 7237:    Cycles through all CODEs and finds the set that has the greatest
 7238:    number of same characters as the provided CODE
 7239: 
 7240:  Arguments:
 7241:    $allcodes - hash ref returned by &get_codes()
 7242:    $CODE     - CODE from the current scanline
 7243: 
 7244:  Returns:
 7245:    2 element list
 7246:     - first elements is number of how closely matching the best fit is 
 7247:       (5 means best set has 5 matching characters)
 7248:     - second element is an arrary ref containing the set of valid CODEs
 7249:       that best fit the passed in CODE
 7250: 
 7251: =cut
 7252: 
 7253: sub scantron_get_closely_matching_CODEs {
 7254:     my ($allcodes,$CODE)=@_;
 7255:     my @CODEs;
 7256:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 7257: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 7258:     }
 7259: 
 7260:     return ($#CODEs,$CODEs[-1]);
 7261: }
 7262: 
 7263: =pod
 7264: 
 7265: =item get_codes
 7266: 
 7267:    Builds a hash which has keys of all of the valid CODEs from the selected
 7268:    set of remembered CODEs.
 7269: 
 7270:  Arguments:
 7271:   $old_name - name of the set of remembered CODEs
 7272:   $cdom     - domain of the course
 7273:   $cnum     - internal course name
 7274: 
 7275:  Returns:
 7276:   %allcodes - keys are the valid CODEs, values are all 1
 7277: 
 7278: =cut
 7279: 
 7280: sub get_codes {
 7281:     my ($old_name, $cdom, $cnum) = @_;
 7282:     if (!$old_name) {
 7283: 	$old_name=$env{'form.scantron_CODElist'};
 7284:     }
 7285:     if (!$cdom) {
 7286: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 7287:     }
 7288:     if (!$cnum) {
 7289: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 7290:     }
 7291:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 7292: 				    $cdom,$cnum);
 7293:     my %allcodes;
 7294:     if ($result{"type\0$old_name"} eq 'number') {
 7295: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 7296:     } else {
 7297: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 7298:     }
 7299:     return %allcodes;
 7300: }
 7301: 
 7302: =pod
 7303: 
 7304: =item scantron_validate_CODE
 7305: 
 7306:    Validates all scanlines in the selected file to not have any
 7307:    invalid or underspecified CODEs and that none of the codes are
 7308:    duplicated if this was requested.
 7309: 
 7310: =cut
 7311: 
 7312: sub scantron_validate_CODE {
 7313:     my ($r,$currentphase) = @_;
 7314:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7315:     if ($scantron_config{'CODElocation'} &&
 7316: 	$scantron_config{'CODEstart'} &&
 7317: 	$scantron_config{'CODElength'}) {
 7318: 	if (!defined($env{'form.scantron_CODElist'})) {
 7319: 	    &FIXME_blow_up()
 7320: 	}
 7321:     } else {
 7322: 	return (0,$currentphase+1);
 7323:     }
 7324:     
 7325:     my %usedCODEs;
 7326: 
 7327:     my %allcodes=&get_codes();
 7328: 
 7329:     my $nav_error;
 7330:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
 7331:     if ($nav_error) {
 7332:         $r->print(&navmap_errormsg());
 7333:         return(1,$currentphase);
 7334:     }
 7335: 
 7336:     my ($scanlines,$scan_data)=&scantron_getfile();
 7337:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7338: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7339: 	if ($line=~/^[\s\cz]*$/) { next; }
 7340: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7341: 						 $scan_data);
 7342: 	my $CODE=$$scan_record{'scantron.CODE'};
 7343: 	my $error=0;
 7344: 	if (!&Apache::lonnet::validCODE($CODE)) {
 7345: 	    &scantron_get_correction($r,$i,$scan_record,
 7346: 				     \%scantron_config,
 7347: 				     $line,'incorrectCODE',\%allcodes);
 7348: 	    return(1,$currentphase);
 7349: 	}
 7350: 	if (%allcodes && !exists($allcodes{$CODE}) 
 7351: 	    && !$$scan_record{'scantron.useCODE'}) {
 7352: 	    &scantron_get_correction($r,$i,$scan_record,
 7353: 				     \%scantron_config,
 7354: 				     $line,'incorrectCODE',\%allcodes);
 7355: 	    return(1,$currentphase);
 7356: 	}
 7357: 	if (exists($usedCODEs{$CODE}) 
 7358: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 7359: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 7360: 	    &scantron_get_correction($r,$i,$scan_record,
 7361: 				     \%scantron_config,
 7362: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 7363: 	    return(1,$currentphase);
 7364: 	}
 7365: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 7366:     }
 7367:     return (0,$currentphase+1);
 7368: }
 7369: 
 7370: =pod
 7371: 
 7372: =item scantron_validate_doublebubble
 7373: 
 7374:    Validates all scanlines in the selected file to not have any
 7375:    bubble lines with multiple bubbles marked.
 7376: 
 7377: =cut
 7378: 
 7379: sub scantron_validate_doublebubble {
 7380:     my ($r,$currentphase) = @_;
 7381:     #get student info
 7382:     my $classlist=&Apache::loncoursedata::get_classlist();
 7383:     my %idmap=&username_to_idmap($classlist);
 7384: 
 7385:     #get scantron line setup
 7386:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7387:     my ($scanlines,$scan_data)=&scantron_getfile();
 7388:     my $nav_error;
 7389:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
 7390:     if ($nav_error) {
 7391:         $r->print(&navmap_errormsg());
 7392:         return(1,$currentphase);
 7393:     }
 7394: 
 7395:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7396: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7397: 	if ($line=~/^[\s\cz]*$/) { next; }
 7398: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7399: 						 $scan_data);
 7400: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 7401: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 7402: 				 'doublebubble',
 7403: 				 $$scan_record{'scantron.doubleerror'});
 7404:     	return (1,$currentphase);
 7405:     }
 7406:     return (0,$currentphase+1);
 7407: }
 7408: 
 7409: 
 7410: sub scantron_get_maxbubble {
 7411:     my ($nav_error,$scantron_config) = @_;
 7412:     if (defined($env{'form.scantron_maxbubble'}) &&
 7413: 	$env{'form.scantron_maxbubble'}) {
 7414: 	&restore_bubble_lines();
 7415: 	return $env{'form.scantron_maxbubble'};
 7416:     }
 7417: 
 7418:     my (undef, undef, $sequence) =
 7419: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7420: 
 7421:     my $navmap=Apache::lonnavmaps::navmap->new();
 7422:     unless (ref($navmap)) {
 7423:         if (ref($nav_error)) {
 7424:             $$nav_error = 1;
 7425:         }
 7426:         return;
 7427:     }
 7428:     my $map=$navmap->getResourceByUrl($sequence);
 7429:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7430:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
 7431: 
 7432:     &Apache::lonxml::clear_problem_counter();
 7433: 
 7434:     my $uname       = $env{'user.name'};
 7435:     my $udom        = $env{'user.domain'};
 7436:     my $cid         = $env{'request.course.id'};
 7437:     my $total_lines = 0;
 7438:     %bubble_lines_per_response = ();
 7439:     %first_bubble_line         = ();
 7440:     %subdivided_bubble_lines   = ();
 7441:     %responsetype_per_response = ();
 7442: 
 7443:     my $response_number = 0;
 7444:     my $bubble_line     = 0;
 7445:     foreach my $resource (@resources) {
 7446:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom,undef,$bubbles_per_row);
 7447:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 7448: 	    foreach my $part_id (@{$parts}) {
 7449:                 my $lines;
 7450: 
 7451: 	        # TODO - make this a persistent hash not an array.
 7452: 
 7453:                 # optionresponse, matchresponse and rankresponse type items 
 7454:                 # render as separate sub-questions in exam mode.
 7455:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 7456:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 7457:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 7458:                     my ($numbub,$numshown);
 7459:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 7460:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 7461:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 7462:                         }
 7463:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 7464:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 7465:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 7466:                         }
 7467:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 7468:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 7469:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 7470:                         }
 7471:                     }
 7472:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 7473:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 7474:                     }
 7475:                     my $bubbles_per_row =
 7476:                         &bubblesheet_bubbles_per_row($scantron_config);
 7477:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
 7478:                     if (($numbub % $bubbles_per_row) != 0) {
 7479:                         $inner_bubble_lines++;
 7480:                     }
 7481:                     for (my $i=0; $i<$numshown; $i++) {
 7482:                         $subdivided_bubble_lines{$response_number} .= 
 7483:                             $inner_bubble_lines.',';
 7484:                     }
 7485:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 7486:                     $lines = $numshown * $inner_bubble_lines;
 7487:                 } else {
 7488:                     $lines = $analysis->{"$part_id.bubble_lines"};
 7489:                 }
 7490: 
 7491:                 $first_bubble_line{$response_number} = $bubble_line;
 7492: 	        $bubble_lines_per_response{$response_number} = $lines;
 7493:                 $responsetype_per_response{$response_number} = 
 7494:                     $analysis->{$part_id.'.type'};
 7495: 	        $response_number++;
 7496: 
 7497: 	        $bubble_line +=  $lines;
 7498: 	        $total_lines +=  $lines;
 7499: 	    }
 7500:         }
 7501:     }
 7502:     &Apache::lonnet::delenv('scantron.');
 7503: 
 7504:     &save_bubble_lines();
 7505:     $env{'form.scantron_maxbubble'} =
 7506: 	$total_lines;
 7507:     return $env{'form.scantron_maxbubble'};
 7508: }
 7509: 
 7510: sub bubblesheet_bubbles_per_row {
 7511:     my ($scantron_config) = @_;
 7512:     my $bubbles_per_row;
 7513:     if (ref($scantron_config) eq 'HASH') {
 7514:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
 7515:     }
 7516:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
 7517:         $bubbles_per_row = 10;
 7518:     }
 7519:     return $bubbles_per_row;
 7520: }
 7521: 
 7522: sub scantron_validate_missingbubbles {
 7523:     my ($r,$currentphase) = @_;
 7524:     #get student info
 7525:     my $classlist=&Apache::loncoursedata::get_classlist();
 7526:     my %idmap=&username_to_idmap($classlist);
 7527: 
 7528:     #get scantron line setup
 7529:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7530:     my ($scanlines,$scan_data)=&scantron_getfile();
 7531:     my $nav_error;
 7532:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 7533:     if ($nav_error) {
 7534:         return(1,$currentphase);
 7535:     }
 7536:     if (!$max_bubble) { $max_bubble=2**31; }
 7537:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7538: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7539: 	if ($line=~/^[\s\cz]*$/) { next; }
 7540: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7541: 						 $scan_data);
 7542: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 7543: 	my @to_correct;
 7544: 	
 7545: 	# Probably here's where the error is...
 7546: 
 7547: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 7548:             my $lastbubble;
 7549:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 7550:                my $question = $1;
 7551:                my $subquestion = $2;
 7552:                if (!defined($first_bubble_line{$question -1})) { next; }
 7553:                my $first = $first_bubble_line{$question-1};
 7554:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7555:                my $subcount = 1;
 7556:                while ($subcount<$subquestion) {
 7557:                    $first += $subans[$subcount-1];
 7558:                    $subcount ++;
 7559:                }
 7560:                my $count = $subans[$subquestion-1];
 7561:                $lastbubble = $first + $count;
 7562:             } else {
 7563:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
 7564:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
 7565:             }
 7566:             if ($lastbubble > $max_bubble) { next; }
 7567: 	    push(@to_correct,$missing);
 7568: 	}
 7569: 	if (@to_correct) {
 7570: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7571: 				     $line,'missingbubble',\@to_correct);
 7572: 	    return (1,$currentphase);
 7573: 	}
 7574: 
 7575:     }
 7576:     return (0,$currentphase+1);
 7577: }
 7578: 
 7579: 
 7580: sub scantron_process_students {
 7581:     my ($r,$symb) = @_;
 7582: 
 7583:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7584:     if (!$symb) {
 7585: 	return '';
 7586:     }
 7587:     my $default_form_data=&defaultFormData($symb);
 7588: 
 7589:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7590:     my $bubbles_per_row =
 7591:         &bubblesheet_bubbles_per_row(\%scantron_config);
 7592:     my ($scanlines,$scan_data)=&scantron_getfile();
 7593:     my $classlist=&Apache::loncoursedata::get_classlist();
 7594:     my %idmap=&username_to_idmap($classlist);
 7595:     my $navmap=Apache::lonnavmaps::navmap->new();
 7596:     unless (ref($navmap)) {
 7597:         $r->print(&navmap_errormsg());
 7598:         return '';
 7599:     }  
 7600:     my $map=$navmap->getResourceByUrl($sequence);
 7601:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7602:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
 7603:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 7604:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 7605:     my $resource_error;
 7606:     foreach my $resource (@resources) {
 7607:         my $ressymb;
 7608:         if (ref($resource)) {
 7609:             $ressymb = $resource->symb();
 7610:         } else {
 7611:             $resource_error = 1;
 7612:             last;
 7613:         }
 7614:         my ($analysis,$parts) =
 7615:             &scantron_partids_tograde($resource,$env{'request.course.id'},
 7616:                                       $env{'user.name'},$env{'user.domain'},1,$bubbles_per_row);
 7617:         $grader_partids_by_symb{$ressymb} = $parts;
 7618:         if (ref($analysis) eq 'HASH') {
 7619:             if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 7620:                 $grader_randomlists_by_symb{$ressymb} = 
 7621:                     $analysis->{'parts_withrandomlist'};
 7622:             }
 7623:         }
 7624:     }
 7625:     if ($resource_error) {
 7626:         $r->print(&navmap_errormsg());
 7627:         return '';
 7628:     }
 7629: 
 7630:     my ($uname,$udom);
 7631:     my $result= <<SCANTRONFORM;
 7632: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 7633:   <input type="hidden" name="command" value="scantron_configphase" />
 7634:   $default_form_data
 7635: SCANTRONFORM
 7636:     $r->print($result);
 7637: 
 7638:     my @delayqueue;
 7639:     my (%completedstudents,%scandata);
 7640:     
 7641:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 7642:     my $count=&get_todo_count($scanlines,$scan_data);
 7643:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet Status',
 7644:  				    'Bubblesheet Progress',$count,
 7645: 				    'inline',undef,'scantronupload');
 7646:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 7647: 					  'Processing first student');
 7648:     $r->print('<br />');
 7649:     my $start=&Time::HiRes::time();
 7650:     my $i=-1;
 7651:     my $started;
 7652: 
 7653:     my $nav_error;
 7654:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 7655:     if ($nav_error) {
 7656:         $r->print(&navmap_errormsg());
 7657:         return '';
 7658:     }
 7659: 
 7660:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 7661:     # the user and return.
 7662: 
 7663:     if ($ssi_error) {
 7664: 	$r->print("</form>");
 7665: 	&ssi_print_error($r);
 7666:         &Apache::lonnet::remove_lock($lock);
 7667: 	return '';		# Dunno why the other returns return '' rather than just returning.
 7668:     }
 7669: 
 7670:     my %lettdig = &letter_to_digits();
 7671:     my $numletts = scalar(keys(%lettdig));
 7672: 
 7673:     while ($i<$scanlines->{'count'}) {
 7674:  	($uname,$udom)=('','');
 7675:  	$i++;
 7676:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7677:  	if ($line=~/^[\s\cz]*$/) { next; }
 7678: 	if ($started) {
 7679: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 7680: 						     'last student');
 7681: 	}
 7682: 	$started=1;
 7683:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7684:  						 $scan_data);
 7685:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 7686:  					      \%idmap,$i)) {
 7687:   	    &scantron_add_delay(\@delayqueue,$line,
 7688:  				'Unable to find a student that matches',1);
 7689:  	    next;
 7690:   	}
 7691:  	if (exists $completedstudents{$uname}) {
 7692:  	    &scantron_add_delay(\@delayqueue,$line,
 7693:  				'Student '.$uname.' has multiple sheets',2);
 7694:  	    next;
 7695:  	}
 7696:   	($uname,$udom)=split(/:/,$uname);
 7697: 
 7698:         my (%partids_by_symb,$res_error);
 7699:         foreach my $resource (@resources) {
 7700:             my $ressymb;
 7701:             if (ref($resource)) {
 7702:                 $ressymb = $resource->symb();
 7703:             } else {
 7704:                 $res_error = 1;
 7705:                 last;
 7706:             }
 7707:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 7708:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 7709:                 my ($analysis,$parts) =
 7710:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom,undef,$bubbles_per_row);
 7711:                 $partids_by_symb{$ressymb} = $parts;
 7712:             } else {
 7713:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
 7714:             }
 7715:         }
 7716: 
 7717:         if ($res_error) {
 7718:             &scantron_add_delay(\@delayqueue,$line,
 7719:                                 'An error occurred while grading student '.$uname,2);
 7720:             next;
 7721:         }
 7722: 
 7723: 	&Apache::lonxml::clear_problem_counter();
 7724:   	&Apache::lonnet::appenv($scan_record);
 7725: 
 7726: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 7727: 	    &scantron_putfile($scanlines,$scan_data);
 7728: 	}
 7729: 	
 7730:         my $scancode;
 7731:         if ((exists($scan_record->{'scantron.CODE'})) &&
 7732:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 7733:             $scancode = $scan_record->{'scantron.CODE'};
 7734:         } else {
 7735:             $scancode = '';
 7736:         }
 7737: 
 7738:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 7739:                                    \@resources,\%partids_by_symb,
 7740:                                    $bubbles_per_row) eq 'ssi_error') {
 7741:             $ssi_error = 0; # So end of handler error message does not trigger.
 7742:             $r->print("</form>");
 7743:             &ssi_print_error($r);
 7744:             &Apache::lonnet::remove_lock($lock);
 7745:             return '';      # Why return ''?  Beats me.
 7746:         }
 7747: 
 7748: 	$completedstudents{$uname}={'line'=>$line};
 7749:         if ($env{'form.verifyrecord'}) {
 7750:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 7751:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 7752:             chomp($studentdata);
 7753:             $studentdata =~ s/\r$//;
 7754:             my $studentrecord = '';
 7755:             my $counter = -1;
 7756:             foreach my $resource (@resources) {
 7757:                 my $ressymb = $resource->symb();
 7758:                 ($counter,my $recording) =
 7759:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 7760:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
 7761:                                              \%scantron_config,\%lettdig,$numletts);
 7762:                 $studentrecord .= $recording;
 7763:             }
 7764:             if ($studentrecord ne $studentdata) {
 7765:                 &Apache::lonxml::clear_problem_counter();
 7766:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 7767:                                            \@resources,\%partids_by_symb,
 7768:                                            $bubbles_per_row) eq 'ssi_error') {
 7769:                     $ssi_error = 0; # So end of handler error message does not trigger.
 7770:                     $r->print("</form>");
 7771:                     &ssi_print_error($r);
 7772:                     &Apache::lonnet::remove_lock($lock);
 7773:                     delete($completedstudents{$uname});
 7774:                     return '';
 7775:                 }
 7776:                 $counter = -1;
 7777:                 $studentrecord = '';
 7778:                 foreach my $resource (@resources) {
 7779:                     my $ressymb = $resource->symb();
 7780:                     ($counter,my $recording) =
 7781:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 7782:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 7783:                                                  \%scantron_config,\%lettdig,$numletts);
 7784:                     $studentrecord .= $recording;
 7785:                 }
 7786:                 if ($studentrecord ne $studentdata) {
 7787:                     $r->print('<p><span class="LC_error">');
 7788:                     if ($scancode eq '') {
 7789:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2].',
 7790:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 7791:                     } else {
 7792:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2] and CODE: [_3].',
 7793:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 7794:                     }
 7795:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 7796:                               &Apache::loncommon::start_data_table_header_row()."\n".
 7797:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 7798:                               &Apache::loncommon::end_data_table_header_row()."\n".
 7799:                               &Apache::loncommon::start_data_table_row().
 7800:                               '<td>'.&mt('Bubble Sheet').'</td>'.
 7801:                               '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
 7802:                               &Apache::loncommon::end_data_table_row().
 7803:                               &Apache::loncommon::start_data_table_row().
 7804:                               '<td>Stored submissions</td>'.
 7805:                               '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
 7806:                               &Apache::loncommon::end_data_table_row().
 7807:                               &Apache::loncommon::end_data_table().'</p>');
 7808:                 } else {
 7809:                     $r->print('<br /><span class="LC_warning">'.
 7810:                              &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 />'.
 7811:                              &mt("As a consequence, this user's submission history records two tries.").
 7812:                                  '</span><br />');
 7813:                 }
 7814:             }
 7815:         }
 7816:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 7817:     } continue {
 7818: 	&Apache::lonxml::clear_problem_counter();
 7819: 	&Apache::lonnet::delenv('scantron.');
 7820:     }
 7821:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 7822:     &Apache::lonnet::remove_lock($lock);
 7823: #    my $lasttime = &Time::HiRes::time()-$start;
 7824: #    $r->print("<p>took $lasttime</p>");
 7825: 
 7826:     $r->print("</form>");
 7827:     return '';
 7828: }
 7829: 
 7830: sub graders_resources_pass {
 7831:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
 7832:         $bubbles_per_row) = @_;
 7833:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
 7834:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
 7835:         foreach my $resource (@{$resources}) {
 7836:             my $ressymb = $resource->symb();
 7837:             my ($analysis,$parts) =
 7838:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
 7839:                                           $env{'user.name'},$env{'user.domain'},1,$bubbles_per_row);
 7840:             $grader_partids_by_symb->{$ressymb} = $parts;
 7841:             if (ref($analysis) eq 'HASH') {
 7842:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 7843:                     $grader_randomlists_by_symb->{$ressymb} =
 7844:                         $analysis->{'parts_withrandomlist'};
 7845:                 }
 7846:             }
 7847:         }
 7848:     }
 7849:     return;
 7850: }
 7851: 
 7852: sub grade_student_bubbles {
 7853:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row) = @_;
 7854: # Walk folder as student here to get resources in order student sees.
 7855:     if (ref($resources) eq 'ARRAY') {
 7856:         my $count = 0;
 7857:         foreach my $resource (@{$resources}) {
 7858:             my $ressymb = $resource->symb();
 7859:             my %form = ('submitted'      => 'scantron',
 7860:                         'grade_target'   => 'grade',
 7861:                         'grade_username' => $uname,
 7862:                         'grade_domain'   => $udom,
 7863:                         'grade_courseid' => $env{'request.course.id'},
 7864:                         'grade_symb'     => $ressymb,
 7865:                         'CODE'           => $scancode
 7866:                        );
 7867:             if ($bubbles_per_row ne '') {
 7868:                 $form{'bubbles_per_row'} = $bubbles_per_row;
 7869:             }
 7870:             if (ref($parts) eq 'HASH') {
 7871:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 7872:                     foreach my $part (@{$parts->{$ressymb}}) {
 7873:                         $form{'scantron_questnum_start.'.$part} =
 7874:                             1+$env{'form.scantron.first_bubble_line.'.$count};
 7875:                         $count++;
 7876:                     }
 7877:                 }
 7878:             }
 7879:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 7880:             return 'ssi_error' if ($ssi_error);
 7881:             last if (&Apache::loncommon::connection_aborted($r));
 7882:         }
 7883:     }
 7884:     return;
 7885: }
 7886: 
 7887: sub scantron_upload_scantron_data {
 7888:     my ($r,$symb)=@_;
 7889:     my $dom = $env{'request.role.domain'};
 7890:     my $domdesc = &Apache::lonnet::domain($dom,'description');
 7891:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
 7892:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 7893: 							  'domainid',
 7894: 							  'coursename',$dom);
 7895:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
 7896:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
 7897:     my $default_form_data=&defaultFormData($symb);
 7898:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
 7899:     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.");
 7900:     $r->print(&Apache::lonhtmlcommon::scripttag('
 7901:     function checkUpload(formname) {
 7902: 	if (formname.upfile.value == "") {
 7903: 	    alert("'.$nofile_alert.'");
 7904: 	    return false;
 7905: 	}
 7906:         if (formname.courseid.value == "") {
 7907:             alert("'.$nocourseid_alert.'");
 7908:             return false;
 7909:         }
 7910: 	formname.submit();
 7911:     }
 7912: 
 7913:     function ToSyllabus() {
 7914:         var cdom = '."'$dom'".';
 7915:         var cnum = document.rules.courseid.value;
 7916:         if (cdom == "" || cdom == null) {
 7917:             return;
 7918:         }
 7919:         if (cnum == "" || cnum == null) {
 7920:            return;
 7921:         }
 7922:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
 7923:                             "height=350,width=350,scrollbars=yes,menubar=no");
 7924:         return;
 7925:     }
 7926: 
 7927: '));
 7928:     $r->print('
 7929: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
 7930: 
 7931: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 7932: '.$default_form_data.
 7933:   &Apache::lonhtmlcommon::start_pick_box().
 7934:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
 7935:   '<input name="courseid" type="text" size="30" />'.$select_link.
 7936:   &Apache::lonhtmlcommon::row_closure().
 7937:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
 7938:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
 7939:   &Apache::lonhtmlcommon::row_closure().
 7940:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
 7941:   '<input name="domainid" type="hidden" />'.$domdesc.
 7942:   &Apache::lonhtmlcommon::row_closure().
 7943:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
 7944:   '<input type="file" name="upfile" size="50" />'.
 7945:   &Apache::lonhtmlcommon::row_closure(1).
 7946:   &Apache::lonhtmlcommon::end_pick_box().'<br />
 7947: 
 7948: <input name="command" value="scantronupload_save" type="hidden" />
 7949: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 7950: </form>
 7951: ');
 7952:     return '';
 7953: }
 7954: 
 7955: 
 7956: sub scantron_upload_scantron_data_save {
 7957:     my($r,$symb)=@_;
 7958:     my $doanotherupload=
 7959: 	'<br /><form action="/adm/grades" method="post">'."\n".
 7960: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 7961: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 7962: 	'</form>'."\n";
 7963:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 7964: 	!&Apache::lonnet::allowed('usc',
 7965: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 7966: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
 7967: 	unless ($symb) {
 7968: 	    $r->print($doanotherupload);
 7969: 	}
 7970: 	return '';
 7971:     }
 7972:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 7973:     my $uploadedfile;
 7974:     $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
 7975:     if (length($env{'form.upfile'}) < 2) {
 7976:         $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>'));
 7977:     } else {
 7978:         my $result = 
 7979:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
 7980:                                             $env{'form.courseid'},$env{'form.domainid'});
 7981: 	if ($result =~ m{^/uploaded/}) {
 7982: 	    $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
 7983:                           '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
 7984: 			  '<span class="LC_filename">'.$result.'</span>'));
 7985:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
 7986:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
 7987:                                                        $env{'form.courseid'},$uploadedfile));
 7988: 	} else {
 7989: 	    $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
 7990:                           '<span class="LC_error">','</span>',$result,
 7991: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 7992: 	}
 7993:     }
 7994:     if ($symb) {
 7995: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
 7996:     } else {
 7997: 	$r->print($doanotherupload);
 7998:     }
 7999:     return '';
 8000: }
 8001: 
 8002: sub validate_uploaded_scantron_file {
 8003:     my ($cdom,$cname,$fname) = @_;
 8004:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
 8005:     my @lines;
 8006:     if ($scanlines ne '-1') {
 8007:         @lines=split("\n",$scanlines,-1);
 8008:     }
 8009:     my $output;
 8010:     if (@lines) {
 8011:         my (%counts,$max_match_format);
 8012:         my ($max_match_count,$max_match_pct) = (0,0);
 8013:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
 8014:         my %idmap = &username_to_idmap($classlist);
 8015:         foreach my $key (keys(%idmap)) {
 8016:             my $lckey = lc($key);
 8017:             $idmap{$lckey} = $idmap{$key};
 8018:         }
 8019:         my %unique_formats;
 8020:         my @formatlines = &get_scantronformat_file();
 8021:         foreach my $line (@formatlines) {
 8022:             chomp($line);
 8023:             my @config = split(/:/,$line);
 8024:             my $idstart = $config[5];
 8025:             my $idlength = $config[6];
 8026:             if (($idstart ne '') && ($idlength > 0)) {
 8027:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
 8028:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
 8029:                 } else {
 8030:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
 8031:                 }
 8032:             }
 8033:         }
 8034:         foreach my $key (keys(%unique_formats)) {
 8035:             my ($idstart,$idlength) = split(':',$key);
 8036:             %{$counts{$key}} = (
 8037:                                'found'   => 0,
 8038:                                'total'   => 0,
 8039:                               );
 8040:             foreach my $line (@lines) {
 8041:                 next if ($line =~ /^#/);
 8042:                 next if ($line =~ /^[\s\cz]*$/);
 8043:                 my $id = substr($line,$idstart-1,$idlength);
 8044:                 $id = lc($id);
 8045:                 if (exists($idmap{$id})) {
 8046:                     $counts{$key}{'found'} ++;
 8047:                 }
 8048:                 $counts{$key}{'total'} ++;
 8049:             }
 8050:             if ($counts{$key}{'total'}) {
 8051:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
 8052:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
 8053:                     $max_match_pct = $percent_match;
 8054:                     $max_match_format = $key;
 8055:                     $max_match_count = $counts{$key}{'total'};
 8056:                 }
 8057:             }
 8058:         }
 8059:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
 8060:             my $format_descs;
 8061:             my $numwithformat = @{$unique_formats{$max_match_format}};
 8062:             for (my $i=0; $i<$numwithformat; $i++) {
 8063:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
 8064:                 if ($i<$numwithformat-2) {
 8065:                     $format_descs .= '"<i>'.$desc.'</i>", ';
 8066:                 } elsif ($i==$numwithformat-2) {
 8067:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
 8068:                 } elsif ($i==$numwithformat-1) {
 8069:                     $format_descs .= '"<i>'.$desc.'</i>"';
 8070:                 }
 8071:             }
 8072:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
 8073:             $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).
 8074:                        '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
 8075:                        '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
 8076:                        '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
 8077:                                   '<i>'.$cdom.'</i>').'</li>'.
 8078:                        '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
 8079:                        '<li>'.&mt('The course roster is not up to date').'</li>'.
 8080:                        '</ul>';
 8081:         }
 8082:     } else {
 8083:         $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
 8084:     }
 8085:     return $output;
 8086: }
 8087: 
 8088: sub valid_file {
 8089:     my ($requested_file)=@_;
 8090:     foreach my $filename (sort(&scantron_filenames())) {
 8091: 	if ($requested_file eq $filename) { return 1; }
 8092:     }
 8093:     return 0;
 8094: }
 8095: 
 8096: sub scantron_download_scantron_data {
 8097:     my ($r,$symb)=@_;
 8098:     my $default_form_data=&defaultFormData($symb);
 8099:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 8100:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8101:     my $file=$env{'form.scantron_selectfile'};
 8102:     if (! &valid_file($file)) {
 8103: 	$r->print('
 8104: 	<p>
 8105: 	    '.&mt('The requested file name was invalid.').'
 8106:         </p>
 8107: ');
 8108: 	return;
 8109:     }
 8110:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 8111:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 8112:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 8113:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 8114:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 8115:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 8116:     $r->print('
 8117:     <p>
 8118: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
 8119: 	      '<a href="'.$orig.'">','</a>').'
 8120:     </p>
 8121:     <p>
 8122: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 8123: 	      '<a href="'.$corrected.'">','</a>').'
 8124:     </p>
 8125:     <p>
 8126: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 8127: 	      '<a href="'.$skipped.'">','</a>').'
 8128:     </p>
 8129: ');
 8130:     return '';
 8131: }
 8132: 
 8133: sub checkscantron_results {
 8134:     my ($r,$symb) = @_;
 8135:     if (!$symb) {return '';}
 8136:     my $cid = $env{'request.course.id'};
 8137:     my %lettdig = &letter_to_digits();
 8138:     my $numletts = scalar(keys(%lettdig));
 8139:     my $cnum = $env{'course.'.$cid.'.num'};
 8140:     my $cdom = $env{'course.'.$cid.'.domain'};
 8141:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8142:     my %record;
 8143:     my %scantron_config =
 8144:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
 8145:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8146:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
 8147:     my $classlist=&Apache::loncoursedata::get_classlist();
 8148:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 8149:     my $navmap=Apache::lonnavmaps::navmap->new();
 8150:     unless (ref($navmap)) {
 8151:         $r->print(&navmap_errormsg());
 8152:         return '';
 8153:     }
 8154:     my $map=$navmap->getResourceByUrl($sequence);
 8155:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8156:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
 8157:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,                             \%grader_randomlists_by_symb);
 8158: 
 8159:     my ($uname,$udom);
 8160:     my (%scandata,%lastname,%bylast);
 8161:     $r->print('
 8162: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 8163: 
 8164:     my @delayqueue;
 8165:     my %completedstudents;
 8166: 
 8167:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
 8168:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet/Submissions Comparison Status',
 8169:                                     'Progress of Bubblesheet Data/Submission Records Comparison',$count,
 8170:                                     'inline',undef,'checkscantron');
 8171:     my ($username,$domain,$started);
 8172:     my $nav_error;
 8173:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 8174:     if ($nav_error) {
 8175:         $r->print(&navmap_errormsg());
 8176:         return '';
 8177:     }
 8178: 
 8179:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 8180:                                           'Processing first student');
 8181:     my $start=&Time::HiRes::time();
 8182:     my $i=-1;
 8183: 
 8184:     while ($i<$scanlines->{'count'}) {
 8185:         ($username,$domain,$uname)=('','','');
 8186:         $i++;
 8187:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 8188:         if ($line=~/^[\s\cz]*$/) { next; }
 8189:         if ($started) {
 8190:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 8191:                                                      'last student');
 8192:         }
 8193:         $started=1;
 8194:         my $scan_record=
 8195:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 8196:                                                      $scan_data);
 8197:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
 8198:                                                               \%idmap,$i)) {
 8199:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 8200:                                 'Unable to find a student that matches',1);
 8201:             next;
 8202:         }
 8203:         if (exists $completedstudents{$uname}) {
 8204:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 8205:                                 'Student '.$uname.' has multiple sheets',2);
 8206:             next;
 8207:         }
 8208:         my $pid = $scan_record->{'scantron.ID'};
 8209:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 8210:         push(@{$bylast{$lastname{$pid}}},$pid);
 8211:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 8212:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 8213:         chomp($scandata{$pid});
 8214:         $scandata{$pid} =~ s/\r$//;
 8215:         ($username,$domain)=split(/:/,$uname);
 8216:         my $counter = -1;
 8217:         foreach my $resource (@resources) {
 8218:             my $parts;
 8219:             my $ressymb = $resource->symb();
 8220:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 8221:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 8222:                 (my $analysis,$parts) =
 8223:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$username,$domain,undef,$bubbles_per_row);
 8224:             } else {
 8225:                 $parts = $grader_partids_by_symb{$ressymb};
 8226:             }
 8227:             ($counter,my $recording) =
 8228:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
 8229:                                          $scandata{$pid},$parts,
 8230:                                          \%scantron_config,\%lettdig,$numletts);
 8231:             $record{$pid} .= $recording;
 8232:         }
 8233:     }
 8234:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 8235:     $r->print('<br />');
 8236:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 8237:     $passed = 0;
 8238:     $failed = 0;
 8239:     $numstudents = 0;
 8240:     foreach my $last (sort(keys(%bylast))) {
 8241:         if (ref($bylast{$last}) eq 'ARRAY') {
 8242:             foreach my $pid (sort(@{$bylast{$last}})) {
 8243:                 my $showscandata = $scandata{$pid};
 8244:                 my $showrecord = $record{$pid};
 8245:                 $showscandata =~ s/\s/&nbsp;/g;
 8246:                 $showrecord =~ s/\s/&nbsp;/g;
 8247:                 if ($scandata{$pid} eq $record{$pid}) {
 8248:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 8249:                     $okstudents .= '<tr class="'.$css_class.'">'.
 8250: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 8251: '</tr>'."\n".
 8252: '<tr class="'.$css_class.'">'."\n".
 8253: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
 8254:                     $passed ++;
 8255:                 } else {
 8256:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
 8257:                     $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".
 8258: '</tr>'."\n".
 8259: '<tr class="'.$css_class.'">'."\n".
 8260: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
 8261: '</tr>'."\n";
 8262:                     $failed ++;
 8263:                 }
 8264:                 $numstudents ++;
 8265:             }
 8266:         }
 8267:     }
 8268:     $r->print(
 8269:         '<p>'
 8270:        .&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).',
 8271:             '<b>',
 8272:             $numstudents,
 8273:             '</b>',
 8274:             $env{'form.scantron_maxbubble'})
 8275:        .'</p>'
 8276:     );
 8277:     $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>');
 8278:     if ($passed) {
 8279:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
 8280:         $r->print(&Apache::loncommon::start_data_table()."\n".
 8281:                  &Apache::loncommon::start_data_table_header_row()."\n".
 8282:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 8283:                  &Apache::loncommon::end_data_table_header_row()."\n".
 8284:                  $okstudents."\n".
 8285:                  &Apache::loncommon::end_data_table().'<br />');
 8286:     }
 8287:     if ($failed) {
 8288:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
 8289:         $r->print(&Apache::loncommon::start_data_table()."\n".
 8290:                  &Apache::loncommon::start_data_table_header_row()."\n".
 8291:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 8292:                  &Apache::loncommon::end_data_table_header_row()."\n".
 8293:                  $badstudents."\n".
 8294:                  &Apache::loncommon::end_data_table()).'<br />'.
 8295:                  &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.');  
 8296:     }
 8297:     $r->print('</form><br />');
 8298:     return;
 8299: }
 8300: 
 8301: sub verify_scantron_grading {
 8302:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
 8303:         $scantron_config,$lettdig,$numletts) = @_;
 8304:     my ($record,%expected,%startpos);
 8305:     return ($counter,$record) if (!ref($resource));
 8306:     return ($counter,$record) if (!$resource->is_problem());
 8307:     my $symb = $resource->symb();
 8308:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
 8309:     foreach my $part_id (@{$partids}) {
 8310:         $counter ++;
 8311:         $expected{$part_id} = 0;
 8312:         if ($env{"form.scantron.sub_bubblelines.$counter"}) {
 8313:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
 8314:             foreach my $item (@sub_lines) {
 8315:                 $expected{$part_id} += $item;
 8316:             }
 8317:         } else {
 8318:             $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
 8319:         }
 8320:         $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
 8321:     }
 8322:     if ($symb) {
 8323:         my %recorded;
 8324:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
 8325:         if ($returnhash{'version'}) {
 8326:             my %lasthash=();
 8327:             my $version;
 8328:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 8329:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 8330:                     $lasthash{$key}=$returnhash{$version.':'.$key};
 8331:                 }
 8332:             }
 8333:             foreach my $key (keys(%lasthash)) {
 8334:                 if ($key =~ /\.scantron$/) {
 8335:                     my $value = &unescape($lasthash{$key});
 8336:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
 8337:                     if ($value eq '') {
 8338:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
 8339:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
 8340:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8341:                             }
 8342:                         }
 8343:                     } else {
 8344:                         my @tocheck;
 8345:                         my @items = split(//,$value);
 8346:                         if (($scantron_config->{'Qon'} eq 'letter') ||
 8347:                             ($scantron_config->{'Qon'} eq 'number')) {
 8348:                             if (@items < $expected{$part_id}) {
 8349:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
 8350:                                 my @singles = split(//,$fragment);
 8351:                                 foreach my $pos (@singles) {
 8352:                                     if ($pos eq ' ') {
 8353:                                         push(@tocheck,$pos);
 8354:                                     } else {
 8355:                                         my $next = shift(@items);
 8356:                                         push(@tocheck,$next);
 8357:                                     }
 8358:                                 }
 8359:                             } else {
 8360:                                 @tocheck = @items;
 8361:                             }
 8362:                             foreach my $letter (@tocheck) {
 8363:                                 if ($scantron_config->{'Qon'} eq 'letter') {
 8364:                                     if ($letter !~ /^[A-J]$/) {
 8365:                                         $letter = $scantron_config->{'Qoff'};
 8366:                                     }
 8367:                                     $recorded{$part_id} .= $letter;
 8368:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
 8369:                                     my $digit;
 8370:                                     if ($letter !~ /^[A-J]$/) {
 8371:                                         $digit = $scantron_config->{'Qoff'};
 8372:                                     } else {
 8373:                                         $digit = $lettdig->{$letter};
 8374:                                     }
 8375:                                     $recorded{$part_id} .= $digit;
 8376:                                 }
 8377:                             }
 8378:                         } else {
 8379:                             @tocheck = @items;
 8380:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
 8381:                                 my $curr_sub = shift(@tocheck);
 8382:                                 my $digit;
 8383:                                 if ($curr_sub =~ /^[A-J]$/) {
 8384:                                     $digit = $lettdig->{$curr_sub}-1;
 8385:                                 }
 8386:                                 if ($curr_sub eq 'J') {
 8387:                                     $digit += scalar($numletts);
 8388:                                 }
 8389:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 8390:                                     if ($j == $digit) {
 8391:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
 8392:                                     } else {
 8393:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8394:                                     }
 8395:                                 }
 8396:                             }
 8397:                         }
 8398:                     }
 8399:                 }
 8400:             }
 8401:         }
 8402:         foreach my $part_id (@{$partids}) {
 8403:             if ($recorded{$part_id} eq '') {
 8404:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
 8405:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 8406:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8407:                     }
 8408:                 }
 8409:             }
 8410:             $record .= $recorded{$part_id};
 8411:         }
 8412:     }
 8413:     return ($counter,$record);
 8414: }
 8415: 
 8416: sub letter_to_digits { 
 8417:     my %lettdig = (
 8418:                     A => 1,
 8419:                     B => 2,
 8420:                     C => 3,
 8421:                     D => 4,
 8422:                     E => 5,
 8423:                     F => 6,
 8424:                     G => 7,
 8425:                     H => 8,
 8426:                     I => 9,
 8427:                     J => 0,
 8428:                   );
 8429:     return %lettdig;
 8430: }
 8431: 
 8432: 
 8433: #-------- end of section for handling grading scantron forms -------
 8434: #
 8435: #-------------------------------------------------------------------
 8436: 
 8437: #-------------------------- Menu interface -------------------------
 8438: #
 8439: #--- Href with symb and command ---
 8440: 
 8441: sub href_symb_cmd {
 8442:     my ($symb,$cmd)=@_;
 8443:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&command='.$cmd;
 8444: }
 8445: 
 8446: sub grading_menu {
 8447:     my ($request,$symb) = @_;
 8448:     if (!$symb) {return '';}
 8449: 
 8450:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 8451:                   'command'=>'individual');
 8452:     
 8453:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8454: 
 8455:     $fields{'command'}='ungraded';
 8456:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8457: 
 8458:     $fields{'command'}='table';
 8459:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8460: 
 8461:     $fields{'command'}='all_for_one';
 8462:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8463: 
 8464:     $fields{'command'}='downloadfilesselect';
 8465:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8466: 
 8467:     $fields{'command'} = 'csvform';
 8468:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8469:     
 8470:     $fields{'command'} = 'processclicker';
 8471:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8472:     
 8473:     $fields{'command'} = 'scantron_selectphase';
 8474:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8475: 
 8476:     $fields{'command'} = 'initialverifyreceipt';
 8477:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8478:     
 8479:     my @menu = ({	categorytitle=>'Hand Grading',
 8480:             items =>[
 8481:                         {	linktext => 'Select individual students to grade',
 8482:                     		url => $url1a,
 8483:                     		permission => 'F',
 8484:                     		icon => 'grade_students.png',
 8485:                     		linktitle => 'Grade current resource for a selection of students.'
 8486:                         }, 
 8487:                         {       linktext => 'Grade ungraded submissions.',
 8488:                                 url => $url1b,
 8489:                                 permission => 'F',
 8490:                                 icon => 'ungrade_sub.png',
 8491:                                 linktitle => 'Grade all submissions that have not been graded yet.'
 8492:                         },
 8493: 
 8494:                         {       linktext => 'Grading table',
 8495:                                 url => $url1c,
 8496:                                 permission => 'F',
 8497:                                 icon => 'grading_table.png',
 8498:                                 linktitle => 'Grade current resource for all students.'
 8499:                         },
 8500:                         {       linktext => 'Grade page/folder for one student',
 8501:                                 url => $url1d,
 8502:                                 permission => 'F',
 8503:                                 icon => 'grade_PageFolder.png',
 8504:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
 8505:                         },
 8506:                         {       linktext => 'Download submissions',
 8507:                                 url => $url1e,
 8508:                                 permission => 'F',
 8509:                                 icon => 'download_sub.png',
 8510:                                 linktitle => 'Download all students submissions.'
 8511:                         }]},
 8512:                          { categorytitle=>'Automated Grading',
 8513:                items =>[
 8514: 
 8515:                 	    {	linktext => 'Upload Scores',
 8516:                     		url => $url2,
 8517:                     		permission => 'F',
 8518:                     		icon => 'uploadscores.png',
 8519:                     		linktitle => 'Specify a file containing the class scores for current resource.'
 8520:                 	    },
 8521:                 	    {	linktext => 'Process Clicker',
 8522:                     		url => $url3,
 8523:                     		permission => 'F',
 8524:                     		icon => 'addClickerInfoFile.png',
 8525:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
 8526:                 	    },
 8527:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
 8528:                     		url => $url4,
 8529:                     		permission => 'F',
 8530:                     		icon => 'bubblesheet.png',
 8531:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
 8532:                 	    },
 8533:                             {   linktext => 'Verify Receipt Number',
 8534:                                 url => $url5,
 8535:                                 permission => 'F',
 8536:                                 icon => 'receipt_number.png',
 8537:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
 8538:                             }
 8539: 
 8540:                     ]
 8541:             });
 8542: 
 8543:     # Create the menu
 8544:     my $Str;
 8545:     $Str .= '<form method="post" action="" name="gradingMenu">';
 8546:     $Str .= '<input type="hidden" name="command" value="" />'.
 8547:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 8548: 
 8549:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
 8550:     return $Str;    
 8551: }
 8552: 
 8553: 
 8554: sub ungraded {
 8555:     my ($request)=@_;
 8556:     &submit_options($request);
 8557: }
 8558: 
 8559: sub submit_options_sequence {
 8560:     my ($request,$symb) = @_;
 8561:     if (!$symb) {return '';}
 8562:     &commonJSfunctions($request);
 8563:     my $result;
 8564: 
 8565:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8566:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 8567:     $result.=&selectfield(0).
 8568:             '<input type="hidden" name="command" value="pickStudentPage" />
 8569:             <div>
 8570:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 8571:             </div>
 8572:         </div>
 8573:   </form>';
 8574:     return $result;
 8575: }
 8576: 
 8577: sub submit_options_table {
 8578:     my ($request,$symb) = @_;
 8579:     if (!$symb) {return '';}
 8580:     &commonJSfunctions($request);
 8581:     my $result;
 8582: 
 8583:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8584:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 8585: 
 8586:     $result.=&selectfield(0).
 8587:             '<input type="hidden" name="command" value="viewgrades" />
 8588:             <div>
 8589:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 8590:             </div>
 8591:         </div>
 8592:   </form>';
 8593:     return $result;
 8594: }
 8595: 
 8596: sub submit_options_download {
 8597:     my ($request,$symb) = @_;
 8598:     if (!$symb) {return '';}
 8599: 
 8600:     &commonJSfunctions($request);
 8601: 
 8602:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8603:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 8604:     $result.='
 8605: <h2>
 8606:   '.&mt('Select Students for Which to Download Submissions').'
 8607: </h2>'.&selectfield(1).'
 8608:                 <input type="hidden" name="command" value="downloadfileslink" /> 
 8609:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 8610:             </div>
 8611:           </div>
 8612: 
 8613: 
 8614:   </form>';
 8615:     return $result;
 8616: }
 8617: 
 8618: #--- Displays the submissions first page -------
 8619: sub submit_options {
 8620:     my ($request,$symb) = @_;
 8621:     if (!$symb) {return '';}
 8622: 
 8623:     &commonJSfunctions($request);
 8624:     my $result;
 8625: 
 8626:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8627: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 8628:     $result.=&selectfield(1).'
 8629:                 <input type="hidden" name="command" value="submission" /> 
 8630: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
 8631:             </div>
 8632:           </div>
 8633: 
 8634: 
 8635:   </form>';
 8636:     return $result;
 8637: }
 8638: 
 8639: sub selectfield {
 8640:    my ($full)=@_;
 8641:    my %options = 
 8642:           (&Apache::lonlocal::texthash(
 8643:              'yes'       => 'with submissions',
 8644:              'queued'    => 'in grading queue',
 8645:              'graded'    => 'with ungraded submissions',
 8646:              'incorrect' => 'with incorrect submissions',
 8647:              'all'       => 'with any status'),
 8648:              'select_form_order' => ['yes','queued','graded','incorrect','all']);
 8649:    my $result='<div class="LC_columnSection">
 8650:   
 8651:     <fieldset>
 8652:       <legend>
 8653:        '.&mt('Sections').'
 8654:       </legend>
 8655:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
 8656:     </fieldset>
 8657:   
 8658:     <fieldset>
 8659:       <legend>
 8660:         '.&mt('Groups').'
 8661:       </legend>
 8662:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
 8663:     </fieldset>
 8664:   
 8665:     <fieldset>
 8666:       <legend>
 8667:         '.&mt('Access Status').'
 8668:       </legend>
 8669:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
 8670:     </fieldset>';
 8671:     if ($full) {
 8672:        $result.='
 8673:     <fieldset>
 8674:       <legend>
 8675:         '.&mt('Submission Status').'
 8676:       </legend>'.
 8677:        &Apache::loncommon::select_form('all','submitonly',\%options).
 8678:    '</fieldset>';
 8679:     }
 8680:     $result.='</div><br />';
 8681:     return $result;
 8682: }
 8683: 
 8684: sub reset_perm {
 8685:     undef(%perm);
 8686: }
 8687: 
 8688: sub init_perm {
 8689:     &reset_perm();
 8690:     foreach my $test_perm ('vgr','mgr','opa') {
 8691: 
 8692: 	my $scope = $env{'request.course.id'};
 8693: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
 8694: 
 8695: 	    $scope .= '/'.$env{'request.course.sec'};
 8696: 	    if ( $perm{$test_perm}=
 8697: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
 8698: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
 8699: 	    } else {
 8700: 		delete($perm{$test_perm});
 8701: 	    }
 8702: 	}
 8703:     }
 8704: }
 8705: 
 8706: sub gather_clicker_ids {
 8707:     my %clicker_ids;
 8708: 
 8709:     my $classlist = &Apache::loncoursedata::get_classlist();
 8710: 
 8711:     # Set up a couple variables.
 8712:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
 8713:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
 8714:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
 8715: 
 8716:     foreach my $student (keys(%$classlist)) {
 8717:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
 8718:         my $username = $classlist->{$student}->[$username_idx];
 8719:         my $domain   = $classlist->{$student}->[$domain_idx];
 8720:         my $clickers =
 8721: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
 8722:         foreach my $id (split(/\,/,$clickers)) {
 8723:             $id=~s/^[\#0]+//;
 8724:             $id=~s/[\-\:]//g;
 8725:             if (exists($clicker_ids{$id})) {
 8726: 		$clicker_ids{$id}.=','.$username.':'.$domain;
 8727:             } else {
 8728: 		$clicker_ids{$id}=$username.':'.$domain;
 8729:             }
 8730:         }
 8731:     }
 8732:     return %clicker_ids;
 8733: }
 8734: 
 8735: sub gather_adv_clicker_ids {
 8736:     my %clicker_ids;
 8737:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 8738:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8739:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
 8740:     foreach my $element (sort(keys(%coursepersonnel))) {
 8741:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
 8742:             my ($puname,$pudom)=split(/\:/,$person);
 8743:             my $clickers =
 8744: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
 8745:             foreach my $id (split(/\,/,$clickers)) {
 8746: 		$id=~s/^[\#0]+//;
 8747:                 $id=~s/[\-\:]//g;
 8748: 		if (exists($clicker_ids{$id})) {
 8749: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
 8750: 		} else {
 8751: 		    $clicker_ids{$id}=$puname.':'.$pudom;
 8752: 		}
 8753:             }
 8754:         }
 8755:     }
 8756:     return %clicker_ids;
 8757: }
 8758: 
 8759: sub clicker_grading_parameters {
 8760:     return ('gradingmechanism' => 'scalar',
 8761:             'upfiletype' => 'scalar',
 8762:             'specificid' => 'scalar',
 8763:             'pcorrect' => 'scalar',
 8764:             'pincorrect' => 'scalar');
 8765: }
 8766: 
 8767: sub process_clicker {
 8768:     my ($r,$symb)=@_;
 8769:     if (!$symb) {return '';}
 8770:     my $result=&checkforfile_js();
 8771:     $result.=&Apache::loncommon::start_data_table().
 8772:              &Apache::loncommon::start_data_table_header_row().
 8773:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
 8774:              &Apache::loncommon::end_data_table_header_row().
 8775:              &Apache::loncommon::start_data_table_row()."<td>\n";
 8776: # Attempt to restore parameters from last session, set defaults if not present
 8777:     my %Saveable_Parameters=&clicker_grading_parameters();
 8778:     &Apache::loncommon::restore_course_settings('grades_clicker',
 8779:                                                  \%Saveable_Parameters);
 8780:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
 8781:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
 8782:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
 8783:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
 8784: 
 8785:     my %checked;
 8786:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
 8787:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
 8788:           $checked{$gradingmechanism}=' checked="checked"';
 8789:        }
 8790:     }
 8791: 
 8792:     my $upload=&mt("Evaluate File");
 8793:     my $type=&mt("Type");
 8794:     my $attendance=&mt("Award points just for participation");
 8795:     my $personnel=&mt("Correctness determined from response by course personnel");
 8796:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
 8797:     my $given=&mt("Correctness determined from given list of answers").' '.
 8798:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
 8799:     my $pcorrect=&mt("Percentage points for correct solution");
 8800:     my $pincorrect=&mt("Percentage points for incorrect solution");
 8801:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
 8802: 						   {'iclicker' => 'i>clicker',
 8803:                                                     'interwrite' => 'interwrite PRS'});
 8804:     $symb = &Apache::lonenc::check_encrypt($symb);
 8805:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
 8806: function sanitycheck() {
 8807: // Accept only integer percentages
 8808:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
 8809:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
 8810: // Find out grading choice
 8811:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8812:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
 8813:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
 8814:       }
 8815:    }
 8816: // By default, new choice equals user selection
 8817:    newgradingchoice=gradingchoice;
 8818: // Not good to give more points for false answers than correct ones
 8819:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
 8820:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
 8821:    }
 8822: // If new choice is attendance only, and old choice was correctness-based, restore defaults
 8823:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
 8824:       document.forms.gradesupload.pcorrect.value=100;
 8825:       document.forms.gradesupload.pincorrect.value=100;
 8826:    }
 8827: // If the values are different, cannot be attendance only
 8828:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
 8829:        (gradingchoice=='attendance')) {
 8830:        newgradingchoice='personnel';
 8831:    }
 8832: // Change grading choice to new one
 8833:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8834:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
 8835:          document.forms.gradesupload.gradingmechanism[i].checked=true;
 8836:       } else {
 8837:          document.forms.gradesupload.gradingmechanism[i].checked=false;
 8838:       }
 8839:    }
 8840: // Remember the old state
 8841:    document.forms.gradesupload.waschecked.value=newgradingchoice;
 8842: }
 8843: ENDUPFORM
 8844:     $result.= <<ENDUPFORM;
 8845: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 8846: <input type="hidden" name="symb" value="$symb" />
 8847: <input type="hidden" name="command" value="processclickerfile" />
 8848: <input type="file" name="upfile" size="50" />
 8849: <br /><label>$type: $selectform</label>
 8850: ENDUPFORM
 8851:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
 8852:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
 8853:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
 8854: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
 8855: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
 8856: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
 8857: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
 8858: <br />&nbsp;&nbsp;&nbsp;
 8859: <input type="text" name="givenanswer" size="50" />
 8860: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
 8861: ENDGRADINGFORM
 8862:          $result.='</td>'.&Apache::loncommon::end_data_table_row().
 8863:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
 8864:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
 8865: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
 8866: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 8867: </form>'
 8868: ENDPERCFORM
 8869:     $result.='</td>'.
 8870:              &Apache::loncommon::end_data_table_row().
 8871:              &Apache::loncommon::end_data_table();
 8872:     return $result;
 8873: }
 8874: 
 8875: sub process_clicker_file {
 8876:     my ($r,$symb)=@_;
 8877:     if (!$symb) {return '';}
 8878: 
 8879:     my %Saveable_Parameters=&clicker_grading_parameters();
 8880:     &Apache::loncommon::store_course_settings('grades_clicker',
 8881:                                               \%Saveable_Parameters);
 8882:     my $result='';
 8883:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
 8884: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
 8885: 	return $result;
 8886:     }
 8887:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
 8888:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
 8889:         return $result;
 8890:     }
 8891:     my $foundgiven=0;
 8892:     if ($env{'form.gradingmechanism'} eq 'given') {
 8893:         $env{'form.givenanswer'}=~s/^\s*//gs;
 8894:         $env{'form.givenanswer'}=~s/\s*$//gs;
 8895:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
 8896:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
 8897:         my @answers=split(/\,/,$env{'form.givenanswer'});
 8898:         $foundgiven=$#answers+1;
 8899:     }
 8900:     my %clicker_ids=&gather_clicker_ids();
 8901:     my %correct_ids;
 8902:     if ($env{'form.gradingmechanism'} eq 'personnel') {
 8903: 	%correct_ids=&gather_adv_clicker_ids();
 8904:     }
 8905:     if ($env{'form.gradingmechanism'} eq 'specific') {
 8906: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
 8907: 	   $correct_id=~tr/a-z/A-Z/;
 8908: 	   $correct_id=~s/\s//gs;
 8909: 	   $correct_id=~s/^[\#0]+//;
 8910:            $correct_id=~s/[\-\:]//g;
 8911:            if ($correct_id) {
 8912: 	      $correct_ids{$correct_id}='specified';
 8913:            }
 8914:         }
 8915:     }
 8916:     if ($env{'form.gradingmechanism'} eq 'attendance') {
 8917: 	$result.=&mt('Score based on attendance only');
 8918:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
 8919:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
 8920:     } else {
 8921: 	my $number=0;
 8922: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
 8923: 	foreach my $id (sort(keys(%correct_ids))) {
 8924: 	    $result.='<br /><tt>'.$id.'</tt> - ';
 8925: 	    if ($correct_ids{$id} eq 'specified') {
 8926: 		$result.=&mt('specified');
 8927: 	    } else {
 8928: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
 8929: 		$result.=&Apache::loncommon::plainname($uname,$udom);
 8930: 	    }
 8931: 	    $number++;
 8932: 	}
 8933:         $result.="</p>\n";
 8934: 	if ($number==0) {
 8935: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
 8936: 	    return $result;
 8937: 	}
 8938:     }
 8939:     if (length($env{'form.upfile'}) < 2) {
 8940:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
 8941: 		     '<span class="LC_error">',
 8942: 		     '</span>',
 8943: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
 8944:         return $result;
 8945:     }
 8946: 
 8947: # Were able to get all the info needed, now analyze the file
 8948: 
 8949:     $result.=&Apache::loncommon::studentbrowser_javascript();
 8950:     $symb = &Apache::lonenc::check_encrypt($symb);
 8951:     $result.=&Apache::loncommon::start_data_table().
 8952:              &Apache::loncommon::start_data_table_header_row().
 8953:              '<th>'.&mt('Evaluate clicker file').'</th>'.
 8954:              &Apache::loncommon::end_data_table_header_row().
 8955:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
 8956: <td>
 8957: <form method="post" action="/adm/grades" name="clickeranalysis">
 8958: <input type="hidden" name="symb" value="$symb" />
 8959: <input type="hidden" name="command" value="assignclickergrades" />
 8960: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
 8961: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
 8962: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
 8963: ENDHEADER
 8964:     if ($env{'form.gradingmechanism'} eq 'given') {
 8965:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
 8966:     } 
 8967:     my %responses;
 8968:     my @questiontitles;
 8969:     my $errormsg='';
 8970:     my $number=0;
 8971:     if ($env{'form.upfiletype'} eq 'iclicker') {
 8972: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
 8973:     }
 8974:     if ($env{'form.upfiletype'} eq 'interwrite') {
 8975:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
 8976:     }
 8977:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
 8978:              '<input type="hidden" name="number" value="'.$number.'" />'.
 8979:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
 8980:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
 8981:              '<br />';
 8982:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
 8983:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
 8984:        return $result;
 8985:     } 
 8986: # Remember Question Titles
 8987: # FIXME: Possibly need delimiter other than ":"
 8988:     for (my $i=0;$i<$number;$i++) {
 8989:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
 8990:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
 8991:     }
 8992:     my $correct_count=0;
 8993:     my $student_count=0;
 8994:     my $unknown_count=0;
 8995: # Match answers with usernames
 8996: # FIXME: Possibly need delimiter other than ":"
 8997:     foreach my $id (keys(%responses)) {
 8998:        if ($correct_ids{$id}) {
 8999:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
 9000:           $correct_count++;
 9001:        } elsif ($clicker_ids{$id}) {
 9002:           if ($clicker_ids{$id}=~/\,/) {
 9003: # More than one user with the same clicker!
 9004:              $result.="</td>".&Apache::loncommon::end_data_table_row().
 9005:                            &Apache::loncommon::start_data_table_row()."<td>".
 9006:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
 9007:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 9008:                            "<select name='multi".$id."'>";
 9009:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
 9010:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
 9011:              }
 9012:              $result.='</select>';
 9013:              $unknown_count++;
 9014:           } else {
 9015: # Good: found one and only one user with the right clicker
 9016:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
 9017:              $student_count++;
 9018:           }
 9019:        } else {
 9020:           $result.="</td>".&Apache::loncommon::end_data_table_row().
 9021:                            &Apache::loncommon::start_data_table_row()."<td>".
 9022:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
 9023:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 9024:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
 9025:                    "\n".&mt("Domain").": ".
 9026:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
 9027:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,0,$id);
 9028:           $unknown_count++;
 9029:        }
 9030:     }
 9031:     $result.='<hr />'.
 9032:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
 9033:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
 9034:        if ($correct_count==0) {
 9035:           $errormsg.="Found no correct answers answers for grading!";
 9036:        } elsif ($correct_count>1) {
 9037:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
 9038:        }
 9039:     }
 9040:     if ($number<1) {
 9041:        $errormsg.="Found no questions.";
 9042:     }
 9043:     if ($errormsg) {
 9044:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
 9045:     } else {
 9046:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
 9047:     }
 9048:     $result.='</form></td>'.
 9049:              &Apache::loncommon::end_data_table_row().
 9050:              &Apache::loncommon::end_data_table();
 9051:     return $result;
 9052: }
 9053: 
 9054: sub iclicker_eval {
 9055:     my ($questiontitles,$responses)=@_;
 9056:     my $number=0;
 9057:     my $errormsg='';
 9058:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 9059:         my %components=&Apache::loncommon::record_sep($line);
 9060:         my @entries=map {$components{$_}} (sort(keys(%components)));
 9061: 	if ($entries[0] eq 'Question') {
 9062: 	    for (my $i=3;$i<$#entries;$i+=6) {
 9063: 		$$questiontitles[$number]=$entries[$i];
 9064: 		$number++;
 9065: 	    }
 9066: 	}
 9067: 	if ($entries[0]=~/^\#/) {
 9068: 	    my $id=$entries[0];
 9069: 	    my @idresponses;
 9070: 	    $id=~s/^[\#0]+//;
 9071: 	    for (my $i=0;$i<$number;$i++) {
 9072: 		my $idx=3+$i*6;
 9073:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
 9074: 		push(@idresponses,$entries[$idx]);
 9075: 	    }
 9076: 	    $$responses{$id}=join(',',@idresponses);
 9077: 	}
 9078:     }
 9079:     return ($errormsg,$number);
 9080: }
 9081: 
 9082: sub interwrite_eval {
 9083:     my ($questiontitles,$responses)=@_;
 9084:     my $number=0;
 9085:     my $errormsg='';
 9086:     my $skipline=1;
 9087:     my $questionnumber=0;
 9088:     my %idresponses=();
 9089:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 9090:         my %components=&Apache::loncommon::record_sep($line);
 9091:         my @entries=map {$components{$_}} (sort(keys(%components)));
 9092:         if ($entries[1] eq 'Time') { $skipline=0; next; }
 9093:         if ($entries[1] eq 'Response') { $skipline=1; }
 9094:         next if $skipline;
 9095:         if ($entries[0]!=$questionnumber) {
 9096:            $questionnumber=$entries[0];
 9097:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
 9098:            $number++;
 9099:         }
 9100:         my $id=$entries[4];
 9101:         $id=~s/^[\#0]+//;
 9102:         $id=~s/^v\d*\://i;
 9103:         $id=~s/[\-\:]//g;
 9104:         $idresponses{$id}[$number]=$entries[6];
 9105:     }
 9106:     foreach my $id (keys(%idresponses)) {
 9107:        $$responses{$id}=join(',',@{$idresponses{$id}});
 9108:        $$responses{$id}=~s/^\s*\,//;
 9109:     }
 9110:     return ($errormsg,$number);
 9111: }
 9112: 
 9113: sub assign_clicker_grades {
 9114:     my ($r,$symb)=@_;
 9115:     if (!$symb) {return '';}
 9116: # See which part we are saving to
 9117:     my $res_error;
 9118:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 9119:     if ($res_error) {
 9120:         return &navmap_errormsg();
 9121:     }
 9122: # FIXME: This should probably look for the first handgradeable part
 9123:     my $part=$$partlist[0];
 9124: # Start screen output
 9125:     my $result=&Apache::loncommon::start_data_table().
 9126:              &Apache::loncommon::start_data_table_header_row().
 9127:              '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
 9128:              &Apache::loncommon::end_data_table_header_row().
 9129:              &Apache::loncommon::start_data_table_row().'<td>';
 9130: # Get correct result
 9131: # FIXME: Possibly need delimiter other than ":"
 9132:     my @correct=();
 9133:     my $gradingmechanism=$env{'form.gradingmechanism'};
 9134:     my $number=$env{'form.number'};
 9135:     if ($gradingmechanism ne 'attendance') {
 9136:        foreach my $key (keys(%env)) {
 9137:           if ($key=~/^form\.correct\:/) {
 9138:              my @input=split(/\,/,$env{$key});
 9139:              for (my $i=0;$i<=$#input;$i++) {
 9140:                  if (($correct[$i]) && ($input[$i]) &&
 9141:                      ($correct[$i] ne $input[$i])) {
 9142:                     $result.='<br /><span class="LC_warning">'.
 9143:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
 9144:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
 9145:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
 9146:                     $correct[$i]=$input[$i];
 9147:                  }
 9148:              }
 9149:           }
 9150:        }
 9151:        for (my $i=0;$i<$number;$i++) {
 9152:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
 9153:              $result.='<br /><span class="LC_error">'.
 9154:                       &mt('No correct result given for question "[_1]"!',
 9155:                           $env{'form.question:'.$i}).'</span>';
 9156:           }
 9157:        }
 9158:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
 9159:     }
 9160: # Start grading
 9161:     my $pcorrect=$env{'form.pcorrect'};
 9162:     my $pincorrect=$env{'form.pincorrect'};
 9163:     my $storecount=0;
 9164:     my %users=();
 9165:     foreach my $key (keys(%env)) {
 9166:        my $user='';
 9167:        if ($key=~/^form\.student\:(.*)$/) {
 9168:           $user=$1;
 9169:        }
 9170:        if ($key=~/^form\.unknown\:(.*)$/) {
 9171:           my $id=$1;
 9172:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
 9173:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
 9174:           } elsif ($env{'form.multi'.$id}) {
 9175:              $user=$env{'form.multi'.$id};
 9176:           }
 9177:        }
 9178:        if ($user) {
 9179:           if ($users{$user}) {
 9180:              $result.='<br /><span class="LC_warning">'.
 9181:                       &mt("More than one entry found for <tt>[_1]</tt>!",$user).
 9182:                       '</span><br />';
 9183:           }
 9184:           $users{$user}=1; 
 9185:           my @answer=split(/\,/,$env{$key});
 9186:           my $sum=0;
 9187:           my $realnumber=$number;
 9188:           for (my $i=0;$i<$number;$i++) {
 9189:              if  ($correct[$i] eq '-') {
 9190:                 $realnumber--;
 9191:              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/))  {
 9192:                 if ($gradingmechanism eq 'attendance') {
 9193:                    $sum+=$pcorrect;
 9194:                 } elsif ($correct[$i] eq '*') {
 9195:                    $sum+=$pcorrect;
 9196:                 } else {
 9197: # We actually grade if correct or not
 9198:                    my $increment=$pincorrect;
 9199: # Special case: numerical answer "0"
 9200:                    if ($correct[$i] eq '0') {
 9201:                       if ($answer[$i]=~/^[0\.]+$/) {
 9202:                          $increment=$pcorrect;
 9203:                       }
 9204: # General numerical answer, both evaluate to something non-zero
 9205:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
 9206:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
 9207:                          $increment=$pcorrect;
 9208:                       }
 9209: # Must be just alphanumeric
 9210:                    } elsif ($answer[$i] eq $correct[$i]) {
 9211:                       $increment=$pcorrect;
 9212:                    }
 9213:                    $sum+=$increment;
 9214:                 }
 9215:              }
 9216:           }
 9217:           my $ave=$sum/(100*$realnumber);
 9218: # Store
 9219:           my ($username,$domain)=split(/\:/,$user);
 9220:           my %grades=();
 9221:           $grades{"resource.$part.solved"}='correct_by_override';
 9222:           $grades{"resource.$part.awarded"}=$ave;
 9223:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 9224:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
 9225:                                                  $env{'request.course.id'},
 9226:                                                  $domain,$username);
 9227:           if ($returncode ne 'ok') {
 9228:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
 9229:           } else {
 9230:              $storecount++;
 9231:           }
 9232:        }
 9233:     }
 9234: # We are done
 9235:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
 9236:              '</td>'.
 9237:              &Apache::loncommon::end_data_table_row().
 9238:              &Apache::loncommon::end_data_table();
 9239:     return $result;
 9240: }
 9241: 
 9242: sub navmap_errormsg {
 9243:     return '<div class="LC_error">'.
 9244:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
 9245:            &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>').
 9246:            '</div>';
 9247: }
 9248: 
 9249: sub startpage {
 9250:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag) = @_;
 9251:     unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
 9252:     $r->print(&Apache::loncommon::start_page('Grading',undef,
 9253:                                           {'bread_crumbs' => $crumbs}));
 9254:     &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
 9255:     unless ($nodisplayflag) {
 9256:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag));
 9257:     }
 9258: }
 9259: 
 9260: sub select_problem {
 9261:     my ($r)=@_;
 9262:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
 9263:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1));
 9264:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
 9265:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
 9266: }
 9267: 
 9268: sub handler {
 9269:     my $request=$_[0];
 9270:     &reset_caches();
 9271:     if ($request->header_only) {
 9272:         &Apache::loncommon::content_type($request,'text/html');
 9273:         $request->send_http_header;
 9274:         return OK;
 9275:     }
 9276:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
 9277: 
 9278:     &init_perm();
 9279:     if (!$env{'request.course.id'}) {
 9280:         # Not in a course.
 9281:         $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
 9282:         return HTTP_NOT_ACCEPTABLE;
 9283:     } elsif (!%perm) {
 9284:         $request->internal_redirect('/adm/quickgrades');
 9285:     }
 9286:     &Apache::loncommon::content_type($request,'text/html');
 9287:     $request->send_http_header;
 9288: 
 9289: 
 9290: # see what command we need to execute
 9291: 
 9292:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
 9293:     my $command=$commands[0];
 9294: 
 9295:     if ($#commands > 0) {
 9296: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
 9297:     }
 9298: 
 9299: # see what the symb is
 9300: 
 9301:     my $symb=$env{'form.symb'};
 9302:     unless ($symb) {
 9303:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
 9304:        $symb=&Apache::lonnet::symbread($url);
 9305:     }
 9306:     &Apache::lonenc::check_decrypt(\$symb);
 9307: 
 9308:     $ssi_error = 0;
 9309:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
 9310: #
 9311: # Not called from a resource, but inside a course
 9312: #    
 9313:         &startpage($request,undef,[],1,1);
 9314:         &select_problem($request);
 9315:     } else {
 9316: 	if ($command eq 'submission' && $perm{'vgr'}) {
 9317:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}]);
 9318: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
 9319: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
 9320:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
 9321:                                        {href=>'',text=>'Select student'}],1,1);
 9322: 	    &pickStudentPage($request,$symb);
 9323: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
 9324:             &startpage($request,$symb,
 9325:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
 9326:                                        {href=>'',text=>'Select student'},
 9327:                                        {href=>'',text=>'Grade student'}],1,1);
 9328: 	    &displayPage($request,$symb);
 9329: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
 9330:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
 9331:                                        {href=>'',text=>'Select student'},
 9332:                                        {href=>'',text=>'Grade student'},
 9333:                                        {href=>'',text=>'Store grades'}],1,1);
 9334: 	    &updateGradeByPage($request,$symb);
 9335: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
 9336:             &startpage($request,$symb,[{href=>'',text=>'...'},
 9337:                                        {href=>'',text=>'Modify grades'}]);
 9338: 	    &processGroup($request,$symb);
 9339: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
 9340:             &startpage($request,$symb);
 9341: 	    $request->print(&grading_menu($request,$symb));
 9342: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
 9343:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
 9344: 	    $request->print(&submit_options($request,$symb));
 9345:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
 9346:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}]);
 9347:             $request->print(&listStudents($request,$symb,'graded'));
 9348:         } elsif ($command eq 'table' && $perm{'vgr'}) {
 9349:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
 9350:             $request->print(&submit_options_table($request,$symb));
 9351:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
 9352:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
 9353:             $request->print(&submit_options_sequence($request,$symb));
 9354: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
 9355:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
 9356: 	    $request->print(&viewgrades($request,$symb));
 9357: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
 9358:             &startpage($request,$symb,[{href=>'',text=>'...'},
 9359:                                        {href=>'',text=>'Store grades'}]);
 9360: 	    $request->print(&processHandGrade($request,$symb));
 9361: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
 9362:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
 9363:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
 9364:                                                                              text=>"Modify grades"},
 9365:                                        {href=>'', text=>"Store grades"}]);
 9366: 	    $request->print(&editgrades($request,$symb));
 9367:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
 9368:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
 9369:             $request->print(&initialverifyreceipt($request,$symb));
 9370: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
 9371:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
 9372:                                        {href=>'',text=>'Verification Result'}]);
 9373: 	    $request->print(&verifyreceipt($request,$symb));
 9374:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
 9375:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
 9376:             $request->print(&process_clicker($request,$symb));
 9377:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
 9378:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
 9379:                                        {href=>'', text=>'Process clicker file'}]);
 9380:             $request->print(&process_clicker_file($request,$symb));
 9381:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
 9382:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
 9383:                                        {href=>'', text=>'Process clicker file'},
 9384:                                        {href=>'', text=>'Store grades'}]);
 9385:             $request->print(&assign_clicker_grades($request,$symb));
 9386: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
 9387:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
 9388: 	    $request->print(&upcsvScores_form($request,$symb));
 9389: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
 9390:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
 9391: 	    $request->print(&csvupload($request,$symb));
 9392: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
 9393:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
 9394: 	    $request->print(&csvuploadmap($request,$symb));
 9395: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
 9396: 	    if ($env{'form.associate'} ne 'Reverse Association') {
 9397:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
 9398: 		$request->print(&csvuploadoptions($request,$symb));
 9399: 	    } else {
 9400: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
 9401: 		    $env{'form.upfile_associate'} = 'reverse';
 9402: 		} else {
 9403: 		    $env{'form.upfile_associate'} = 'forward';
 9404: 		}
 9405:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
 9406: 		$request->print(&csvuploadmap($request,$symb));
 9407: 	    }
 9408: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
 9409:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
 9410: 	    $request->print(&csvuploadassign($request,$symb));
 9411: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
 9412:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9413: 	    $request->print(&scantron_selectphase($request,undef,$symb));
 9414:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
 9415:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9416:  	    $request->print(&scantron_do_warning($request,$symb));
 9417: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
 9418:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9419: 	    $request->print(&scantron_validate_file($request,$symb));
 9420: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
 9421:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9422: 	    $request->print(&scantron_process_students($request,$symb));
 9423:  	} elsif ($command eq 'scantronupload' && 
 9424:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9425: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9426:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9427:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
 9428:  	} elsif ($command eq 'scantronupload_save' &&
 9429:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9430: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9431:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9432:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
 9433:  	} elsif ($command eq 'scantron_download' &&
 9434: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 9435:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9436:  	    $request->print(&scantron_download_scantron_data($request,$symb));
 9437:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
 9438:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9439:             $request->print(&checkscantron_results($request,$symb));
 9440:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
 9441:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}]);
 9442:             $request->print(&submit_options_download($request,$symb));
 9443:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
 9444:             &startpage($request,$symb,
 9445:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
 9446:     {href=>'', text=>'Download submissions'}]);
 9447:             &submit_download_link($request,$symb);
 9448: 	} elsif ($command) {
 9449:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
 9450: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
 9451: 	}
 9452:     }
 9453:     if ($ssi_error) {
 9454: 	&ssi_print_error($request);
 9455:     }
 9456:     &Apache::lonquickgrades::endGradeScreen($request);
 9457:     $request->print(&Apache::loncommon::end_page());
 9458:     &reset_caches();
 9459:     return OK;
 9460: }
 9461: 
 9462: 1;
 9463: 
 9464: __END__;
 9465: 
 9466: 
 9467: =head1 NAME
 9468: 
 9469: Apache::grades
 9470: 
 9471: =head1 SYNOPSIS
 9472: 
 9473: Handles the viewing of grades.
 9474: 
 9475: This is part of the LearningOnline Network with CAPA project
 9476: described at http://www.lon-capa.org.
 9477: 
 9478: =head1 OVERVIEW
 9479: 
 9480: Do an ssi with retries:
 9481: While I'd love to factor out this with the vesrion in lonprintout,
 9482: 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
 9483: I'm not quite ready to invent (e.g. an ssi_with_retry object).
 9484: 
 9485: At least the logic that drives this has been pulled out into loncommon.
 9486: 
 9487: 
 9488: 
 9489: ssi_with_retries - Does the server side include of a resource.
 9490:                      if the ssi call returns an error we'll retry it up to
 9491:                      the number of times requested by the caller.
 9492:                      If we still have a proble, no text is appended to the
 9493:                      output and we set some global variables.
 9494:                      to indicate to the caller an SSI error occurred.  
 9495:                      All of this is supposed to deal with the issues described
 9496:                      in LonCAPA BZ 5631 see:
 9497:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
 9498:                      by informing the user that this happened.
 9499: 
 9500: Parameters:
 9501:   resource   - The resource to include.  This is passed directly, without
 9502:                interpretation to lonnet::ssi.
 9503:   form       - The form hash parameters that guide the interpretation of the resource
 9504:                
 9505:   retries    - Number of retries allowed before giving up completely.
 9506: Returns:
 9507:   On success, returns the rendered resource identified by the resource parameter.
 9508: Side Effects:
 9509:   The following global variables can be set:
 9510:    ssi_error                - If an unrecoverable error occurred this becomes true.
 9511:                               It is up to the caller to initialize this to false
 9512:                               if desired.
 9513:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
 9514:                               of the resource that could not be rendered by the ssi
 9515:                               call.
 9516:    ssi_error_message   - The error string fetched from the ssi response
 9517:                               in the event of an error.
 9518: 
 9519: 
 9520: =head1 HANDLER SUBROUTINE
 9521: 
 9522: ssi_with_retries()
 9523: 
 9524: =head1 SUBROUTINES
 9525: 
 9526: =over
 9527: 
 9528: =item scantron_get_correction() : 
 9529: 
 9530:    Builds the interface screen to interact with the operator to fix a
 9531:    specific error condition in a specific scanline
 9532: 
 9533:  Arguments:
 9534:     $r           - Apache request object
 9535:     $i           - number of the current scanline
 9536:     $scan_record - hash ref as returned from &scantron_parse_scanline()
 9537:     $scan_config - hash ref as returned from &get_scantron_config()
 9538:     $line        - full contents of the current scanline
 9539:     $error       - error condition, valid values are
 9540:                    'incorrectCODE', 'duplicateCODE',
 9541:                    'doublebubble', 'missingbubble',
 9542:                    'duplicateID', 'incorrectID'
 9543:     $arg         - extra information needed
 9544:        For errors:
 9545:          - duplicateID   - paper number that this studentID was seen before on
 9546:          - duplicateCODE - array ref of the paper numbers this CODE was
 9547:                            seen on before
 9548:          - incorrectCODE - current incorrect CODE 
 9549:          - doublebubble  - array ref of the bubble lines that have double
 9550:                            bubble errors
 9551:          - missingbubble - array ref of the bubble lines that have missing
 9552:                            bubble errors
 9553: 
 9554: =item  scantron_get_maxbubble() : 
 9555: 
 9556:    Arguments:
 9557:        $nav_error  - Reference to scalar which is a flag to indicate a
 9558:                       failure to retrieve a navmap object.
 9559:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
 9560:        calling routine should trap the error condition and display the warning
 9561:        found in &navmap_errormsg().
 9562: 
 9563:        $scantron_config - Reference to bubblesheet format configuration hash.
 9564: 
 9565:    Returns the maximum number of bubble lines that are expected to
 9566:    occur. Does this by walking the selected sequence rendering the
 9567:    resource and then checking &Apache::lonxml::get_problem_counter()
 9568:    for what the current value of the problem counter is.
 9569: 
 9570:    Caches the results to $env{'form.scantron_maxbubble'},
 9571:    $env{'form.scantron.bubble_lines.n'}, 
 9572:    $env{'form.scantron.first_bubble_line.n'} and
 9573:    $env{"form.scantron.sub_bubblelines.n"}
 9574:    which are the total number of bubble, lines, the number of bubble
 9575:    lines for response n and number of the first bubble line for response n,
 9576:    and a comma separated list of numbers of bubble lines for sub-questions
 9577:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
 9578: 
 9579: 
 9580: =item  scantron_validate_missingbubbles() : 
 9581: 
 9582:    Validates all scanlines in the selected file to not have any
 9583:     answers that don't have bubbles that have not been verified
 9584:     to be bubble free.
 9585: 
 9586: =item  scantron_process_students() : 
 9587: 
 9588:    Routine that does the actual grading of the bubble sheet information.
 9589: 
 9590:    The parsed scanline hash is added to %env 
 9591: 
 9592:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
 9593:    foreach resource , with the form data of
 9594: 
 9595: 	'submitted'     =>'scantron' 
 9596: 	'grade_target'  =>'grade',
 9597: 	'grade_username'=> username of student
 9598: 	'grade_domain'  => domain of student
 9599: 	'grade_courseid'=> of course
 9600: 	'grade_symb'    => symb of resource to grade
 9601: 
 9602:     This triggers a grading pass. The problem grading code takes care
 9603:     of converting the bubbled letter information (now in %env) into a
 9604:     valid submission.
 9605: 
 9606: =item  scantron_upload_scantron_data() :
 9607: 
 9608:     Creates the screen for adding a new bubble sheet data file to a course.
 9609: 
 9610: =item  scantron_upload_scantron_data_save() : 
 9611: 
 9612:    Adds a provided bubble information data file to the course if user
 9613:    has the correct privileges to do so. 
 9614: 
 9615: =item  valid_file() :
 9616: 
 9617:    Validates that the requested bubble data file exists in the course.
 9618: 
 9619: =item  scantron_download_scantron_data() : 
 9620: 
 9621:    Shows a list of the three internal files (original, corrected,
 9622:    skipped) for a specific bubble sheet data file that exists in the
 9623:    course.
 9624: 
 9625: =item  scantron_validate_ID() : 
 9626: 
 9627:    Validates all scanlines in the selected file to not have any
 9628:    invalid or underspecified student/employee IDs
 9629: 
 9630: =item navmap_errormsg() :
 9631: 
 9632:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
 9633:    Should be called whenever the request to instantiate a navmap object fails.  
 9634: 
 9635: =back
 9636: 
 9637: =cut

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