File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.619: download - view: text, annotated - select for diffs
Wed Apr 14 15:04:58 2010 UTC (14 years ago) by www
Branches: MAIN
CVS tags: HEAD
Continuing fixing up $symb-transfer

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.619 2010/04/14 15:04:58 www Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: 
   30: 
   31: package Apache::grades;
   32: use strict;
   33: use Apache::style;
   34: use Apache::lonxml;
   35: use Apache::lonnet;
   36: use Apache::loncommon;
   37: use Apache::lonhtmlcommon;
   38: use Apache::lonnavmaps;
   39: use Apache::lonhomework;
   40: use Apache::lonpickcode;
   41: use Apache::loncoursedata;
   42: use Apache::lonmsg();
   43: use Apache::Constants qw(:common);
   44: use Apache::lonlocal;
   45: use Apache::lonenc;
   46: use String::Similarity;
   47: use LONCAPA;
   48: 
   49: use POSIX qw(floor);
   50: 
   51: 
   52: 
   53: my %perm=();
   54: 
   55: #  These variables are used to recover from ssi errors
   56: 
   57: my $ssi_retries = 5;
   58: my $ssi_error;
   59: my $ssi_error_resource;
   60: my $ssi_error_message;
   61: 
   62: 
   63: sub ssi_with_retries {
   64:     my ($resource, $retries, %form) = @_;
   65:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
   66:     if ($response->is_error) {
   67: 	$ssi_error          = 1;
   68: 	$ssi_error_resource = $resource;
   69: 	$ssi_error_message  = $response->code . " " . $response->message;
   70:     }
   71: 
   72:     return $content;
   73: 
   74: }
   75: #
   76: #  Prodcuces an ssi retry failure error message to the user:
   77: #
   78: 
   79: sub ssi_print_error {
   80:     my ($r) = @_;
   81:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
   82:     $r->print('
   83: <br />
   84: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
   85: <p>
   86: '.&mt('Unable to retrieve a resource from a server:').'<br />
   87: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
   88: '.&mt('Error:').' '.$ssi_error_message.'
   89: </p>
   90: <p>'.
   91: &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 />'.
   92: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
   93: '</p>');
   94:     return;
   95: }
   96: 
   97: #
   98: # --- Retrieve the parts from the metadata file.---
   99: # Returns an array of everything that the resources stores away
  100: #
  101: 
  102: sub getpartlist {
  103:     my ($symb,$errorref) = @_;
  104: 
  105:     my $navmap   = Apache::lonnavmaps::navmap->new();
  106:     unless (ref($navmap)) {
  107:         if (ref($errorref)) { 
  108:             $$errorref = 'navmap';
  109:             return;
  110:         }
  111:     }
  112:     my $res      = $navmap->getBySymb($symb);
  113:     my $partlist = $res->parts();
  114:     my $url      = $res->src();
  115:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
  116: 
  117:     my @stores;
  118:     foreach my $part (@{ $partlist }) {
  119: 	foreach my $key (@metakeys) {
  120: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
  121: 	}
  122:     }
  123:     return @stores;
  124: }
  125: 
  126: #--- Format fullname, username:domain if different for display
  127: #--- Use anywhere where the student names are listed
  128: sub nameUserString {
  129:     my ($type,$fullname,$uname,$udom) = @_;
  130:     if ($type eq 'header') {
  131: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
  132:     } else {
  133: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
  134: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
  135:     }
  136: }
  137: 
  138: #--- Get the partlist and the response type for a given problem. ---
  139: #--- Indicate if a response type is coded handgraded or not. ---
  140: sub response_type {
  141:     my ($symb,$response_error) = @_;
  142: 
  143:     my $navmap = Apache::lonnavmaps::navmap->new();
  144:     unless (ref($navmap)) {
  145:         if (ref($response_error)) {
  146:             $$response_error = 1;
  147:         }
  148:         return;
  149:     }
  150:     my $res = $navmap->getBySymb($symb);
  151:     unless (ref($res)) {
  152:         $$response_error = 1;
  153:         return;
  154:     }
  155:     my $partlist = $res->parts();
  156:     my %vPart = 
  157: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
  158:     my (%response_types,%handgrade);
  159:     foreach my $part (@{ $partlist }) {
  160: 	next if (%vPart && !exists($vPart{$part}));
  161: 
  162: 	my @types = $res->responseType($part);
  163: 	my @ids = $res->responseIds($part);
  164: 	for (my $i=0; $i < scalar(@ids); $i++) {
  165: 	    $response_types{$part}{$ids[$i]} = $types[$i];
  166: 	    $handgrade{$part.'_'.$ids[$i]} = 
  167: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
  168: 				     '.handgrade',$symb);
  169: 	}
  170:     }
  171:     return ($partlist,\%handgrade,\%response_types);
  172: }
  173: 
  174: sub flatten_responseType {
  175:     my ($responseType) = @_;
  176:     my @part_response_id =
  177: 	map { 
  178: 	    my $part = $_;
  179: 	    map {
  180: 		[$part,$_]
  181: 		} sort(keys(%{ $responseType->{$part} }));
  182: 	} sort(keys(%$responseType));
  183:     return @part_response_id;
  184: }
  185: 
  186: sub get_display_part {
  187:     my ($partID,$symb)=@_;
  188:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
  189:     if (defined($display) and $display ne '') {
  190:         $display.= ' (<span class="LC_internal_info">'
  191:                   .&mt('Part ID: [_1]',$partID).'</span>)';
  192:     } else {
  193: 	$display=$partID;
  194:     }
  195:     return $display;
  196: }
  197: 
  198: sub reset_caches {
  199:     &reset_analyze_cache();
  200:     &reset_perm();
  201: }
  202: 
  203: {
  204:     my %analyze_cache;
  205:     my %analyze_cache_formkeys;
  206: 
  207:     sub reset_analyze_cache {
  208: 	undef(%analyze_cache);
  209:         undef(%analyze_cache_formkeys);
  210:     }
  211: 
  212:     sub get_analyze {
  213: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash)=@_;
  214: 	my $key = "$symb\0$uname\0$udom";
  215: 	if (exists($analyze_cache{$key})) {
  216:             my $getupdate = 0;
  217:             if (ref($add_to_hash) eq 'HASH') {
  218:                 foreach my $item (keys(%{$add_to_hash})) {
  219:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
  220:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
  221:                             $getupdate = 1;
  222:                             last;
  223:                         }
  224:                     } else {
  225:                         $getupdate = 1;
  226:                     }
  227:                 }
  228:             }
  229:             if (!$getupdate) {
  230:                 return $analyze_cache{$key};
  231:             }
  232:         }
  233: 
  234: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
  235: 	$url=&Apache::lonnet::clutter($url);
  236:         my %form = ('grade_target'      => 'analyze',
  237:                     'grade_domain'      => $udom,
  238:                     'grade_symb'        => $symb,
  239:                     'grade_courseid'    =>  $env{'request.course.id'},
  240:                     'grade_username'    => $uname,
  241:                     'grade_noincrement' => $no_increment);
  242:         if (ref($add_to_hash)) {
  243:             %form = (%form,%{$add_to_hash});
  244:         } 
  245: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
  246: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
  247: 	my %analyze=&Apache::lonnet::str2hash($subresult);
  248:         if (ref($add_to_hash) eq 'HASH') {
  249:             $analyze_cache_formkeys{$key} = $add_to_hash;
  250:         } else {
  251:             $analyze_cache_formkeys{$key} = {};
  252:         }
  253: 	return $analyze_cache{$key} = \%analyze;
  254:     }
  255: 
  256:     sub get_order {
  257: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment)=@_;
  258: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment);
  259: 	return $analyze->{"$partid.$respid.shown"};
  260:     }
  261: 
  262:     sub get_radiobutton_correct_foil {
  263: 	my ($partid,$respid,$symb,$uname,$udom)=@_;
  264: 	my $analyze = &get_analyze($symb,$uname,$udom);
  265:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom);
  266:         if (ref($foils) eq 'ARRAY') {
  267: 	    foreach my $foil (@{$foils}) {
  268: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
  269: 		    return $foil;
  270: 	        }
  271: 	    }
  272: 	}
  273:     }
  274: 
  275:     sub scantron_partids_tograde {
  276:         my ($resource,$cid,$uname,$udom,$check_for_randomlist) = @_;
  277:         my (%analysis,@parts);
  278:         if (ref($resource)) {
  279:             my $symb = $resource->symb();
  280:             my $add_to_form;
  281:             if ($check_for_randomlist) {
  282:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
  283:             }
  284:             my $analyze = &get_analyze($symb,$uname,$udom,undef,$add_to_form);
  285:             if (ref($analyze) eq 'HASH') {
  286:                 %analysis = %{$analyze};
  287:             }
  288:             if (ref($analysis{'parts'}) eq 'ARRAY') {
  289:                 foreach my $part (@{$analysis{'parts'}}) {
  290:                     my ($id,$respid) = split(/\./,$part);
  291:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
  292:                         push(@parts,$part);
  293:                     }
  294:                 }
  295:             }
  296:         }
  297:         return (\%analysis,\@parts);
  298:     }
  299: 
  300: }
  301: 
  302: #--- Clean response type for display
  303: #--- Currently filters option/rank/radiobutton/match/essay/Task
  304: #        response types only.
  305: sub cleanRecord {
  306:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
  307: 	$uname,$udom) = @_;
  308:     my $grayFont = '<span class="LC_internal_info">';
  309:     if ($response =~ /^(option|rank)$/) {
  310: 	my %answer=&Apache::lonnet::str2hash($answer);
  311: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  312: 	my ($toprow,$bottomrow);
  313: 	foreach my $foil (@$order) {
  314: 	    if ($grading{$foil} == 1) {
  315: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
  316: 	    } else {
  317: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
  318: 	    }
  319: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  320: 	}
  321: 	return '<blockquote><table border="1">'.
  322: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  323: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  324: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
  325:     } elsif ($response eq 'match') {
  326: 	my %answer=&Apache::lonnet::str2hash($answer);
  327: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  328: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
  329: 	my ($toprow,$middlerow,$bottomrow);
  330: 	foreach my $foil (@$order) {
  331: 	    my $item=shift(@items);
  332: 	    if ($grading{$foil} == 1) {
  333: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
  334: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
  335: 	    } else {
  336: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
  337: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
  338: 	    }
  339: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  340: 	}
  341: 	return '<blockquote><table border="1">'.
  342: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  343: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
  344: 	    $middlerow.'</tr>'.
  345: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  346: 	    $bottomrow.'</tr>'.'</table></blockquote>';
  347:     } elsif ($response eq 'radiobutton') {
  348: 	my %answer=&Apache::lonnet::str2hash($answer);
  349: 	my ($toprow,$bottomrow);
  350: 	my $correct = 
  351: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom);
  352: 	foreach my $foil (@$order) {
  353: 	    if (exists($answer{$foil})) {
  354: 		if ($foil eq $correct) {
  355: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
  356: 		} else {
  357: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
  358: 		}
  359: 	    } else {
  360: 		$toprow.='<td>'.&mt('false').'</td>';
  361: 	    }
  362: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  363: 	}
  364: 	return '<blockquote><table border="1">'.
  365: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  366: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  367: 	    $bottomrow.'</tr>'.'</table></blockquote>';
  368:     } elsif ($response eq 'essay') {
  369: 	if (! exists ($env{'form.'.$symb})) {
  370: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
  371: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
  372: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
  373: 
  374: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
  375: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
  376: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
  377: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
  378: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
  379: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
  380: 	}
  381: 	$answer =~ s-\n-<br />-g;
  382: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
  383:     } elsif ( $response eq 'organic') {
  384: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
  385: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
  386: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
  387: 	return $result;
  388:     } elsif ( $response eq 'Task') {
  389: 	if ( $answer eq 'SUBMITTED') {
  390: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
  391: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
  392: 	    return $result;
  393: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
  394: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
  395: 			       keys(%{$record}));
  396: 	    return join('<br />',($version,@matches));
  397: 			       
  398: 			       
  399: 	} else {
  400: 	    my $result =
  401: 		'<p>'
  402: 		.&mt('Overall result: [_1]',
  403: 		     $record->{$version."resource.$respid.$partid.status"})
  404: 		.'</p>';
  405: 	    
  406: 	    $result .= '<ul>';
  407: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
  408: 			     keys(%{$record}));
  409: 	    foreach my $grade (sort(@grade)) {
  410: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
  411: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
  412: 				     $dim, $record->{$grade}).
  413: 			  '</li>';
  414: 	    }
  415: 	    $result.='</ul>';
  416: 	    return $result;
  417: 	}
  418:     } elsif ( $response =~ m/(?:numerical|formula)/) {
  419: 	$answer = 
  420: 	    &Apache::loncommon::format_previous_attempt_value('submission',
  421: 							      $answer);
  422:     }
  423:     return $answer;
  424: }
  425: 
  426: #-- A couple of common js functions
  427: sub commonJSfunctions {
  428:     my $request = shift;
  429:     $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
  430:     function radioSelection(radioButton) {
  431: 	var selection=null;
  432: 	if (radioButton.length > 1) {
  433: 	    for (var i=0; i<radioButton.length; i++) {
  434: 		if (radioButton[i].checked) {
  435: 		    return radioButton[i].value;
  436: 		}
  437: 	    }
  438: 	} else {
  439: 	    if (radioButton.checked) return radioButton.value;
  440: 	}
  441: 	return selection;
  442:     }
  443: 
  444:     function pullDownSelection(selectOne) {
  445: 	var selection="";
  446: 	if (selectOne.length > 1) {
  447: 	    for (var i=0; i<selectOne.length; i++) {
  448: 		if (selectOne[i].selected) {
  449: 		    return selectOne[i].value;
  450: 		}
  451: 	    }
  452: 	} else {
  453:             // only one value it must be the selected one
  454: 	    return selectOne.value;
  455: 	}
  456:     }
  457: COMMONJSFUNCTIONS
  458: }
  459: 
  460: #--- Dumps the class list with usernames,list of sections,
  461: #--- section, ids and fullnames for each user.
  462: sub getclasslist {
  463:     my ($getsec,$filterlist,$getgroup) = @_;
  464:     my @getsec;
  465:     my @getgroup;
  466:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  467:     if (!ref($getsec)) {
  468: 	if ($getsec ne '' && $getsec ne 'all') {
  469: 	    @getsec=($getsec);
  470: 	}
  471:     } else {
  472: 	@getsec=@{$getsec};
  473:     }
  474:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
  475:     if (!ref($getgroup)) {
  476: 	if ($getgroup ne '' && $getgroup ne 'all') {
  477: 	    @getgroup=($getgroup);
  478: 	}
  479:     } else {
  480: 	@getgroup=@{$getgroup};
  481:     }
  482:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
  483: 
  484:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
  485:     # Bail out if we were unable to get the classlist
  486:     return if (! defined($classlist));
  487:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
  488:     #
  489:     my %sections;
  490:     my %fullnames;
  491:     foreach my $student (keys(%$classlist)) {
  492:         my $end      = 
  493:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
  494:         my $start    = 
  495:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
  496:         my $id       = 
  497:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
  498:         my $section  = 
  499:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
  500:         my $fullname = 
  501:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
  502:         my $status   = 
  503:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
  504:         my $group   = 
  505:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
  506: 	# filter students according to status selected
  507: 	if ($filterlist && (!($stu_status =~ /Any/))) {
  508: 	    if (!($stu_status =~ $status)) {
  509: 		delete($classlist->{$student});
  510: 		next;
  511: 	    }
  512: 	}
  513: 	# filter students according to groups selected
  514: 	my @stu_groups = split(/,/,$group);
  515: 	if (@getgroup) {
  516: 	    my $exclude = 1;
  517: 	    foreach my $grp (@getgroup) {
  518: 	        foreach my $stu_group (@stu_groups) {
  519: 	            if ($stu_group eq $grp) {
  520: 	                $exclude = 0;
  521:     	            } 
  522: 	        }
  523:     	        if (($grp eq 'none') && !$group) {
  524:         	        $exclude = 0;
  525:         	}
  526: 	    }
  527: 	    if ($exclude) {
  528: 	        delete($classlist->{$student});
  529: 	    }
  530: 	}
  531: 	$section = ($section ne '' ? $section : 'none');
  532: 	if (&canview($section)) {
  533: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
  534: 		$sections{$section}++;
  535: 		if ($classlist->{$student}) {
  536: 		    $fullnames{$student}=$fullname;
  537: 		}
  538: 	    } else {
  539: 		delete($classlist->{$student});
  540: 	    }
  541: 	} else {
  542: 	    delete($classlist->{$student});
  543: 	}
  544:     }
  545:     my %seen = ();
  546:     my @sections = sort(keys(%sections));
  547:     return ($classlist,\@sections,\%fullnames);
  548: }
  549: 
  550: sub canmodify {
  551:     my ($sec)=@_;
  552:     if ($perm{'mgr'}) {
  553: 	if (!defined($perm{'mgr_section'})) {
  554: 	    # can modify whole class
  555: 	    return 1;
  556: 	} else {
  557: 	    if ($sec eq $perm{'mgr_section'}) {
  558: 		#can modify the requested section
  559: 		return 1;
  560: 	    } else {
  561: 		# can't modify the request section
  562: 		return 0;
  563: 	    }
  564: 	}
  565:     }
  566:     #can't modify
  567:     return 0;
  568: }
  569: 
  570: sub canview {
  571:     my ($sec)=@_;
  572:     if ($perm{'vgr'}) {
  573: 	if (!defined($perm{'vgr_section'})) {
  574: 	    # can modify whole class
  575: 	    return 1;
  576: 	} else {
  577: 	    if ($sec eq $perm{'vgr_section'}) {
  578: 		#can modify the requested section
  579: 		return 1;
  580: 	    } else {
  581: 		# can't modify the request section
  582: 		return 0;
  583: 	    }
  584: 	}
  585:     }
  586:     #can't modify
  587:     return 0;
  588: }
  589: 
  590: #--- Retrieve the grade status of a student for all the parts
  591: sub student_gradeStatus {
  592:     my ($symb,$udom,$uname,$partlist) = @_;
  593:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
  594:     my %partstatus = ();
  595:     foreach (@$partlist) {
  596: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
  597: 	$status              = 'nothing' if ($status eq '');
  598: 	$partstatus{$_}      = $status;
  599: 	my $subkey           = "resource.$_.submitted_by";
  600: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
  601:     }
  602:     return %partstatus;
  603: }
  604: 
  605: # hidden form and javascript that calls the form
  606: # Use by verifyscript and viewgrades
  607: # Shows a student's view of problem and submission
  608: sub jscriptNform {
  609:     my ($symb) = @_;
  610:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  611:     my $jscript= &Apache::lonhtmlcommon::scripttag(
  612: 	'    function viewOneStudent(user,domain) {'."\n".
  613: 	'	document.onestudent.student.value = user;'."\n".
  614: 	'	document.onestudent.userdom.value = domain;'."\n".
  615: 	'	document.onestudent.submit();'."\n".
  616: 	'    }'."\n".
  617: 	"\n");
  618:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
  619: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  620: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
  621: 	'<input type="hidden" name="command" value="submission" />'."\n".
  622: 	'<input type="hidden" name="student" value="" />'."\n".
  623: 	'<input type="hidden" name="userdom" value="" />'."\n".
  624: 	'</form>'."\n";
  625:     return $jscript;
  626: }
  627: 
  628: 
  629: 
  630: # Given the score (as a number [0-1] and the weight) what is the final
  631: # point value? This function will round to the nearest tenth, third,
  632: # or quarter if one of those is within the tolerance of .00001.
  633: sub compute_points {
  634:     my ($score, $weight) = @_;
  635:     
  636:     my $tolerance = .00001;
  637:     my $points = $score * $weight;
  638: 
  639:     # Check for nearness to 1/x.
  640:     my $check_for_nearness = sub {
  641:         my ($factor) = @_;
  642:         my $num = ($points * $factor) + $tolerance;
  643:         my $floored_num = floor($num);
  644:         if ($num - $floored_num < 2 * $tolerance * $factor) {
  645:             return $floored_num / $factor;
  646:         }
  647:         return $points;
  648:     };
  649: 
  650:     $points = $check_for_nearness->(10);
  651:     $points = $check_for_nearness->(3);
  652:     $points = $check_for_nearness->(4);
  653:     
  654:     return $points;
  655: }
  656: 
  657: #------------------ End of general use routines --------------------
  658: 
  659: #
  660: # Find most similar essay
  661: #
  662: 
  663: sub most_similar {
  664:     my ($uname,$udom,$uessay,$old_essays)=@_;
  665: 
  666: # ignore spaces and punctuation
  667: 
  668:     $uessay=~s/\W+/ /gs;
  669: 
  670: # ignore empty submissions (occuring when only files are sent)
  671: 
  672:     unless ($uessay=~/\w+/s) { return ''; }
  673: 
  674: # these will be returned. Do not care if not at least 50 percent similar
  675:     my $limit=0.6;
  676:     my $sname='';
  677:     my $sdom='';
  678:     my $scrsid='';
  679:     my $sessay='';
  680: # go through all essays ...
  681:     foreach my $tkey (keys(%$old_essays)) {
  682: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
  683: # ... except the same student
  684:         next if (($tname eq $uname) && ($tdom eq $udom));
  685: 	my $tessay=$old_essays->{$tkey};
  686: 	$tessay=~s/\W+/ /gs;
  687: # String similarity gives up if not even limit
  688: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
  689: # Found one
  690: 	if ($tsimilar>$limit) {
  691: 	    $limit=$tsimilar;
  692: 	    $sname=$tname;
  693: 	    $sdom=$tdom;
  694: 	    $scrsid=$tcrsid;
  695: 	    $sessay=$old_essays->{$tkey};
  696: 	}
  697:     }
  698:     if ($limit>0.6) {
  699:        return ($sname,$sdom,$scrsid,$sessay,$limit);
  700:     } else {
  701:        return ('','','','',0);
  702:     }
  703: }
  704: 
  705: #-------------------------------------------------------------------
  706: 
  707: #------------------------------------ Receipt Verification Routines
  708: #
  709: 
  710: sub initialverifyreceipt {
  711:    my ($request,$symb) = @_;
  712:    &commonJSfunctions($request);
  713:    return '<form name="gradingMenu"><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
  714:         &Apache::lonnet::recprefix($env{'request.course.id'}).
  715:         '-<input type="text" name="receipt" size="4" />'.
  716:         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  717:         '<input type="hidden" name="command" value="verify" />'.
  718:         "</form>\n";
  719: }
  720: 
  721: #--- Check whether a receipt number is valid.---
  722: sub verifyreceipt {
  723:     my ($request,$symb)  = @_;
  724: 
  725:     my $courseid = $env{'request.course.id'};
  726:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
  727: 	$env{'form.receipt'};
  728:     $receipt     =~ s/[^\-\d]//g;
  729: 
  730:     my $title.=
  731: 	'<h3><span class="LC_info">'.
  732: 	&mt('Verifying Receipt Number [_1]',$receipt).
  733: 	'</span></h3>'."\n";
  734: 
  735:     my ($string,$contents,$matches) = ('','',0);
  736:     my (undef,undef,$fullname) = &getclasslist('all','0');
  737:     
  738:     my $receiptparts=0;
  739:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
  740: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
  741:     my $parts=['0'];
  742:     if ($receiptparts) {
  743:         my $res_error; 
  744:         ($parts)=&response_type($symb,\$res_error);
  745:         if ($res_error) {
  746:             return &navmap_errormsg();
  747:         } 
  748:     }
  749:     
  750:     my $header = 
  751: 	&Apache::loncommon::start_data_table().
  752: 	&Apache::loncommon::start_data_table_header_row().
  753: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
  754: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
  755: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
  756:     if ($receiptparts) {
  757: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
  758:     }
  759:     $header.=
  760: 	&Apache::loncommon::end_data_table_header_row();
  761: 
  762:     foreach (sort 
  763: 	     {
  764: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  765: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  766: 		 }
  767: 		 return $a cmp $b;
  768: 	     } (keys(%$fullname))) {
  769: 	my ($uname,$udom)=split(/\:/);
  770: 	foreach my $part (@$parts) {
  771: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
  772: 		$contents.=
  773: 		    &Apache::loncommon::start_data_table_row().
  774: 		    '<td>&nbsp;'."\n".
  775: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
  776: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
  777: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
  778: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
  779: 		if ($receiptparts) {
  780: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
  781: 		}
  782: 		$contents.= 
  783: 		    &Apache::loncommon::end_data_table_row()."\n";
  784: 		
  785: 		$matches++;
  786: 	    }
  787: 	}
  788:     }
  789:     if ($matches == 0) {
  790:         $string = $title
  791:                  .'<p class="LC_warning">'
  792:                  .&mt('No match found for the above receipt number.')
  793:                  .'</p>';
  794:     } else {
  795: 	$string = &jscriptNform($symb).$title.
  796: 	    '<p>'.
  797: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
  798: 	    '</p>'.
  799: 	    $header.
  800: 	    $contents.
  801: 	    &Apache::loncommon::end_data_table()."\n";
  802:     }
  803:     return $string;
  804: }
  805: 
  806: #--- This is called by a number of programs.
  807: #--- Called from the Grading Menu - View/Grade an individual student
  808: #--- Also called directly when one clicks on the subm button 
  809: #    on the problem page.
  810: sub listStudents {
  811:     my ($request,$symb,$submitonly) = @_;
  812: 
  813:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
  814:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
  815:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
  816:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
  817:     unless ($submitonly) {
  818:        $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
  819:     }
  820: 
  821:     my $result='<h3><span class="LC_info">&nbsp;'
  822: 	.&mt("View/Grade/Regrade Submissions for a Student or a Group of Students")
  823: 	.'</span></h3>';
  824: 
  825:     my ($partlist,$handgrade,$responseType) = &response_type($symb
  826: #,$res_error
  827:     );
  828: 
  829:     my %lt = &Apache::lonlocal::texthash (
  830: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
  831: 		'single'   => 'Please select the student before clicking on the Next button.',
  832: 	     );
  833:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
  834:     function checkSelect(checkBox) {
  835: 	var ctr=0;
  836: 	var sense="";
  837: 	if (checkBox.length > 1) {
  838: 	    for (var i=0; i<checkBox.length; i++) {
  839: 		if (checkBox[i].checked) {
  840: 		    ctr++;
  841: 		}
  842: 	    }
  843: 	    sense = '$lt{'multiple'}';
  844: 	} else {
  845: 	    if (checkBox.checked) {
  846: 		ctr = 1;
  847: 	    }
  848: 	    sense = '$lt{'single'}';
  849: 	}
  850: 	if (ctr == 0) {
  851: 	    alert(sense);
  852: 	    return false;
  853: 	}
  854: 	document.gradesub.submit();
  855:     }
  856: 
  857:     function reLoadList(formname) {
  858: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
  859: 	formname.command.value = 'submission';
  860: 	formname.submit();
  861:     }
  862: LISTJAVASCRIPT
  863: 
  864:     &commonJSfunctions($request);
  865:     $request->print($result);
  866: 
  867:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
  868:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
  869:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
  870: 	"\n";
  871: 	
  872:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
  873:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
  874:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
  875:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
  876:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
  877:                   .&Apache::lonhtmlcommon::row_closure();
  878:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
  879:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
  880:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
  881:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
  882:                   .&Apache::lonhtmlcommon::row_closure();
  883: 
  884:     my $submission_options;
  885:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
  886: 	$submission_options.=
  887: 	    '<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> '.&mt('essay part only').' </label>'."\n";
  888:     }
  889:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  890:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
  891:     $env{'form.Status'} = $saveStatus;
  892:     $submission_options.=
  893:         '<span class="LC_nobreak">'.
  894:         '<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> '.
  895:         &mt('last submission only').' </label></span>'."\n".
  896:         '<span class="LC_nobreak">'.
  897:         '<label><input type="radio" name="lastSub" value="last" /> '.
  898:         &mt('last submission &amp; parts info').' </label></span>'."\n".
  899:         '<span class="LC_nobreak">'.
  900:         '<label><input type="radio" name="lastSub" value="datesub" /> '.
  901:         &mt('by dates and submissions').'</label></span>'."\n".
  902:         '<span class="LC_nobreak">'.
  903:         '<label><input type="radio" name="lastSub" value="all" /> '.
  904:         &mt('all details').'</label></span>';
  905:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
  906:                   .$submission_options
  907:                   .&Apache::lonhtmlcommon::row_closure();
  908: 
  909:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
  910:                   .'<select name="increment">'
  911:                   .'<option value="1">'.&mt('Whole Points').'</option>'
  912:                   .'<option value=".5">'.&mt('Half Points').'</option>'
  913:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
  914:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
  915:                   .'</select>'
  916:                   .&Apache::lonhtmlcommon::row_closure();
  917: 
  918:     $gradeTable .= 
  919:         &build_section_inputs().
  920: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
  921: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
  922: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  923: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
  924: 
  925:     if (exists($env{'form.Status'})) {
  926: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
  927:     } else {
  928:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
  929:                       .&Apache::lonhtmlcommon::StatusOptions(
  930:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
  931:                       .&Apache::lonhtmlcommon::row_closure();
  932:     }
  933: 
  934:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
  935:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
  936:                   .&Apache::lonhtmlcommon::row_closure(1)
  937:                   .&Apache::lonhtmlcommon::end_pick_box();
  938: 
  939:     $gradeTable .= '<p>'
  940:                   .&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"
  941:                   .'<input type="hidden" name="command" value="processGroup" />'
  942:                   .'</p>';
  943: 
  944: # checkall buttons
  945:     $gradeTable.=&check_script('gradesub', 'stuinfo');
  946:     $gradeTable.='<input type="button" '."\n".
  947:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
  948:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
  949:     $gradeTable.=&check_buttons();
  950:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
  951:     $gradeTable.= &Apache::loncommon::start_data_table().
  952: 	&Apache::loncommon::start_data_table_header_row();
  953:     my $loop = 0;
  954:     while ($loop < 2) {
  955: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
  956: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
  957: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
  958: 	    foreach my $part (sort(@$partlist)) {
  959: 		my $display_part=
  960: 		    &get_display_part((split(/_/,$part))[0],$symb);
  961: 		$gradeTable.=
  962: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
  963: 	    }
  964: 	} elsif ($submitonly eq 'queued') {
  965: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
  966: 	}
  967: 	$loop++;
  968: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
  969:     }
  970:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
  971: 
  972:     my $ctr = 0;
  973:     foreach my $student (sort 
  974: 			 {
  975: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  976: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  977: 			     }
  978: 			     return $a cmp $b;
  979: 			 }
  980: 			 (keys(%$fullname))) {
  981: 	my ($uname,$udom) = split(/:/,$student);
  982: 
  983: 	my %status = ();
  984: 
  985: 	if ($submitonly eq 'queued') {
  986: 	    my %queue_status = 
  987: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
  988: 							$udom,$uname);
  989: 	    next if (!defined($queue_status{'gradingqueue'}));
  990: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
  991: 	}
  992: 
  993: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
  994: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
  995: 	    my $submitted = 0;
  996: 	    my $graded = 0;
  997: 	    my $incorrect = 0;
  998: 	    foreach (keys(%status)) {
  999: 		$submitted = 1 if ($status{$_} ne 'nothing');
 1000: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
 1001: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
 1002: 		
 1003: 		my ($foo,$partid,$foo1) = split(/\./,$_);
 1004: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 1005: 		    $submitted = 0;
 1006: 		    my ($part)=split(/\./,$partid);
 1007: 		    $gradeTable.='<input type="hidden" name="'.
 1008: 			$student.':'.$part.':submitted_by" value="'.
 1009: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
 1010: 		}
 1011: 	    }
 1012: 	    
 1013: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 1014: 				     $submitonly eq 'incorrect' ||
 1015: 				     $submitonly eq 'graded'));
 1016: 	    next if (!$graded && ($submitonly eq 'graded'));
 1017: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 1018: 	}
 1019: 
 1020: 	$ctr++;
 1021: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
 1022:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
 1023: 	if ( $perm{'vgr'} eq 'F' ) {
 1024: 	    if ($ctr%2 ==1) {
 1025: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
 1026: 	    }
 1027: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
 1028:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
 1029:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
 1030: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
 1031: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
 1032: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
 1033: 
 1034: 	    if ($submitonly ne 'all') {
 1035: 		foreach (sort(keys(%status))) {
 1036: 		    next if ($_ =~ /^resource.*?submitted_by$/);
 1037: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
 1038: 		}
 1039: 	    }
 1040: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
 1041: 	    if ($ctr%2 ==0) {
 1042: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
 1043: 	    }
 1044: 	}
 1045:     }
 1046:     if ($ctr%2 ==1) {
 1047: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
 1048: 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1049: 		foreach (@$partlist) {
 1050: 		    $gradeTable.='<td>&nbsp;</td>';
 1051: 		}
 1052: 	    } elsif ($submitonly eq 'queued') {
 1053: 		$gradeTable.='<td>&nbsp;</td>';
 1054: 	    }
 1055: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
 1056:     }
 1057: 
 1058:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
 1059:         '<input type="button" '.
 1060:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
 1061:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
 1062:     if ($ctr == 0) {
 1063: 	my $num_students=(scalar(keys(%$fullname)));
 1064: 	if ($num_students eq 0) {
 1065: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
 1066: 	} else {
 1067: 	    my $submissions='submissions';
 1068: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
 1069: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
 1070: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
 1071: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
 1072: 		&mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
 1073: 		    $num_students).
 1074: 		'</span><br />';
 1075: 	}
 1076:     } elsif ($ctr == 1) {
 1077: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
 1078:     }
 1079:     $request->print($gradeTable);
 1080:     return '';
 1081: }
 1082: 
 1083: #---- Called from the listStudents routine
 1084: 
 1085: sub check_script {
 1086:     my ($form, $type)=@_;
 1087:     my $chkallscript= &Apache::lonhtmlcommon::scripttag('
 1088:     function checkall() {
 1089:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1090:             ele = document.forms.'.$form.'.elements[i];
 1091:             if (ele.name == "'.$type.'") {
 1092:             document.forms.'.$form.'.elements[i].checked=true;
 1093:                                        }
 1094:         }
 1095:     }
 1096: 
 1097:     function checksec() {
 1098:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1099:             ele = document.forms.'.$form.'.elements[i];
 1100:            string = document.forms.'.$form.'.chksec.value;
 1101:            if
 1102:           (ele.value.indexOf(":::SECTION"+string)>0) {
 1103:               document.forms.'.$form.'.elements[i].checked=true;
 1104:             }
 1105:         }
 1106:     }
 1107: 
 1108: 
 1109:     function uncheckall() {
 1110:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1111:             ele = document.forms.'.$form.'.elements[i];
 1112:             if (ele.name == "'.$type.'") {
 1113:             document.forms.'.$form.'.elements[i].checked=false;
 1114:                                        }
 1115:         }
 1116:     }
 1117: 
 1118: '."\n");
 1119:     return $chkallscript;
 1120: }
 1121: 
 1122: sub check_buttons {
 1123:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
 1124:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
 1125:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
 1126:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
 1127:     return $buttons;
 1128: }
 1129: 
 1130: #     Displays the submissions for one student or a group of students
 1131: sub processGroup {
 1132:     my ($request,$symb)  = @_;
 1133:     my $ctr        = 0;
 1134:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1135:     my $total      = scalar(@stuchecked)-1;
 1136: 
 1137:     foreach my $student (@stuchecked) {
 1138: 	my ($uname,$udom,$fullname) = split(/:/,$student);
 1139: 	$env{'form.student'}        = $uname;
 1140: 	$env{'form.userdom'}        = $udom;
 1141: 	$env{'form.fullname'}       = $fullname;
 1142: 	&submission($request,$ctr,$total,$symb);
 1143: 	$ctr++;
 1144:     }
 1145:     return '';
 1146: }
 1147: 
 1148: #------------------------------------------------------------------------------------
 1149: #
 1150: #-------------------------- Next few routines handles grading by student, essentially
 1151: #                           handles essay response type problem/part
 1152: #
 1153: #--- Javascript to handle the submission page functionality ---
 1154: sub sub_page_js {
 1155:     my $request = shift;
 1156: 	    my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 1157:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1158:     function updateRadio(formname,id,weight) {
 1159: 	var gradeBox = formname["GD_BOX"+id];
 1160: 	var radioButton = formname["RADVAL"+id];
 1161: 	var oldpts = formname["oldpts"+id].value;
 1162: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
 1163: 	gradeBox.value = pts;
 1164: 	var resetbox = false;
 1165: 	if (isNaN(pts) || pts < 0) {
 1166: 	    alert("$alertmsg"+pts);
 1167: 	    for (var i=0; i<radioButton.length; i++) {
 1168: 		if (radioButton[i].checked) {
 1169: 		    gradeBox.value = i;
 1170: 		    resetbox = true;
 1171: 		}
 1172: 	    }
 1173: 	    if (!resetbox) {
 1174: 		formtextbox.value = "";
 1175: 	    }
 1176: 	    return;
 1177: 	}
 1178: 
 1179: 	if (pts > weight) {
 1180: 	    var resp = confirm("You entered a value ("+pts+
 1181: 			       ") greater than the weight for the part. Accept?");
 1182: 	    if (resp == false) {
 1183: 		gradeBox.value = oldpts;
 1184: 		return;
 1185: 	    }
 1186: 	}
 1187: 
 1188: 	for (var i=0; i<radioButton.length; i++) {
 1189: 	    radioButton[i].checked=false;
 1190: 	    if (pts == i && pts != "") {
 1191: 		radioButton[i].checked=true;
 1192: 	    }
 1193: 	}
 1194: 	updateSelect(formname,id);
 1195: 	formname["stores"+id].value = "0";
 1196:     }
 1197: 
 1198:     function writeBox(formname,id,pts) {
 1199: 	var gradeBox = formname["GD_BOX"+id];
 1200: 	if (checkSolved(formname,id) == 'update') {
 1201: 	    gradeBox.value = pts;
 1202: 	} else {
 1203: 	    var oldpts = formname["oldpts"+id].value;
 1204: 	    gradeBox.value = oldpts;
 1205: 	    var radioButton = formname["RADVAL"+id];
 1206: 	    for (var i=0; i<radioButton.length; i++) {
 1207: 		radioButton[i].checked=false;
 1208: 		if (i == oldpts) {
 1209: 		    radioButton[i].checked=true;
 1210: 		}
 1211: 	    }
 1212: 	}
 1213: 	formname["stores"+id].value = "0";
 1214: 	updateSelect(formname,id);
 1215: 	return;
 1216:     }
 1217: 
 1218:     function clearRadBox(formname,id) {
 1219: 	if (checkSolved(formname,id) == 'noupdate') {
 1220: 	    updateSelect(formname,id);
 1221: 	    return;
 1222: 	}
 1223: 	gradeSelect = formname["GD_SEL"+id];
 1224: 	for (var i=0; i<gradeSelect.length; i++) {
 1225: 	    if (gradeSelect[i].selected) {
 1226: 		var selectx=i;
 1227: 	    }
 1228: 	}
 1229: 	var stores = formname["stores"+id];
 1230: 	if (selectx == stores.value) { return };
 1231: 	var gradeBox = formname["GD_BOX"+id];
 1232: 	gradeBox.value = "";
 1233: 	var radioButton = formname["RADVAL"+id];
 1234: 	for (var i=0; i<radioButton.length; i++) {
 1235: 	    radioButton[i].checked=false;
 1236: 	}
 1237: 	stores.value = selectx;
 1238:     }
 1239: 
 1240:     function checkSolved(formname,id) {
 1241: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
 1242: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
 1243: 	    if (!reply) {return "noupdate";}
 1244: 	    formname.overRideScore.value = 'yes';
 1245: 	}
 1246: 	return "update";
 1247:     }
 1248: 
 1249:     function updateSelect(formname,id) {
 1250: 	formname["GD_SEL"+id][0].selected = true;
 1251: 	return;
 1252:     }
 1253: 
 1254: //=========== Check that a point is assigned for all the parts  ============
 1255:     function checksubmit(formname,val,total,parttot) {
 1256: 	formname.gradeOpt.value = val;
 1257: 	if (val == "Save & Next") {
 1258: 	    for (i=0;i<=total;i++) {
 1259: 		for (j=0;j<parttot;j++) {
 1260: 		    var partid = formname["partid"+i+"_"+j].value;
 1261: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1262: 			var points = formname["GD_BOX"+i+"_"+partid].value;
 1263: 			if (points == "") {
 1264: 			    var name = formname["name"+i].value;
 1265: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
 1266: 			    var resp = confirm("You did not assign a score for "+studentID+
 1267: 					       ", part "+partid+". Continue?");
 1268: 			    if (resp == false) {
 1269: 				formname["GD_BOX"+i+"_"+partid].focus();
 1270: 				return false;
 1271: 			    }
 1272: 			}
 1273: 		    }
 1274: 		    
 1275: 		}
 1276: 	    }
 1277: 	    
 1278: 	}
 1279: 	if (val == "Grade Student") {
 1280: 	    if (formname.Status.value == "") {
 1281: 		formname.Status.value = "Active";
 1282: 	    }
 1283: 	    formname.studentNo.value = total;
 1284: 	}
 1285: 	formname.submit();
 1286:     }
 1287: 
 1288: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1289:     function checkSubmitPage(formname,total) {
 1290: 	noscore = new Array(100);
 1291: 	var ptr = 0;
 1292: 	for (i=1;i<total;i++) {
 1293: 	    var partid = formname["q_"+i].value;
 1294: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1295: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1296: 		var status = formname["solved"+i+"_"+partid].value;
 1297: 		if (points == "" && status != "correct_by_student") {
 1298: 		    noscore[ptr] = i;
 1299: 		    ptr++;
 1300: 		}
 1301: 	    }
 1302: 	}
 1303: 	if (ptr != 0) {
 1304: 	    var sense = ptr == 1 ? ": " : "s: ";
 1305: 	    var prolist = "";
 1306: 	    if (ptr == 1) {
 1307: 		prolist = noscore[0];
 1308: 	    } else {
 1309: 		var i = 0;
 1310: 		while (i < ptr-1) {
 1311: 		    prolist += noscore[i]+", ";
 1312: 		    i++;
 1313: 		}
 1314: 		prolist += "and "+noscore[i];
 1315: 	    }
 1316: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1317: 	    if (resp == false) {
 1318: 		return false;
 1319: 	    }
 1320: 	}
 1321: 
 1322: 	formname.submit();
 1323:     }
 1324: SUBJAVASCRIPT
 1325: }
 1326: 
 1327: #--- javascript for essay type problem --
 1328: sub sub_page_kw_js {
 1329:     my $request = shift;
 1330:     my $iconpath = $request->dir_config('lonIconsURL');
 1331:     &commonJSfunctions($request);
 1332: 
 1333:     my $inner_js_msg_central= &Apache::lonhtmlcommon::scripttag(<<INNERJS);
 1334:     function checkInput() {
 1335:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1336:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1337:       var usrctr = document.msgcenter.usrctr.value;
 1338:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1339:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1340: 
 1341:       var msgchk = "";
 1342:       if (document.msgcenter.subchk.checked) {
 1343:          msgchk = "msgsub,";
 1344:       }
 1345:       var includemsg = 0;
 1346:       for (var i=1; i<=nmsg; i++) {
 1347:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1348:           var frmmsg = document.msgcenter["msg"+i];
 1349:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1350:           var showflg = opener.document.SCORE["shownOnce"+i];
 1351:           showflg.value = "1";
 1352:           var chkbox = document.msgcenter["msgn"+i];
 1353:           if (chkbox.checked) {
 1354:              msgchk += "savemsg"+i+",";
 1355:              includemsg = 1;
 1356:           }
 1357:       }
 1358:       if (document.msgcenter.newmsgchk.checked) {
 1359:          msgchk += "newmsg"+usrctr;
 1360:          includemsg = 1;
 1361:       }
 1362:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1363:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1364:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1365:       includemsg.value = msgchk;
 1366: 
 1367:       self.close()
 1368: 
 1369:     }
 1370: INNERJS
 1371: 
 1372:     my $inner_js_highlight_central= &Apache::lonhtmlcommon::scripttag(<<INNERJS);
 1373:     function updateChoice(flag) {
 1374:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1375:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1376:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1377:       opener.document.SCORE.refresh.value = "on";
 1378:       if (opener.document.SCORE.keywords.value!=""){
 1379:          opener.document.SCORE.submit();
 1380:       }
 1381:       self.close()
 1382:     }
 1383: INNERJS
 1384: 
 1385:     my $start_page_msg_central = 
 1386:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1387: 				       {'js_ready'  => 1,
 1388: 					'only_body' => 1,
 1389: 					'bgcolor'   =>'#FFFFFF',});
 1390:     my $end_page_msg_central = 
 1391: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1392: 
 1393: 
 1394:     my $start_page_highlight_central = 
 1395:         &Apache::loncommon::start_page('Highlight Central',
 1396: 				       $inner_js_highlight_central,
 1397: 				       {'js_ready'  => 1,
 1398: 					'only_body' => 1,
 1399: 					'bgcolor'   =>'#FFFFFF',});
 1400:     my $end_page_highlight_central = 
 1401: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1402: 
 1403:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1404:     $docopen=~s/^document\.//;
 1405:     my $alertmsg = &mt('Please select a word or group of words from document and then click this link.');
 1406:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1407: 
 1408: //===================== Show list of keywords ====================
 1409:   function keywords(formname) {
 1410:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
 1411:     if (nret==null) return;
 1412:     formname.keywords.value = nret;
 1413: 
 1414:     if (formname.keywords.value != "") {
 1415: 	formname.refresh.value = "on";
 1416: 	formname.submit();
 1417:     }
 1418:     return;
 1419:   }
 1420: 
 1421: //===================== Script to view submitted by ==================
 1422:   function viewSubmitter(submitter) {
 1423:     document.SCORE.refresh.value = "on";
 1424:     document.SCORE.NCT.value = "1";
 1425:     document.SCORE.unamedom0.value = submitter;
 1426:     document.SCORE.submit();
 1427:     return;
 1428:   }
 1429: 
 1430: //===================== Script to add keyword(s) ==================
 1431:   function getSel() {
 1432:     if (document.getSelection) txt = document.getSelection();
 1433:     else if (document.selection) txt = document.selection.createRange().text;
 1434:     else return;
 1435:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1436:     if (cleantxt=="") {
 1437: 	alert("$alertmsg");
 1438: 	return;
 1439:     }
 1440:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
 1441:     if (nret==null) return;
 1442:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1443:     if (document.SCORE.keywords.value != "") {
 1444: 	document.SCORE.refresh.value = "on";
 1445: 	document.SCORE.submit();
 1446:     }
 1447:     return;
 1448:   }
 1449: 
 1450: //====================== Script for composing message ==============
 1451:    // preload images
 1452:    img1 = new Image();
 1453:    img1.src = "$iconpath/mailbkgrd.gif";
 1454:    img2 = new Image();
 1455:    img2.src = "$iconpath/mailto.gif";
 1456: 
 1457:   function msgCenter(msgform,usrctr,fullname) {
 1458:     var Nmsg  = msgform.savemsgN.value;
 1459:     savedMsgHeader(Nmsg,usrctr,fullname);
 1460:     var subject = msgform.msgsub.value;
 1461:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1462:     re = /msgsub/;
 1463:     var shwsel = "";
 1464:     if (re.test(msgchk)) { shwsel = "checked" }
 1465:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1466:     displaySubject(checkEntities(subject),shwsel);
 1467:     for (var i=1; i<=Nmsg; i++) {
 1468: 	var testmsg = "savemsg"+i+",";
 1469: 	re = new RegExp(testmsg,"g");
 1470: 	shwsel = "";
 1471: 	if (re.test(msgchk)) { shwsel = "checked" }
 1472: 	var message = document.SCORE["savemsg"+i].value;
 1473: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1474: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1475: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1476:     }
 1477:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1478:     shwsel = "";
 1479:     re = /newmsg/;
 1480:     if (re.test(msgchk)) { shwsel = "checked" }
 1481:     newMsg(newmsg,shwsel);
 1482:     msgTail(); 
 1483:     return;
 1484:   }
 1485: 
 1486:   function checkEntities(strx) {
 1487:     if (strx.length == 0) return strx;
 1488:     var orgStr = ["&", "<", ">", '"']; 
 1489:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1490:     var counter = 0;
 1491:     while (counter < 4) {
 1492: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1493: 	counter++;
 1494:     }
 1495:     return strx;
 1496:   }
 1497: 
 1498:   function strReplace(strx, orgStr, newStr) {
 1499:     return strx.split(orgStr).join(newStr);
 1500:   }
 1501: 
 1502:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1503:     var height = 70*Nmsg+250;
 1504:     var scrollbar = "no";
 1505:     if (height > 600) {
 1506: 	height = 600;
 1507: 	scrollbar = "yes";
 1508:     }
 1509:     var xpos = (screen.width-600)/2;
 1510:     xpos = (xpos < 0) ? '0' : xpos;
 1511:     var ypos = (screen.height-height)/2-30;
 1512:     ypos = (ypos < 0) ? '0' : ypos;
 1513: 
 1514:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
 1515:     pWin.focus();
 1516:     pDoc = pWin.document;
 1517:     pDoc.$docopen;
 1518:     pDoc.write('$start_page_msg_central');
 1519: 
 1520:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1521:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1522:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
 1523: 
 1524:     pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
 1525:     pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
 1526:     pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
 1527: }
 1528:     function displaySubject(msg,shwsel) {
 1529:     pDoc = pWin.document;
 1530:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1531:     pDoc.write("<td>Subject<\\/td>");
 1532:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1533:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
 1534: }
 1535: 
 1536:   function displaySavedMsg(ctr,msg,shwsel) {
 1537:     pDoc = pWin.document;
 1538:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1539:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
 1540:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1541:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
 1542: }
 1543: 
 1544:   function newMsg(newmsg,shwsel) {
 1545:     pDoc = pWin.document;
 1546:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1547:     pDoc.write("<td align=\\"center\\">New<\\/td>");
 1548:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1549:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
 1550: }
 1551: 
 1552:   function msgTail() {
 1553:     pDoc = pWin.document;
 1554:     pDoc.write("<\\/table>");
 1555:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1556:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1557:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onclick=\\"self.close()\\"><br /><br />");
 1558:     pDoc.write("<\\/form>");
 1559:     pDoc.write('$end_page_msg_central');
 1560:     pDoc.close();
 1561: }
 1562: 
 1563: //====================== Script for keyword highlight options ==============
 1564:   function kwhighlight() {
 1565:     var kwclr    = document.SCORE.kwclr.value;
 1566:     var kwsize   = document.SCORE.kwsize.value;
 1567:     var kwstyle  = document.SCORE.kwstyle.value;
 1568:     var redsel = "";
 1569:     var grnsel = "";
 1570:     var blusel = "";
 1571:     if (kwclr=="red")   {var redsel="checked"};
 1572:     if (kwclr=="green") {var grnsel="checked"};
 1573:     if (kwclr=="blue")  {var blusel="checked"};
 1574:     var sznsel = "";
 1575:     var sz1sel = "";
 1576:     var sz2sel = "";
 1577:     if (kwsize=="0")  {var sznsel="checked"};
 1578:     if (kwsize=="+1") {var sz1sel="checked"};
 1579:     if (kwsize=="+2") {var sz2sel="checked"};
 1580:     var synsel = "";
 1581:     var syisel = "";
 1582:     var sybsel = "";
 1583:     if (kwstyle=="")    {var synsel="checked"};
 1584:     if (kwstyle=="<i>") {var syisel="checked"};
 1585:     if (kwstyle=="<b>") {var sybsel="checked"};
 1586:     highlightCentral();
 1587:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
 1588:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
 1589:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
 1590:     highlightend();
 1591:     return;
 1592:   }
 1593: 
 1594:   function highlightCentral() {
 1595: //    if (window.hwdWin) window.hwdWin.close();
 1596:     var xpos = (screen.width-400)/2;
 1597:     xpos = (xpos < 0) ? '0' : xpos;
 1598:     var ypos = (screen.height-330)/2-30;
 1599:     ypos = (ypos < 0) ? '0' : ypos;
 1600: 
 1601:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1602:     hwdWin.focus();
 1603:     var hDoc = hwdWin.document;
 1604:     hDoc.$docopen;
 1605:     hDoc.write('$start_page_highlight_central');
 1606:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1607:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options<\\/span><\\/h3><br /><br />");
 1608: 
 1609:     hDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
 1610:     hDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
 1611:     hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
 1612:   }
 1613: 
 1614:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1615:     var hDoc = hwdWin.document;
 1616:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1617:     hDoc.write("<td align=\\"left\\">");
 1618:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
 1619:     hDoc.write("<td align=\\"left\\">");
 1620:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
 1621:     hDoc.write("<td align=\\"left\\">");
 1622:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
 1623:     hDoc.write("<\\/tr>");
 1624:   }
 1625: 
 1626:   function highlightend() { 
 1627:     var hDoc = hwdWin.document;
 1628:     hDoc.write("<\\/table>");
 1629:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1630:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onclick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
 1631:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onclick=\\"self.close()\\"><br /><br />");
 1632:     hDoc.write("<\\/form>");
 1633:     hDoc.write('$end_page_highlight_central');
 1634:     hDoc.close();
 1635:   }
 1636: 
 1637: SUBJAVASCRIPT
 1638: }
 1639: 
 1640: sub get_increment {
 1641:     my $increment = $env{'form.increment'};
 1642:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1643:         $increment != .1) {
 1644:         $increment = 1;
 1645:     }
 1646:     return $increment;
 1647: }
 1648: 
 1649: sub gradeBox_start {
 1650:     return (
 1651:         &Apache::loncommon::start_data_table()
 1652:        .&Apache::loncommon::start_data_table_header_row()
 1653:        .'<th>'.&mt('Part').'</th>'
 1654:        .'<th>'.&mt('Points').'</th>'
 1655:        .'<th>&nbsp;</th>'
 1656:        .'<th>'.&mt('Assign Grade').'</th>'
 1657:        .'<th>'.&mt('Weight').'</th>'
 1658:        .'<th>'.&mt('Grade Status').'</th>'
 1659:        .&Apache::loncommon::end_data_table_header_row()
 1660:     );
 1661: }
 1662: 
 1663: sub gradeBox_end {
 1664:     return (
 1665:         &Apache::loncommon::end_data_table()
 1666:     );
 1667: }
 1668: #--- displays the grading box, used in essay type problem and grading by page/sequence
 1669: sub gradeBox {
 1670:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 1671:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1672: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 1673:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 1674:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
 1675:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
 1676:     $wgt       = ($wgt > 0 ? $wgt : '1');
 1677:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 1678: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 1679:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 1680:     my $display_part= &get_display_part($partid,$symb);
 1681:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 1682: 				       [$partid]);
 1683:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 1684:     if ($last_resets{$partid}) {
 1685:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 1686:     }
 1687:     $result.=&Apache::loncommon::start_data_table_row();
 1688:     my $ctr = 0;
 1689:     my $thisweight = 0;
 1690:     my $increment = &get_increment();
 1691: 
 1692:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 1693:     while ($thisweight<=$wgt) {
 1694: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 1695:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 1696: 	    $thisweight.')" value="'.$thisweight.'" '.
 1697: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 1698: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 1699:         $thisweight += $increment;
 1700: 	$ctr++;
 1701:     }
 1702:     $radio.='</tr></table>';
 1703: 
 1704:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 1705: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 1706: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 1707: 	$wgt.')" /></td>'."\n";
 1708:     $line.='<td>/'.$wgt.' '.$wgtmsg.
 1709: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 1710: 	' </td>'."\n";
 1711:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
 1712: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 1713:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 1714: 	$line.='<option></option>'.
 1715: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
 1716:     } else {
 1717: 	$line.='<option selected="selected"></option>'.
 1718: 	    '<option value="excused" >'.&mt('excused').'</option>';
 1719:     }
 1720:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
 1721: 
 1722: 
 1723:     $result .= 
 1724: 	    '<td>'.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
 1725:     $result.=&Apache::loncommon::end_data_table_row();
 1726:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 1727: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 1728: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 1729: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 1730:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 1731:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 1732:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 1733:         $aggtries.'" />'."\n";
 1734:     my $res_error;
 1735:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
 1736:     if ($res_error) {
 1737:         return &navmap_errormsg();
 1738:     }
 1739:     return $result;
 1740: }
 1741: 
 1742: sub handback_box {
 1743:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error) = @_;
 1744:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
 1745:     my (@respids);
 1746:      my @part_response_id = &flatten_responseType($responseType);
 1747:     foreach my $part_response_id (@part_response_id) {
 1748:     	my ($part,$resp) = @{ $part_response_id };
 1749:         if ($part eq $partid) {
 1750:             push(@respids,$resp);
 1751:         }
 1752:     }
 1753:     my $result;
 1754:     foreach my $respid (@respids) {
 1755: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 1756: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 1757: 	next if (!@$files);
 1758: 	my $file_counter = 1;
 1759: 	foreach my $file (@$files) {
 1760: 	    if ($file =~ /\/portfolio\//) {
 1761:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 1762:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
 1763:     	        $file_disp = "$name.$ext";
 1764:     	        $file = $file_path.$file_disp;
 1765:     	        $result.=&mt('Return commented version of [_1] to student.',
 1766:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 1767:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 1768:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
 1769:     	        $result.='('.&mt('File will be uploaded when you click on Save &amp; Next below.').')<br />';
 1770:     	        $file_counter++;
 1771: 	    }
 1772: 	}
 1773:     }
 1774:     return $result;    
 1775: }
 1776: 
 1777: sub show_problem {
 1778:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 1779:     my $rendered;
 1780:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 1781:     &Apache::lonxml::remember_problem_counter();
 1782:     if ($mode eq 'both' or $mode eq 'text') {
 1783: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 1784: 						       $env{'request.course.id'},
 1785: 						       undef,\%form);
 1786:     }
 1787:     if ($removeform) {
 1788: 	$rendered=~s|<form(.*?)>||g;
 1789: 	$rendered=~s|</form>||g;
 1790: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 1791:     }
 1792:     my $companswer;
 1793:     if ($mode eq 'both' or $mode eq 'answer') {
 1794: 	&Apache::lonxml::restore_problem_counter();
 1795: 	$companswer=
 1796: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 1797: 						    $env{'request.course.id'},
 1798: 						    %form);
 1799:     }
 1800:     if ($removeform) {
 1801: 	$companswer=~s|<form(.*?)>||g;
 1802: 	$companswer=~s|</form>||g;
 1803: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 1804:     }
 1805:     $rendered=
 1806:         '<div class="LC_Box">'
 1807:        .'<h3 class="LC_hcell">'.&mt('View of the problem').'</h3>'
 1808:        .$rendered
 1809:        .'</div>';
 1810:     $companswer=
 1811:         '<div class="LC_Box">'
 1812:        .'<h3 class="LC_hcell">'.&mt('Correct answer').'</h3>'
 1813:        .$companswer
 1814:        .'</div>';
 1815:     my $result;
 1816:     if ($mode eq 'both') {
 1817:         $result=$rendered.$companswer;
 1818:     } elsif ($mode eq 'text') {
 1819:         $result=$rendered;
 1820:     } elsif ($mode eq 'answer') {
 1821:         $result=$companswer;
 1822:     }
 1823:     return $result;
 1824: }
 1825: 
 1826: sub files_exist {
 1827:     my ($r, $symb) = @_;
 1828:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1829: 
 1830:     foreach my $student (@students) {
 1831:         my ($uname,$udom,$fullname) = split(/:/,$student);
 1832:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 1833: 					      $udom,$uname);
 1834:         my ($string,$timestamp)= &get_last_submission(\%record);
 1835:         foreach my $submission (@$string) {
 1836:             my ($partid,$respid) =
 1837: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 1838:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 1839: 					   \%record);
 1840:             return 1 if (@$files);
 1841:         }
 1842:     }
 1843:     return 0;
 1844: }
 1845: 
 1846: sub download_all_link {
 1847:     my ($r,$symb) = @_;
 1848:     my $all_students = 
 1849: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 1850: 
 1851:     my $parts =
 1852: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 1853: 
 1854:     my $identifier = &Apache::loncommon::get_cgi_id();
 1855:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 1856:                              'cgi.'.$identifier.'.symb' => $symb,
 1857:                              'cgi.'.$identifier.'.parts' => $parts,});
 1858:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 1859: 	      &mt('Download All Submitted Documents').'</a>');
 1860:     return
 1861: }
 1862: 
 1863: sub build_section_inputs {
 1864:     my $section_inputs;
 1865:     if ($env{'form.section'} eq '') {
 1866:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 1867:     } else {
 1868:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 1869:         foreach my $section (@sections) {
 1870:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 1871:         }
 1872:     }
 1873:     return $section_inputs;
 1874: }
 1875: 
 1876: # --------------------------- show submissions of a student, option to grade 
 1877: sub submission {
 1878:     my ($request,$counter,$total,$symb) = @_;
 1879:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 1880:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 1881:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 1882:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 1883: 
 1884:     my $probtitle=&Apache::lonnet::gettitle($symb); 
 1885:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 1886: 
 1887:     if (!&canview($usec)) {
 1888: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
 1889: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
 1890: 			$env{'request.course.id'}.')</span>');
 1891: 	return;
 1892:     }
 1893: 
 1894:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 1895:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 1896:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 1897:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 1898:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1899: 	'" src="'.$request->dir_config('lonIconsURL').
 1900: 	'/check.gif" height="16" border="0" />';
 1901: 
 1902:     my %old_essays;
 1903:     # header info
 1904:     if ($counter == 0) {
 1905: 	&sub_page_js($request);
 1906: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
 1907: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
 1908: 	    &download_all_link($request, $symb);
 1909: 	}
 1910: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>');
 1911: 
 1912: 	# option to display problem, only once else it cause problems 
 1913:         # with the form later since the problem has a form.
 1914: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 1915: 	    my $mode;
 1916: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 1917: 		$mode='both';
 1918: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 1919: 		$mode='text';
 1920: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 1921: 		$mode='answer';
 1922: 	    }
 1923: 	    &Apache::lonxml::clear_problem_counter();
 1924: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 1925: 	}
 1926: 
 1927: 	# kwclr is the only variable that is guaranteed to be non blank 
 1928:         # if this subroutine has been called once.
 1929: 	my %keyhash = ();
 1930: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
 1931: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 1932: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 1933: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 1934: 
 1935: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 1936: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 1937: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 1938: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 1939: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 1940: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
 1941: 		$keyhash{$symb.'_subject'} : $probtitle;
 1942: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 1943: 	}
 1944: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 1945: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 1946: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 1947: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 1948: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 1949: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 1950: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 1951: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 1952: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 1953: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 1954: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 1955: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 1956: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 1957: 			&build_section_inputs().
 1958: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 1959: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
 1960: 			'<input type="hidden" name="NCT"'.
 1961: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 1962: 	if ($env{'form.handgrade'} eq 'yes') {
 1963: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 1964: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 1965: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 1966: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
 1967: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 1968: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 1969: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 1970: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
 1971: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
 1972: 	    }
 1973: 	}
 1974: 	
 1975: 	my ($cts,$prnmsg) = (1,'');
 1976: 	while ($cts <= $env{'form.savemsgN'}) {
 1977: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 1978: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 1979: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 1980: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 1981: 		'" />'."\n".
 1982: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 1983: 	    $cts++;
 1984: 	}
 1985: 	$request->print($prnmsg);
 1986: 
 1987: 	if ($env{'form.handgrade'} eq 'yes') {
 1988: #
 1989: # Print out the keyword options line
 1990: #
 1991: 	    $request->print(<<KEYWORDS);
 1992: &nbsp;<b>Keyword Options:</b>&nbsp;
 1993: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
 1994: <a href="#" onmousedown="javascript:getSel(); return false"
 1995:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
 1996: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
 1997: KEYWORDS
 1998: #
 1999: # Load the other essays for similarity check
 2000: #
 2001:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 2002: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 2003: 	    $apath=&escape($apath);
 2004: 	    $apath=~s/\W/\_/gs;
 2005: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
 2006:         }
 2007:     }
 2008: 
 2009: # This is where output for one specific student would start
 2010:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
 2011:     $request->print(
 2012:         "\n\n"
 2013:        .'<div class="LC_grade_show_user'.$add_class.'">'
 2014:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
 2015:        ."\n"
 2016:     );
 2017: 
 2018:     # Show additional functions if allowed
 2019:     if ($perm{'vgr'}) {
 2020:         $request->print(
 2021:             &Apache::loncommon::track_student_link(
 2022:                 &mt('View recent activity'),
 2023:                 $uname,$udom,'check')
 2024:            .' '
 2025:         );
 2026:     }
 2027:     if ($perm{'opa'}) {
 2028:         $request->print(
 2029:             &Apache::loncommon::pprmlink(
 2030:                 &mt('Set/Change parameters'),
 2031:                 $uname,$udom,$symb,'check'));
 2032:     }
 2033: 
 2034:     # Show Problem
 2035:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2036: 	my $mode;
 2037: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2038: 	    $mode='both';
 2039: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2040: 	    $mode='text';
 2041: 	} elsif ($env{'form.vAns'} eq 'all') {
 2042: 	    $mode='answer';
 2043: 	}
 2044: 	&Apache::lonxml::clear_problem_counter();
 2045: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2046:     }
 2047: 
 2048:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2049:     my $res_error;
 2050:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2051:     if ($res_error) {
 2052:         $request->print(&navmap_errormsg());
 2053:         return;
 2054:     }
 2055: 
 2056:     # Display student info
 2057:     $request->print(($counter == 0 ? '' : '<br />'));
 2058: 
 2059:     my $result='<div class="LC_Box">'
 2060:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
 2061:     $result.='<input type="hidden" name="name'.$counter.
 2062:              '" value="'.$env{'form.fullname'}.'" />'."\n";
 2063:     if ($env{'form.handgrade'} eq 'no') {
 2064:         $result.='<p class="LC_info">'
 2065:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
 2066:                 ."</p>\n";
 2067:     }
 2068: 
 2069:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
 2070:     my $fullname;
 2071:     my $col_fullnames = [];
 2072:     if ($env{'form.handgrade'} eq 'yes') {
 2073: 	(my $sub_result,$fullname,$col_fullnames)=
 2074: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2075: 				 $counter);
 2076: 	$result.=$sub_result;
 2077:     }
 2078:     $request->print($result."\n");
 2079: 
 2080:     # print student answer/submission
 2081:     # Options are (1) Handgraded submission only
 2082:     #             (2) Last submission, includes submission that is not handgraded 
 2083:     #                  (for multi-response type part)
 2084:     #             (3) Last submission plus the parts info
 2085:     #             (4) The whole record for this student
 2086:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
 2087: 	my ($string,$timestamp)= &get_last_submission(\%record);
 2088: 	
 2089: 	my $lastsubonly;
 2090: 
 2091:         if ($$timestamp eq '') {
 2092:             $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
 2093:         } else {
 2094:             $lastsubonly =
 2095:                 '<div class="LC_grade_submissions_body">'
 2096:                .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
 2097: 
 2098: 	    my %seenparts;
 2099: 	    my @part_response_id = &flatten_responseType($responseType);
 2100: 	    foreach my $part (@part_response_id) {
 2101: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
 2102: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
 2103: 
 2104: 		my ($partid,$respid) = @{ $part };
 2105: 		my $display_part=&get_display_part($partid,$symb);
 2106: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2107: 		    if (exists($seenparts{$partid})) { next; }
 2108: 		    $seenparts{$partid}=1;
 2109: 		    my $submitby='<b>Part:</b> '.$display_part.
 2110: 			' <b>Collaborative submission by:</b> '.
 2111: 			'<a href="javascript:viewSubmitter(\''.
 2112: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
 2113: 			'\');" target="_self">'.
 2114: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
 2115: 		    $request->print($submitby);
 2116: 		    next;
 2117: 		}
 2118: 		my $responsetype = $responseType->{$partid}->{$respid};
 2119: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
 2120:                     $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
 2121:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2122:                         ' <span class="LC_internal_info">'.
 2123:                         '('.&mt('Part ID: [_1]',$respid).')'.
 2124:                         '</span>&nbsp; &nbsp;'.
 2125: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
 2126: 		    next;
 2127: 		}
 2128: 		foreach my $submission (@$string) {
 2129: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2130: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2131: 		    my ($ressub,$hide,$subval) = split(/:/,$submission,3);
 2132: 		    # Similarity check
 2133: 		    my $similar='';
 2134: 		    if($env{'form.checkPlag'}){
 2135: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2136: 			    &most_similar($uname,$udom,$subval,\%old_essays);
 2137: 			if ($osim) {
 2138: 			    $osim=int($osim*100.0);
 2139: 			    my %old_course_desc = 
 2140: 				&Apache::lonnet::coursedescription($ocrsid,
 2141: 								   {'one_time' => 1});
 2142: 
 2143:                             if ($hide) {
 2144:                                 $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
 2145:                                          &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
 2146:                             } else {
 2147: 			        $similar="<hr /><h3><span class=\"LC_warning\">".
 2148: 				    &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
 2149: 				        $osim,
 2150: 				        &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
 2151: 				        $old_course_desc{'description'},
 2152: 				        $old_course_desc{'num'},
 2153: 				        $old_course_desc{'domain'}).
 2154: 				    '</span></h3><blockquote><i>'.
 2155: 				    &keywords_highlight($oessay).
 2156: 				    '</i></blockquote><hr />';
 2157:                             }
 2158: 			}
 2159: 		    }
 2160: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
 2161: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
 2162: 			($env{'form.lastSub'} eq 'hdgrade' && 
 2163: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
 2164: 			my $display_part=&get_display_part($partid,$symb);
 2165:                         $lastsubonly.='<div class="LC_grade_submission_part">'.
 2166:                             '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2167:                             ' <span class="LC_internal_info">'.
 2168:                             '('.&mt('Part ID: [_1]',$respid).')'.
 2169:                             '</span>&nbsp; &nbsp;';
 2170: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2171: 			if (@$files) {
 2172:                             if ($hide) {
 2173:                                 $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
 2174:                             } else {
 2175:                                 $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
 2176:                                 foreach my $file (@$files) {
 2177:                                     &Apache::lonnet::allowuploaded('/adm/grades',$file);
 2178:                                     $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" /> '.$file.'</a>';
 2179:                                 }
 2180:                             }
 2181: 			    $lastsubonly.='<br />';
 2182: 			}
 2183:                         if ($hide) {
 2184:                             $lastsubonly.='<b>'.&mt('Anonymous Survey').'</b>'; 
 2185:                         } else {
 2186: 			    $lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
 2187: 			        &cleanRecord($subval,$responsetype,$symb,$partid,
 2188: 					     $respid,\%record,$order,undef,$uname,$udom);
 2189:                         }
 2190: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2191: 			$lastsubonly.='</div>';
 2192: 		    }
 2193: 		}
 2194: 	    }
 2195: 	    $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
 2196: 	}
 2197: 	$request->print($lastsubonly);
 2198:    } elsif ($env{'form.lastSub'} eq 'datesub') {
 2199:         my ($parts,$handgrade,$responseType) = &response_type($symb);
 2200: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2201:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2202: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2203: 								 $env{'request.course.id'},
 2204: 								 $last,'.submission',
 2205: 								 'Apache::grades::keywords_highlight'));
 2206:     }
 2207: 
 2208:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2209: 	.$udom.'" />'."\n");
 2210:     # return if view submission with no grading option
 2211: # FIXME: the logic seems off here. Why show the grade button if you cannot grade?
 2212:     if (!&canmodify($usec)) {
 2213: 	my $toGrade.='<input type="button" value="Grade Student" '.
 2214: 	    'onclick="javascript:checksubmit(this.form,\'Grade Student\',\''
 2215: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
 2216: 	$toGrade.='</div>'."\n";
 2217: 	$request->print($toGrade);
 2218: 	return;
 2219:     } else {
 2220: 	$request->print('</div>'."\n");
 2221:     }
 2222: 
 2223:     # essay grading message center
 2224:     if ($env{'form.handgrade'} eq 'yes') {
 2225: 	my $result='<div class="LC_grade_message_center">';
 2226:     
 2227: 	$result.='<div class="LC_grade_message_center_header">'.
 2228: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
 2229: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2230: 	my $msgfor = $givenn.' '.$lastname;
 2231: 	if (scalar(@$col_fullnames) > 0) {
 2232: 	    my $lastone = pop(@$col_fullnames);
 2233: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2234: 	}
 2235: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2236: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2237: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
 2238: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2239: 	    ',\''.$msgfor.'\');" target="_self">'.
 2240: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
 2241: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2242: 	    '<img src="'.$request->dir_config('lonIconsURL').
 2243: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
 2244: 	    '<br />&nbsp;('.
 2245: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
 2246: 	$result.='</div></div>';
 2247: 	$request->print($result);
 2248:     }
 2249: 
 2250:     my %seen = ();
 2251:     my @partlist;
 2252:     my @gradePartRespid;
 2253:     my @part_response_id = &flatten_responseType($responseType);
 2254:     $request->print(
 2255:         '<div class="LC_Box">'
 2256:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
 2257:     );
 2258:     $request->print(&gradeBox_start());
 2259:     foreach my $part_response_id (@part_response_id) {
 2260:     	my ($partid,$respid) = @{ $part_response_id };
 2261: 	my $part_resp = join('_',@{ $part_response_id });
 2262: 	next if ($seen{$partid} > 0);
 2263: 	$seen{$partid}++;
 2264: 	next if ($$handgrade{$part_resp} ne 'yes' 
 2265: 		 && $env{'form.lastSub'} eq 'hdgrade');
 2266: 	push(@partlist,$partid);
 2267: 	push(@gradePartRespid,$partid.'.'.$respid);
 2268: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2269:     }
 2270:     $request->print(&gradeBox_end()); # </div>
 2271:     $request->print('</div>');
 2272: 
 2273:     $request->print('<div class="LC_grade_info_links">');
 2274:     $request->print('</div>');
 2275: 
 2276:     $result='<input type="hidden" name="partlist'.$counter.
 2277: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2278:     $result.='<input type="hidden" name="gradePartRespid'.
 2279: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2280:     my $ctr = 0;
 2281:     while ($ctr < scalar(@partlist)) {
 2282: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2283: 	    $partlist[$ctr].'" />'."\n";
 2284: 	$ctr++;
 2285:     }
 2286:     $request->print($result.''."\n");
 2287: 
 2288: # Done with printing info for one student
 2289: 
 2290:     $request->print('</div>');#LC_grade_show_user
 2291: 
 2292: 
 2293:     # print end of form
 2294:     if ($counter == $total) {
 2295:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
 2296: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2297: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
 2298: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2299: 	my $ntstu ='<select name="NTSTU">'.
 2300: 	    '<option>1</option><option>2</option>'.
 2301: 	    '<option>3</option><option>5</option>'.
 2302: 	    '<option>7</option><option>10</option></select>'."\n";
 2303: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2304: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2305:         $endform.=&mt('[_1]student(s)',$ntstu);
 2306: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2307: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2308: 	    '<input type="button" value="'.&mt('Next').'" '.
 2309: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2310:         $endform.='<span class="LC_warning">'.
 2311:                   &mt('(Next and Previous (student) do not save the scores.)').
 2312:                   '</span>'."\n" ;
 2313:         $endform.="<input type='hidden' value='".&get_increment().
 2314:             "' name='increment' />";
 2315: 	$endform.='</td></tr></table></form>';
 2316: 	$request->print($endform);
 2317:     }
 2318:     return '';
 2319: }
 2320: 
 2321: sub check_collaborators {
 2322:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2323:     my ($result,@col_fullnames);
 2324:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2325:     foreach my $part (keys(%$handgrade)) {
 2326: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2327: 					'.maxcollaborators',
 2328: 					$symb,$udom,$uname);
 2329: 	next if ($ncol <= 0);
 2330: 	$part =~ s/\_/\./g;
 2331: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2332: 	my (@good_collaborators, @bad_collaborators);
 2333: 	foreach my $possible_collaborator
 2334: 	    (split(/,?\s+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2335: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2336: 	    next if ($possible_collaborator eq '');
 2337: 	    my ($co_name,$co_dom) = split(/\@|:/,$possible_collaborator);
 2338: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2339: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2340: 	    # Doing this grep allows 'fuzzy' specification
 2341: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2342: 			       keys(%$classlist));
 2343: 	    if (! scalar(@matches)) {
 2344: 		push(@bad_collaborators, $possible_collaborator);
 2345: 	    } else {
 2346: 		push(@good_collaborators, @matches);
 2347: 	    }
 2348: 	}
 2349: 	if (scalar(@good_collaborators) != 0) {
 2350: 	    $result.='<br />'.&mt('Collaborators: ');
 2351: 	    foreach my $name (@good_collaborators) {
 2352: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2353: 		push(@col_fullnames, $givenn.' '.$lastname);
 2354: 		$result.=$fullname->{$name}.'&nbsp; &nbsp; &nbsp;';
 2355: 	    }
 2356: 	    $result.='<br />'."\n";
 2357: 	    my ($part)=split(/\./,$part);
 2358: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2359: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2360: 		"\n";
 2361: 	}
 2362: 	if (scalar(@bad_collaborators) > 0) {
 2363: 	    $result.='<div class="LC_warning">';
 2364: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2365: 	    $result .= '</div>';
 2366: 	}         
 2367: 	if (scalar(@bad_collaborators > $ncol)) {
 2368: 	    $result .= '<div class="LC_warning">';
 2369: 	    $result .= &mt('This student has submitted too many '.
 2370: 		'collaborators.  Maximum is [_1].',$ncol);
 2371: 	    $result .= '</div>';
 2372: 	}
 2373:     }
 2374:     return ($result,$fullname,\@col_fullnames);
 2375: }
 2376: 
 2377: #--- Retrieve the last submission for all the parts
 2378: sub get_last_submission {
 2379:     my ($returnhash)=@_;
 2380:     my (@string,$timestamp,%lasthidden);
 2381:     if ($$returnhash{'version'}) {
 2382: 	my %lasthash=();
 2383: 	my ($version);
 2384: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2385: 	    foreach my $key (sort(split(/\:/,
 2386: 					$$returnhash{$version.':keys'}))) {
 2387: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2388: 		$timestamp = 
 2389: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2390: 	    }
 2391: 	}
 2392:         my %typeparts;
 2393:         my $showsurv = 
 2394:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
 2395:         foreach my $key (sort(keys(%lasthash))) {
 2396:             if ($key =~ /\.type$/) {
 2397:                 if (($lasthash{$key} eq 'anonsurvey') || 
 2398:                     ($lasthash{$key} eq 'anonsurveycred')) {
 2399:                     my ($ign,@parts) = split(/\./,$key);
 2400:                     pop(@parts);
 2401:                     unless ($showsurv) {
 2402:                         my $id = join(',',@parts);
 2403:                         $typeparts{$ign.'.'.$id} = $lasthash{$key};
 2404:                     }
 2405:                     delete($lasthash{$key});
 2406:                 }
 2407:             }
 2408:         }
 2409:         my @hidden = keys(%typeparts);
 2410: 	foreach my $key (keys(%lasthash)) {
 2411: 	    next if ($key !~ /\.submission$/);
 2412:             my $hide;
 2413:             if (@hidden) {
 2414:                 foreach my $id (@hidden) {
 2415:                     if ($key =~ /^\Q$id\E/) {
 2416:                         $hide = 1;
 2417:                         last;
 2418:                     }
 2419:                 }
 2420:             }
 2421: 	    my ($partid,$foo) = split(/submission$/,$key);
 2422: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
 2423: 		'<span class="LC_warning">Draft Copy</span> ' : '';
 2424: 	    push(@string, join(':', $key, $hide, $draft.$lasthash{$key}));
 2425: 	}
 2426:     }
 2427:     if (!@string) {
 2428: 	$string[0] =
 2429: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
 2430:     }
 2431:     return (\@string,\$timestamp);
 2432: }
 2433: 
 2434: #--- High light keywords, with style choosen by user.
 2435: sub keywords_highlight {
 2436:     my $string    = shift;
 2437:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2438:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2439:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2440:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2441:     foreach my $keyword (@keylist) {
 2442: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2443:     }
 2444:     return $string;
 2445: }
 2446: 
 2447: #--- Called from submission routine
 2448: sub processHandGrade {
 2449:     my ($request,$symb) = @_;
 2450:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2451:     my $button = $env{'form.gradeOpt'};
 2452:     my $ngrade = $env{'form.NCT'};
 2453:     my $ntstu  = $env{'form.NTSTU'};
 2454:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2455:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 2456: 
 2457:     if ($button eq 'Save & Next') {
 2458: 	my $ctr = 0;
 2459: 	while ($ctr < $ngrade) {
 2460: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 2461: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 2462: 	    if ($errorflag eq 'no_score') {
 2463: 		$ctr++;
 2464: 		next;
 2465: 	    }
 2466: 	    if ($errorflag eq 'not_allowed') {
 2467: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
 2468: 		$ctr++;
 2469: 		next;
 2470: 	    }
 2471: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 2472: 	    my ($subject,$message,$msgstatus) = ('','','');
 2473: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 2474:             my ($feedurl,$showsymb) =
 2475: 		&get_feedurl_and_symb($symb,$uname,$udom);
 2476: 	    my $messagetail;
 2477: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 2478: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 2479: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 2480: 		$subject.=' ['.$restitle.']';
 2481: 		my (@msgnum) = split(/,/,$includemsg);
 2482: 		foreach (@msgnum) {
 2483: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 2484: 		}
 2485: 		$message =&Apache::lonfeedback::clear_out_html($message);
 2486: 		if ($env{'form.withgrades'.$ctr}) {
 2487: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 2488: 		    $messagetail = " for <a href=\"".
 2489: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
 2490: 		}
 2491: 		$msgstatus = 
 2492:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 2493: 						     $message.$messagetail,
 2494:                                                      undef,$feedurl,undef,
 2495:                                                      undef,undef,$showsymb,
 2496:                                                      $restitle);
 2497: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
 2498: 				$msgstatus);
 2499: 	    }
 2500: 	    if ($env{'form.collaborator'.$ctr}) {
 2501: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 2502: 		foreach my $collabstr (@collabstrs) {
 2503: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 2504: 		    foreach my $collaborator (@collaborators) {
 2505: 			my ($errorflag,$pts,$wgt) = 
 2506: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 2507: 					   $env{'form.unamedom'.$ctr},$part);
 2508: 			if ($errorflag eq 'not_allowed') {
 2509: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 2510: 			    next;
 2511: 			} elsif ($message ne '') {
 2512: 			    my ($baseurl,$showsymb) = 
 2513: 				&get_feedurl_and_symb($symb,$collaborator,
 2514: 						      $udom);
 2515: 			    if ($env{'form.withgrades'.$ctr}) {
 2516: 				$messagetail = " for <a href=\"".
 2517:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
 2518: 			    }
 2519: 			    $msgstatus = 
 2520: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 2521: 			}
 2522: 		    }
 2523: 		}
 2524: 	    }
 2525: 	    $ctr++;
 2526: 	}
 2527:     }
 2528: 
 2529:     if ($env{'form.handgrade'} eq 'yes') {
 2530: 	# Keywords sorted in alphabatical order
 2531: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2532: 	my %keyhash = ();
 2533: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 2534: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 2535: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 2536: 	$env{'form.keywords'} = join(' ',@keywords);
 2537: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 2538: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 2539: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 2540: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 2541: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 2542: 
 2543: 	# message center - Order of message gets changed. Blank line is eliminated.
 2544: 	# New messages are saved in env for the next student.
 2545: 	# All messages are saved in nohist_handgrade.db
 2546: 	my ($ctr,$idx) = (1,1);
 2547: 	while ($ctr <= $env{'form.savemsgN'}) {
 2548: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 2549: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 2550: 		$idx++;
 2551: 	    }
 2552: 	    $ctr++;
 2553: 	}
 2554: 	$ctr = 0;
 2555: 	while ($ctr < $ngrade) {
 2556: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 2557: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2558: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2559: 		$idx++;
 2560: 	    }
 2561: 	    $ctr++;
 2562: 	}
 2563: 	$env{'form.savemsgN'} = --$idx;
 2564: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 2565: 	my $putresult = &Apache::lonnet::put
 2566: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 2567:     }
 2568:     # Called by Save & Refresh from Highlight Attribute Window
 2569:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 2570:     if ($env{'form.refresh'} eq 'on') {
 2571: 	my ($ctr,$total) = (0,0);
 2572: 	while ($ctr < $ngrade) {
 2573: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 2574: 	    $ctr++;
 2575: 	}
 2576: 	$env{'form.NTSTU'}=$ngrade;
 2577: 	$ctr = 0;
 2578: 	while ($ctr < $total) {
 2579: 	    my $processUser = $env{'form.unamedom'.$ctr};
 2580: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2581: 	    $env{'form.fullname'} = $$fullname{$processUser};
 2582: 	    &submission($request,$ctr,$total-1);
 2583: 	    $ctr++;
 2584: 	}
 2585: 	return '';
 2586:     }
 2587: 
 2588: # Go directly to grade student - from submission or link from chart page
 2589:     if ($button eq 'Grade Student') {
 2590: #	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
 2591: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
 2592: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2593: 	$env{'form.fullname'} = $$fullname{$processUser};
 2594: 	&submission($request,0,0);
 2595: 	return '';
 2596:     }
 2597: 
 2598:     # Get the next/previous one or group of students
 2599:     my $firststu = $env{'form.unamedom0'};
 2600:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 2601:     my $ctr = 2;
 2602:     while ($laststu eq '') {
 2603: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 2604: 	$ctr++;
 2605: 	$laststu = $firststu if ($ctr > $ngrade);
 2606:     }
 2607: 
 2608:     my (@parsedlist,@nextlist);
 2609:     my ($nextflg) = 0;
 2610:     foreach my $item (sort 
 2611: 	     {
 2612: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 2613: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 2614: 		 }
 2615: 		 return $a cmp $b;
 2616: 	     } (keys(%$fullname))) {
 2617: # FIXME: this is fishy, looks like the button label
 2618: 	if ($nextflg == 1 && $button =~ /Next$/) {
 2619: 	    push(@parsedlist,$item);
 2620: 	}
 2621: 	$nextflg = 1 if ($item eq $laststu);
 2622: 	if ($button eq 'Previous') {
 2623: 	    last if ($item eq $firststu);
 2624: 	    push(@parsedlist,$item);
 2625: 	}
 2626:     }
 2627:     $ctr = 0;
 2628: # FIXME: this is fishy, looks like the button label
 2629:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 2630:     my $res_error;
 2631:     my ($partlist) = &response_type($symb,\$res_error);
 2632:     if ($res_error) {
 2633:         $request->print(&navmap_errormsg());
 2634:         return;
 2635:     }
 2636:     foreach my $student (@parsedlist) {
 2637: 	my $submitonly=$env{'form.submitonly'};
 2638: 	my ($uname,$udom) = split(/:/,$student);
 2639: 	
 2640: 	if ($submitonly eq 'queued') {
 2641: 	    my %queue_status = 
 2642: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 2643: 							$udom,$uname);
 2644: 	    next if (!defined($queue_status{'gradingqueue'}));
 2645: 	}
 2646: 
 2647: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 2648: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2649: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 2650: 	    my $submitted = 0;
 2651: 	    my $ungraded = 0;
 2652: 	    my $incorrect = 0;
 2653: 	    foreach my $item (keys(%status)) {
 2654: 		$submitted = 1 if ($status{$item} ne 'nothing');
 2655: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 2656: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 2657: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 2658: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 2659: 		    $submitted = 0;
 2660: 		}
 2661: 	    }
 2662: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 2663: 				     $submitonly eq 'incorrect' ||
 2664: 				     $submitonly eq 'graded'));
 2665: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 2666: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 2667: 	}
 2668: 	push(@nextlist,$student) if ($ctr < $ntstu);
 2669: 	last if ($ctr == $ntstu);
 2670: 	$ctr++;
 2671:     }
 2672: 
 2673:     $ctr = 0;
 2674:     my $total = scalar(@nextlist)-1;
 2675: 
 2676:     foreach (sort(@nextlist)) {
 2677: 	my ($uname,$udom,$submitter) = split(/:/);
 2678: 	$env{'form.student'}  = $uname;
 2679: 	$env{'form.userdom'}  = $udom;
 2680: 	$env{'form.fullname'} = $$fullname{$_};
 2681: 	&submission($request,$ctr,$total);
 2682: 	$ctr++;
 2683:     }
 2684:     if ($total < 0) {
 2685: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
 2686: 	$the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
 2687: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
 2688: 	$request->print($the_end);
 2689:     }
 2690:     return '';
 2691: }
 2692: 
 2693: #---- Save the score and award for each student, if changed
 2694: sub saveHandGrade {
 2695:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 2696:     my @version_parts;
 2697:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 2698: 					   $env{'request.course.id'});
 2699:     if (!&canmodify($usec)) { return('not_allowed'); }
 2700:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 2701:     my @parts_graded;
 2702:     my %newrecord  = ();
 2703:     my ($pts,$wgt) = ('','');
 2704:     my %aggregate = ();
 2705:     my $aggregateflag = 0;
 2706:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 2707:     foreach my $new_part (@parts) {
 2708: 	#collaborator ($submi may vary for different parts
 2709: 	if ($submitter && $new_part ne $part) { next; }
 2710: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 2711: 	if ($dropMenu eq 'excused') {
 2712: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 2713: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 2714: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 2715: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 2716: 		}
 2717: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 2718: 	    }
 2719: 	} elsif ($dropMenu eq 'reset status'
 2720: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 2721: 	    foreach my $key (keys(%record)) {
 2722: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 2723: 	    }
 2724: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2725: 		"$env{'user.name'}:$env{'user.domain'}";
 2726:             my $totaltries = $record{'resource.'.$part.'.tries'};
 2727: 
 2728:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 2729: 					       [$new_part]);
 2730:             my $aggtries =$totaltries;
 2731:             if ($last_resets{$new_part}) {
 2732:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 2733: 					   $new_part);
 2734:             }
 2735: 
 2736:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 2737:             if ($aggtries > 0) {
 2738:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 2739:                 $aggregateflag = 1;
 2740:             }
 2741: 	} elsif ($dropMenu eq '') {
 2742: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 2743: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 2744: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 2745: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 2746: 		next;
 2747: 	    }
 2748: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 2749: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 2750: 	    my $partial= $pts/$wgt;
 2751: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 2752: 		#do not update score for part if not changed.
 2753:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 2754: 		next;
 2755: 	    } else {
 2756: 	        push(@parts_graded,$new_part);
 2757: 	    }
 2758: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 2759: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 2760: 	    }
 2761: 	    my $reckey = 'resource.'.$new_part.'.solved';
 2762: 	    if ($partial == 0) {
 2763: 		if ($record{$reckey} ne 'incorrect_by_override') {
 2764: 		    $newrecord{$reckey} = 'incorrect_by_override';
 2765: 		}
 2766: 	    } else {
 2767: 		if ($record{$reckey} ne 'correct_by_override') {
 2768: 		    $newrecord{$reckey} = 'correct_by_override';
 2769: 		}
 2770: 	    }	    
 2771: 	    if ($submitter && 
 2772: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 2773: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 2774: 	    }
 2775: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2776: 		"$env{'user.name'}:$env{'user.domain'}";
 2777: 	}
 2778: 	# unless problem has been graded, set flag to version the submitted files
 2779: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 2780: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 2781: 	        $dropMenu eq 'reset status')
 2782: 	   {
 2783: 	    push(@version_parts,$new_part);
 2784: 	}
 2785:     }
 2786:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2787:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2788: 
 2789:     if (%newrecord) {
 2790:         if (@version_parts) {
 2791:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 2792:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 2793: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 2794: 	    foreach my $new_part (@version_parts) {
 2795: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 2796: 				$new_part,\%newrecord);
 2797: 	    }
 2798:         }
 2799: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 2800: 				$env{'request.course.id'},$domain,$stuname);
 2801: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 2802: 				     $cdom,$cnum,$domain,$stuname);
 2803:     }
 2804:     if ($aggregateflag) {
 2805:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 2806: 			      $cdom,$cnum);
 2807:     }
 2808:     return ('',$pts,$wgt);
 2809: }
 2810: 
 2811: sub check_and_remove_from_queue {
 2812:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 2813:     my @ungraded_parts;
 2814:     foreach my $part (@{$parts}) {
 2815: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 2816: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 2817: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 2818: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 2819: 		) {
 2820: 	    push(@ungraded_parts, $part);
 2821: 	}
 2822:     }
 2823:     if ( !@ungraded_parts ) {
 2824: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 2825: 					       $cnum,$domain,$stuname);
 2826:     }
 2827: }
 2828: 
 2829: sub handback_files {
 2830:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 2831:     my $portfolio_root = '/userfiles/portfolio';
 2832:     my $res_error;
 2833:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2834:     if ($res_error) {
 2835:         $request->print('<br />'.&navmap_errormsg().'<br />');
 2836:         return;
 2837:     }
 2838:     my @part_response_id = &flatten_responseType($responseType);
 2839:     foreach my $part_response_id (@part_response_id) {
 2840:     	my ($part_id,$resp_id) = @{ $part_response_id };
 2841: 	my $part_resp = join('_',@{ $part_response_id });
 2842:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
 2843:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
 2844:                 my $file_counter = 1;
 2845: 		my $file_msg;
 2846:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
 2847:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
 2848:                     my ($directory,$answer_file) = 
 2849:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
 2850:                     my ($answer_name,$answer_ver,$answer_ext) =
 2851: 		        &file_name_version_ext($answer_file);
 2852: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 2853:                     my $getpropath = 1;
 2854: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
 2855: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 2856:                     # fix file name
 2857:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 2858:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 2859:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
 2860:             	                                $save_file_name);
 2861:                     if ($result !~ m|^/uploaded/|) {
 2862:                         $request->print('<br /><span class="LC_error">'.
 2863:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 2864:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$file_counter).
 2865:                                         '</span>');
 2866:                     } else {
 2867:                         # mark the file as read only
 2868:                         my @files = ($save_file_name);
 2869:                         my @what = ($symb,$env{'request.course.id'},'handback');
 2870:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
 2871: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 2872: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 2873: 			}
 2874:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 2875: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
 2876: 
 2877:                     }
 2878:                     $request->print("<br />".$fname." will be the uploaded file name");
 2879:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
 2880:                     $file_counter++;
 2881:                 }
 2882: 		my $subject = "File Handed Back by Instructor ";
 2883: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
 2884: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
 2885: 		$message .= ' The returned file(s) are named: '. $file_msg;
 2886: 		$message .= " and can be found in your portfolio space.";
 2887: 		my ($feedurl,$showsymb) = 
 2888: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
 2889:                 my $restitle = &Apache::lonnet::gettitle($symb);
 2890: 		my $msgstatus = 
 2891:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
 2892: 			 ' (File Returned) ['.$restitle.']',$message,undef,
 2893:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
 2894:             }
 2895:         }
 2896:     return;
 2897: }
 2898: 
 2899: sub get_feedurl_and_symb {
 2900:     my ($symb,$uname,$udom) = @_;
 2901:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2902:     $url = &Apache::lonnet::clutter($url);
 2903:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 2904: 					$symb,$udom,$uname);
 2905:     if ($encrypturl =~ /^yes$/i) {
 2906: 	&Apache::lonenc::encrypted(\$url,1);
 2907: 	&Apache::lonenc::encrypted(\$symb,1);
 2908:     }
 2909:     return ($url,$symb);
 2910: }
 2911: 
 2912: sub get_submitted_files {
 2913:     my ($udom,$uname,$partid,$respid,$record) = @_;
 2914:     my @files;
 2915:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 2916:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 2917:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 2918:     	    push(@files,$file_url.$file);
 2919:         }
 2920:     }
 2921:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 2922:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 2923:     }
 2924:     return (\@files);
 2925: }
 2926: 
 2927: # ----------- Provides number of tries since last reset.
 2928: sub get_num_tries {
 2929:     my ($record,$last_reset,$part) = @_;
 2930:     my $timestamp = '';
 2931:     my $num_tries = 0;
 2932:     if ($$record{'version'}) {
 2933:         for (my $version=$$record{'version'};$version>=1;$version--) {
 2934:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 2935:                 $timestamp = $$record{$version.':timestamp'};
 2936:                 if ($timestamp > $last_reset) {
 2937:                     $num_tries ++;
 2938:                 } else {
 2939:                     last;
 2940:                 }
 2941:             }
 2942:         }
 2943:     }
 2944:     return $num_tries;
 2945: }
 2946: 
 2947: # ----------- Determine decrements required in aggregate totals 
 2948: sub decrement_aggs {
 2949:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 2950:     my %decrement = (
 2951:                         attempts => 0,
 2952:                         users => 0,
 2953:                         correct => 0
 2954:                     );
 2955:     $decrement{'attempts'} = $aggtries;
 2956:     if ($solvedstatus =~ /^correct/) {
 2957:         $decrement{'correct'} = 1;
 2958:     }
 2959:     if ($aggtries == $totaltries) {
 2960:         $decrement{'users'} = 1;
 2961:     }
 2962:     foreach my $type (keys(%decrement)) {
 2963:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 2964:     }
 2965:     return;
 2966: }
 2967: 
 2968: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 2969: sub get_last_resets {
 2970:     my ($symb,$courseid,$partids) =@_;
 2971:     my %last_resets;
 2972:     my $cdom = $env{'course.'.$courseid.'.domain'};
 2973:     my $cname = $env{'course.'.$courseid.'.num'};
 2974:     my @keys;
 2975:     foreach my $part (@{$partids}) {
 2976: 	push(@keys,"$symb\0$part\0resettime");
 2977:     }
 2978:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 2979: 				     $cdom,$cname);
 2980:     foreach my $part (@{$partids}) {
 2981: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 2982:     }
 2983:     return %last_resets;
 2984: }
 2985: 
 2986: # ----------- Handles creating versions for portfolio files as answers
 2987: sub version_portfiles {
 2988:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 2989:     my $version_parts = join('|',@$v_flag);
 2990:     my @returned_keys;
 2991:     my $parts = join('|', @$parts_graded);
 2992:     my $portfolio_root = '/userfiles/portfolio';
 2993:     foreach my $key (keys(%$record)) {
 2994:         my $new_portfiles;
 2995:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 2996:             my @versioned_portfiles;
 2997:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 2998:             foreach my $file (@portfiles) {
 2999:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 3000:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 3001: 		my ($answer_name,$answer_ver,$answer_ext) =
 3002: 		    &file_name_version_ext($answer_file);
 3003:                 my $getpropath = 1;    
 3004:                 my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
 3005:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 3006:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
 3007:                 if ($new_answer ne 'problem getting file') {
 3008:                     push(@versioned_portfiles, $directory.$new_answer);
 3009:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
 3010:                         [$directory.$new_answer],
 3011:                         [$symb,$env{'request.course.id'},'graded']);
 3012:                 }
 3013:             }
 3014:             $$record{$key} = join(',',@versioned_portfiles);
 3015:             push(@returned_keys,$key);
 3016:         }
 3017:     } 
 3018:     return (@returned_keys);   
 3019: }
 3020: 
 3021: sub get_next_version {
 3022:     my ($answer_name, $answer_ext, $dir_list) = @_;
 3023:     my $version;
 3024:     foreach my $row (@$dir_list) {
 3025:         my ($file) = split(/\&/,$row,2);
 3026:         my ($file_name,$file_version,$file_ext) =
 3027: 	    &file_name_version_ext($file);
 3028:         if (($file_name eq $answer_name) && 
 3029: 	    ($file_ext eq $answer_ext)) {
 3030:                 # gets here if filename and extension match, regardless of version
 3031:                 if ($file_version ne '') {
 3032:                 # a versioned file is found  so save it for later
 3033:                 if ($file_version > $version) {
 3034: 		    $version = $file_version;
 3035: 	        }
 3036:             }
 3037:         }
 3038:     } 
 3039:     $version ++;
 3040:     return($version);
 3041: }
 3042: 
 3043: sub version_selected_portfile {
 3044:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 3045:     my ($answer_name,$answer_ver,$answer_ext) =
 3046:         &file_name_version_ext($file_name);
 3047:     my $new_answer;
 3048:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 3049:     if($env{'form.copy'} eq '-1') {
 3050:         $new_answer = 'problem getting file';
 3051:     } else {
 3052:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 3053:         my $copy_result = &Apache::lonnet::finishuserfileupload(
 3054:                             $stu_name,$domain,'copy',
 3055: 		        '/portfolio'.$directory.$new_answer);
 3056:     }    
 3057:     return ($new_answer);
 3058: }
 3059: 
 3060: sub file_name_version_ext {
 3061:     my ($file)=@_;
 3062:     my @file_parts = split(/\./, $file);
 3063:     my ($name,$version,$ext);
 3064:     if (@file_parts > 1) {
 3065: 	$ext=pop(@file_parts);
 3066: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 3067: 	    $version=pop(@file_parts);
 3068: 	}
 3069: 	$name=join('.',@file_parts);
 3070:     } else {
 3071: 	$name=join('.',@file_parts);
 3072:     }
 3073:     return($name,$version,$ext);
 3074: }
 3075: 
 3076: #--------------------------------------------------------------------------------------
 3077: #
 3078: #-------------------------- Next few routines handles grading by section or whole class
 3079: #
 3080: #--- Javascript to handle grading by section or whole class
 3081: sub viewgrades_js {
 3082:     my ($request) = shift;
 3083: 
 3084:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3085:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
 3086:    function writePoint(partid,weight,point) {
 3087: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3088: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3089: 	if (point == "textval") {
 3090: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3091: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3092: 		alert("$alertmsg"+parseFloat(point));
 3093: 		var resetbox = false;
 3094: 		for (var i=0; i<radioButton.length; i++) {
 3095: 		    if (radioButton[i].checked) {
 3096: 			textbox.value = i;
 3097: 			resetbox = true;
 3098: 		    }
 3099: 		}
 3100: 		if (!resetbox) {
 3101: 		    textbox.value = "";
 3102: 		}
 3103: 		return;
 3104: 	    }
 3105: 	    if (parseFloat(point) > parseFloat(weight)) {
 3106: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3107: 				   ") greater than the weight for the part. Accept?");
 3108: 		if (resp == false) {
 3109: 		    textbox.value = "";
 3110: 		    return;
 3111: 		}
 3112: 	    }
 3113: 	    for (var i=0; i<radioButton.length; i++) {
 3114: 		radioButton[i].checked=false;
 3115: 		if (parseFloat(point) == i) {
 3116: 		    radioButton[i].checked=true;
 3117: 		}
 3118: 	    }
 3119: 
 3120: 	} else {
 3121: 	    textbox.value = parseFloat(point);
 3122: 	}
 3123: 	for (i=0;i<document.classgrade.total.value;i++) {
 3124: 	    var user = document.classgrade["ctr"+i].value;
 3125: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3126: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3127: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3128: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3129: 	    if (saveval != "correct") {
 3130: 		scorename.value = point;
 3131: 		if (selname[0].selected != true) {
 3132: 		    selname[0].selected = true;
 3133: 		}
 3134: 	    }
 3135: 	}
 3136: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3137:     }
 3138: 
 3139:     function writeRadText(partid,weight) {
 3140: 	var selval   = document.classgrade["SELVAL_"+partid];
 3141: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3142:         var override = document.classgrade["FORCE_"+partid].checked;
 3143: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3144: 	if (selval[1].selected || selval[2].selected) {
 3145: 	    for (var i=0; i<radioButton.length; i++) {
 3146: 		radioButton[i].checked=false;
 3147: 
 3148: 	    }
 3149: 	    textbox.value = "";
 3150: 
 3151: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3152: 		var user = document.classgrade["ctr"+i].value;
 3153: 		user = user.replace(new RegExp(':', 'g'),"_");
 3154: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3155: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3156: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3157: 		if ((saveval != "correct") || override) {
 3158: 		    scorename.value = "";
 3159: 		    if (selval[1].selected) {
 3160: 			selname[1].selected = true;
 3161: 		    } else {
 3162: 			selname[2].selected = true;
 3163: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3164: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3165: 		    }
 3166: 		}
 3167: 	    }
 3168: 	} else {
 3169: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3170: 		var user = document.classgrade["ctr"+i].value;
 3171: 		user = user.replace(new RegExp(':', 'g'),"_");
 3172: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3173: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3174: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3175: 		if ((saveval != "correct") || override) {
 3176: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3177: 		    selname[0].selected = true;
 3178: 		}
 3179: 	    }
 3180: 	}	    
 3181:     }
 3182: 
 3183:     function changeSelect(partid,user) {
 3184: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3185: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3186: 	var point  = textbox.value;
 3187: 	var weight = document.classgrade["weight_"+partid].value;
 3188: 
 3189: 	if (isNaN(point) || parseFloat(point) < 0) {
 3190: 	    alert("$alertmsg"+parseFloat(point));
 3191: 	    textbox.value = "";
 3192: 	    return;
 3193: 	}
 3194: 	if (parseFloat(point) > parseFloat(weight)) {
 3195: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3196: 			       ") greater than the weight of the part. Accept?");
 3197: 	    if (resp == false) {
 3198: 		textbox.value = "";
 3199: 		return;
 3200: 	    }
 3201: 	}
 3202: 	selval[0].selected = true;
 3203:     }
 3204: 
 3205:     function changeOneScore(partid,user) {
 3206: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3207: 	if (selval[1].selected || selval[2].selected) {
 3208: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3209: 	    if (selval[2].selected) {
 3210: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3211: 	    }
 3212:         }
 3213:     }
 3214: 
 3215:     function resetEntry(numpart) {
 3216: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3217: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3218: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3219: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3220: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3221: 	    for (var i=0; i<radioButton.length; i++) {
 3222: 		radioButton[i].checked=false;
 3223: 
 3224: 	    }
 3225: 	    textbox.value = "";
 3226: 	    selval[0].selected = true;
 3227: 
 3228: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3229: 		var user = document.classgrade["ctr"+i].value;
 3230: 		user = user.replace(new RegExp(':', 'g'),"_");
 3231: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3232: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3233: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3234: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3235: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3236: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3237: 		if (saveselval == "excused") {
 3238: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3239: 		} else {
 3240: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3241: 		}
 3242: 	    }
 3243: 	}
 3244:     }
 3245: 
 3246: VIEWJAVASCRIPT
 3247: }
 3248: 
 3249: #--- show scores for a section or whole class w/ option to change/update a score
 3250: sub viewgrades {
 3251:     my ($request,$symb) = @_;
 3252:     &viewgrades_js($request);
 3253: 
 3254:     #need to make sure we have the correct data for later EXT calls, 
 3255:     #thus invalidate the cache
 3256:     &Apache::lonnet::devalidatecourseresdata(
 3257:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3258:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3259:     &Apache::lonnet::clear_EXT_cache_status();
 3260: 
 3261:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3262: 
 3263:     #view individual student submission form - called using Javascript viewOneStudent
 3264:     $result.=&jscriptNform($symb);
 3265: 
 3266:     #beginning of class grading form
 3267:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3268:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3269: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3270: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3271: 	&build_section_inputs().
 3272: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3273: 
 3274:     my ($common_header,$specific_header);
 3275:     if ($env{'form.section'} eq 'all') {
 3276: 	$common_header = &mt('Assign Common Grade to Class');
 3277:         $specific_header = &mt('Assign Grade to Specific Students in Class');
 3278:     } elsif ($env{'form.section'} eq 'none') {
 3279:         $common_header = &mt('Assign Common Grade to Students in no Section');
 3280: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
 3281:     } else {
 3282:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3283:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
 3284: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
 3285:     }
 3286:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
 3287:     #radio buttons/text box for assigning points for a section or class.
 3288:     #handles different parts of a problem
 3289:     my $res_error;
 3290:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3291:     if ($res_error) {
 3292:         return &navmap_errormsg();
 3293:     }
 3294:     my %weight = ();
 3295:     my $ctsparts = 0;
 3296:     my %seen = ();
 3297:     my @part_response_id = &flatten_responseType($responseType);
 3298:     foreach my $part_response_id (@part_response_id) {
 3299:     	my ($partid,$respid) = @{ $part_response_id };
 3300: 	my $part_resp = join('_',@{ $part_response_id });
 3301: 	next if $seen{$partid};
 3302: 	$seen{$partid}++;
 3303: 	my $handgrade=$$handgrade{$part_resp};
 3304: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 3305: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 3306: 
 3307: 	my $display_part=&get_display_part($partid,$symb);
 3308: 	my $radio.='<table border="0"><tr>';  
 3309: 	my $ctr = 0;
 3310: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 3311: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 3312: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 3313: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 3314: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 3315: 	    $ctr++;
 3316: 	}
 3317: 	$radio.='</tr></table>';
 3318: 	my $line = '<input type="text" name="TEXTVAL_'.
 3319: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
 3320: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 3321: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 3322: 	$line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
 3323: 	    'onchange="javascript:writeRadText(\''.$partid.'\','.
 3324: 		$weight{$partid}.')"> '.
 3325: 	    '<option selected="selected"> </option>'.
 3326: 	    '<option value="excused">'.&mt('excused').'</option>'.
 3327: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 3328: 	    '</select></td>'.
 3329:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 3330: 	$line.='<input type="hidden" name="partid_'.
 3331: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 3332: 	$line.='<input type="hidden" name="weight_'.
 3333: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 3334: 
 3335: 	$result.=
 3336: 	    &Apache::loncommon::start_data_table_row()."\n".
 3337: 	    '<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>'.
 3338: 	    &Apache::loncommon::end_data_table_row()."\n";
 3339: 	$ctsparts++;
 3340:     }
 3341:     $result.=&Apache::loncommon::end_data_table()."\n".
 3342: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 3343:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 3344: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
 3345: 
 3346:     #table listing all the students in a section/class
 3347:     #header of table
 3348:     $result.= '<h3>'.$specific_header.'</h3>'.
 3349:               &Apache::loncommon::start_data_table().
 3350: 	      &Apache::loncommon::start_data_table_header_row().
 3351: 	      '<th>'.&mt('No.').'</th>'.
 3352: 	      '<th>'.&nameUserString('header')."</th>\n";
 3353:     my $partserror;
 3354:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3355:     if ($partserror) {
 3356:         return &navmap_errormsg();
 3357:     }
 3358:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 3359:     my @partids = ();
 3360:     foreach my $part (@parts) {
 3361: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3362:         my $narrowtext = &mt('Tries');
 3363: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 3364: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 3365: 	my ($partid) = &split_part_type($part);
 3366:         push(@partids,$partid);
 3367: 	my $display_part=&get_display_part($partid,$symb);
 3368: 	if ($display =~ /^Partial Credit Factor/) {
 3369: 	    $result.='<th>'.
 3370: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
 3371: 		    $display_part,$weight{$partid}).'</th>'."\n";
 3372: 	    next;
 3373: 	    
 3374: 	} else {
 3375: 	    if ($display =~ /Problem Status/) {
 3376: 		my $grade_status_mt = &mt('Grade Status');
 3377: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 3378: 	    }
 3379: 	    my $part_mt = &mt('Part:');
 3380: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 3381: 	}
 3382: 
 3383: 	$result.='<th>'.$display.'</th>'."\n";
 3384:     }
 3385:     $result.=&Apache::loncommon::end_data_table_header_row();
 3386: 
 3387:     my %last_resets = 
 3388: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 3389: 
 3390:     #get info for each student
 3391:     #list all the students - with points and grade status
 3392:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3393:     my $ctr = 0;
 3394:     foreach (sort 
 3395: 	     {
 3396: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3397: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3398: 		 }
 3399: 		 return $a cmp $b;
 3400: 	     } (keys(%$fullname))) {
 3401: 	$ctr++;
 3402: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 3403: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
 3404:     }
 3405:     $result.=&Apache::loncommon::end_data_table();
 3406:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 3407:     $result.='<input type="button" value="'.&mt('Save').'" '.
 3408: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
 3409:     if (scalar(%$fullname) eq 0) {
 3410: 	my $colspan=3+scalar(@parts);
 3411: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3412:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 3413: 	$result='<span class="LC_warning">'.
 3414: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 3415: 	        $section_display, $stu_status).
 3416: 	    '</span>';
 3417:     }
 3418:     return $result;
 3419: }
 3420: 
 3421: #--- call by previous routine to display each student
 3422: sub viewstudentgrade {
 3423:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 3424:     my ($uname,$udom) = split(/:/,$student);
 3425:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 3426:     my %aggregates = (); 
 3427:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 3428: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
 3429: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
 3430: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 3431: 	'\');" target="_self">'.$fullname.'</a> '.
 3432: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 3433:     $student=~s/:/_/; # colon doen't work in javascript for names
 3434:     foreach my $apart (@$parts) {
 3435: 	my ($part,$type) = &split_part_type($apart);
 3436: 	my $score=$record{"resource.$part.$type"};
 3437:         $result.='<td align="center">';
 3438:         my ($aggtries,$totaltries);
 3439:         unless (exists($aggregates{$part})) {
 3440: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 3441: 
 3442: 	    $aggtries = $totaltries;
 3443:             if ($$last_resets{$part}) {  
 3444:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 3445: 					   $part);
 3446:             }
 3447:             $result.='<input type="hidden" name="'.
 3448:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 3449:             $result.='<input type="hidden" name="'.
 3450:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 3451:             $aggregates{$part} = 1;
 3452:         }
 3453: 	if ($type eq 'awarded') {
 3454: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 3455: 	    $result.='<input type="hidden" name="'.
 3456: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 3457: 	    $result.='<input type="text" name="'.
 3458: 		'GD_'.$student.'_'.$part.'_awarded" '.
 3459:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
 3460: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 3461: 	} elsif ($type eq 'solved') {
 3462: 	    my ($status,$foo)=split(/_/,$score,2);
 3463: 	    $status = 'nothing' if ($status eq '');
 3464: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 3465: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 3466: 	    $result.='&nbsp;<select name="'.
 3467: 		'GD_'.$student.'_'.$part.'_solved" '.
 3468:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 3469: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 3470: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 3471: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 3472: 	    $result.="</select>&nbsp;</td>\n";
 3473: 	} else {
 3474: 	    $result.='<input type="hidden" name="'.
 3475: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 3476: 		    "\n";
 3477: 	    $result.='<input type="text" name="'.
 3478: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 3479: 		'value="'.$score.'" size="4" /></td>'."\n";
 3480: 	}
 3481:     }
 3482:     $result.=&Apache::loncommon::end_data_table_row();
 3483:     return $result;
 3484: }
 3485: 
 3486: #--- change scores for all the students in a section/class
 3487: #    record does not get update if unchanged
 3488: sub editgrades {
 3489:     my ($request,$symb) = @_;
 3490: 
 3491:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3492:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 3493:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
 3494: 
 3495:     my $result= &Apache::loncommon::start_data_table().
 3496: 	&Apache::loncommon::start_data_table_header_row().
 3497: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 3498: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 3499:     my %scoreptr = (
 3500: 		    'correct'  =>'correct_by_override',
 3501: 		    'incorrect'=>'incorrect_by_override',
 3502: 		    'excused'  =>'excused',
 3503: 		    'ungraded' =>'ungraded_attempted',
 3504:                     'credited' =>'credit_attempted',
 3505: 		    'nothing'  => '',
 3506: 		    );
 3507:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 3508: 
 3509:     my (@partid);
 3510:     my %weight = ();
 3511:     my %columns = ();
 3512:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 3513: 
 3514:     my $partserror;
 3515:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3516:     if ($partserror) {
 3517:         return &navmap_errormsg();
 3518:     }
 3519:     my $header;
 3520:     while ($ctr < $env{'form.totalparts'}) {
 3521: 	my $partid = $env{'form.partid_'.$ctr};
 3522: 	push(@partid,$partid);
 3523: 	$weight{$partid} = $env{'form.weight_'.$partid};
 3524: 	$ctr++;
 3525:     }
 3526:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3527:     foreach my $partid (@partid) {
 3528: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 3529: 	    '<th align="center">'.&mt('New Score').'</th>';
 3530: 	$columns{$partid}=2;
 3531: 	foreach my $stores (@parts) {
 3532: 	    my ($part,$type) = &split_part_type($stores);
 3533: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 3534: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 3535: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 3536: 	    $display =~ s/\[Part: \Q$part\E\]//;
 3537:             my $narrowtext = &mt('Tries');
 3538: 	    $display =~ s/Number of Attempts/$narrowtext/;
 3539: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 3540: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 3541: 	    $columns{$partid}+=2;
 3542: 	}
 3543:     }
 3544:     foreach my $partid (@partid) {
 3545: 	my $display_part=&get_display_part($partid,$symb);
 3546: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 3547: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 3548: 	    '</th>';
 3549: 
 3550:     }
 3551:     $result .= &Apache::loncommon::end_data_table_header_row().
 3552: 	&Apache::loncommon::start_data_table_header_row().
 3553: 	$header.
 3554: 	&Apache::loncommon::end_data_table_header_row();
 3555:     my @noupdate;
 3556:     my ($updateCtr,$noupdateCtr) = (1,1);
 3557:     for ($i=0; $i<$env{'form.total'}; $i++) {
 3558: 	my $line;
 3559: 	my $user = $env{'form.ctr'.$i};
 3560: 	my ($uname,$udom)=split(/:/,$user);
 3561: 	my %newrecord;
 3562: 	my $updateflag = 0;
 3563: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 3564: 	my $usec=$classlist->{"$uname:$udom"}[5];
 3565: 	if (!&canmodify($usec)) {
 3566: 	    my $numcols=scalar(@partid)*4+2;
 3567: 	    push(@noupdate,
 3568: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
 3569: 		 &mt('Not allowed to modify student')."</span></td></tr>");
 3570: 	    next;
 3571: 	}
 3572:         my %aggregate = ();
 3573:         my $aggregateflag = 0;
 3574: 	$user=~s/:/_/; # colon doen't work in javascript for names
 3575: 	foreach (@partid) {
 3576: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 3577: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 3578: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 3579: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3580: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 3581: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 3582: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 3583: 	    my $score;
 3584: 	    if ($partial eq '') {
 3585: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3586: 	    } elsif ($partial > 0) {
 3587: 		$score = 'correct_by_override';
 3588: 	    } elsif ($partial == 0) {
 3589: 		$score = 'incorrect_by_override';
 3590: 	    }
 3591: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 3592: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 3593: 
 3594: 	    $newrecord{'resource.'.$_.'.regrader'}=
 3595: 		"$env{'user.name'}:$env{'user.domain'}";
 3596: 	    if ($dropMenu eq 'reset status' &&
 3597: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 3598: 		$newrecord{'resource.'.$_.'.tries'} = '';
 3599: 		$newrecord{'resource.'.$_.'.solved'} = '';
 3600: 		$newrecord{'resource.'.$_.'.award'} = '';
 3601: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 3602: 		$updateflag = 1;
 3603:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 3604:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 3605:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 3606:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 3607:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3608:                     $aggregateflag = 1;
 3609:                 }
 3610: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 3611: 		$updateflag = 1;
 3612: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 3613: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 3614: 		$rec_update++;
 3615: 	    }
 3616: 
 3617: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3618: 		'<td align="center">'.$awarded.
 3619: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 3620: 
 3621: 
 3622: 	    my $partid=$_;
 3623: 	    foreach my $stores (@parts) {
 3624: 		my ($part,$type) = &split_part_type($stores);
 3625: 		if ($part !~ m/^\Q$partid\E/) { next;}
 3626: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 3627: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 3628: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 3629: 		if ($awarded ne '' && $awarded ne $old_aw) {
 3630: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 3631: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3632: 		    $updateflag=1;
 3633: 		}
 3634: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3635: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 3636: 	    }
 3637: 	}
 3638: 	$line.="\n";
 3639: 
 3640: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3641: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3642: 
 3643: 	if ($updateflag) {
 3644: 	    $count++;
 3645: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 3646: 				    $udom,$uname);
 3647: 
 3648: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 3649: 					      $cnum,$udom,$uname)) {
 3650: 		# need to figure out if should be in queue.
 3651: 		my %record =  
 3652: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 3653: 					     $udom,$uname);
 3654: 		my $all_graded = 1;
 3655: 		my $none_graded = 1;
 3656: 		foreach my $part (@parts) {
 3657: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 3658: 			$all_graded = 0;
 3659: 		    } else {
 3660: 			$none_graded = 0;
 3661: 		    }
 3662: 		}
 3663: 
 3664: 		if ($all_graded || $none_graded) {
 3665: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 3666: 							   $symb,$cdom,$cnum,
 3667: 							   $udom,$uname);
 3668: 		}
 3669: 	    }
 3670: 
 3671: 	    $result.=&Apache::loncommon::start_data_table_row().
 3672: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 3673: 		&Apache::loncommon::end_data_table_row();
 3674: 	    $updateCtr++;
 3675: 	} else {
 3676: 	    push(@noupdate,
 3677: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 3678: 	    $noupdateCtr++;
 3679: 	}
 3680:         if ($aggregateflag) {
 3681:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3682: 				  $cdom,$cnum);
 3683:         }
 3684:     }
 3685:     if (@noupdate) {
 3686: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
 3687: 	my $numcols=scalar(@partid)*4+2;
 3688: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 3689: 	    '<td align="center" colspan="'.$numcols.'">'.
 3690: 	    &mt('No Changes Occurred For the Students Below').
 3691: 	    '</td>'.
 3692: 	    &Apache::loncommon::end_data_table_row();
 3693: 	foreach my $line (@noupdate) {
 3694: 	    $result.=
 3695: 		&Apache::loncommon::start_data_table_row().
 3696: 		$line.
 3697: 		&Apache::loncommon::end_data_table_row();
 3698: 	}
 3699:     }
 3700:     $result .= &Apache::loncommon::end_data_table();
 3701:     my $msg = '<p><b>'.
 3702: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 3703: 	    $rec_update,$count).'</b><br />'.
 3704: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 3705: 	'</b></p>';
 3706:     return $title.$msg.$result;
 3707: }
 3708: 
 3709: sub split_part_type {
 3710:     my ($partstr) = @_;
 3711:     my ($temp,@allparts)=split(/_/,$partstr);
 3712:     my $type=pop(@allparts);
 3713:     my $part=join('_',@allparts);
 3714:     return ($part,$type);
 3715: }
 3716: 
 3717: #------------- end of section for handling grading by section/class ---------
 3718: #
 3719: #----------------------------------------------------------------------------
 3720: 
 3721: 
 3722: #----------------------------------------------------------------------------
 3723: #
 3724: #-------------------------- Next few routines handles grading by csv upload
 3725: #
 3726: #--- Javascript to handle csv upload
 3727: sub csvupload_javascript_reverse_associate {
 3728:     my $error1=&mt('You need to specify the username or the student/employee ID');
 3729:     my $error2=&mt('You need to specify at least one grading field');
 3730:   return(<<ENDPICK);
 3731:   function verify(vf) {
 3732:     var foundsomething=0;
 3733:     var founduname=0;
 3734:     var foundID=0;
 3735:     for (i=0;i<=vf.nfields.value;i++) {
 3736:       tw=eval('vf.f'+i+'.selectedIndex');
 3737:       if (i==0 && tw!=0) { foundID=1; }
 3738:       if (i==1 && tw!=0) { founduname=1; }
 3739:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 3740:     }
 3741:     if (founduname==0 && foundID==0) {
 3742: 	alert('$error1');
 3743: 	return;
 3744:     }
 3745:     if (foundsomething==0) {
 3746: 	alert('$error2');
 3747: 	return;
 3748:     }
 3749:     vf.submit();
 3750:   }
 3751:   function flip(vf,tf) {
 3752:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3753:     var i;
 3754:     for (i=0;i<=vf.nfields.value;i++) {
 3755:       //can not pick the same destination field for both name and domain
 3756:       if (((i ==0)||(i ==1)) && 
 3757:           ((tf==0)||(tf==1)) && 
 3758:           (i!=tf) &&
 3759:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3760:         eval('vf.f'+i+'.selectedIndex=0;')
 3761:       }
 3762:     }
 3763:   }
 3764: ENDPICK
 3765: }
 3766: 
 3767: sub csvupload_javascript_forward_associate {
 3768:     my $error1=&mt('You need to specify the username or the student/employee ID');
 3769:     my $error2=&mt('You need to specify at least one grading field');
 3770:   return(<<ENDPICK);
 3771:   function verify(vf) {
 3772:     var foundsomething=0;
 3773:     var founduname=0;
 3774:     var foundID=0;
 3775:     for (i=0;i<=vf.nfields.value;i++) {
 3776:       tw=eval('vf.f'+i+'.selectedIndex');
 3777:       if (tw==1) { foundID=1; }
 3778:       if (tw==2) { founduname=1; }
 3779:       if (tw>3) { foundsomething=1; }
 3780:     }
 3781:     if (founduname==0 && foundID==0) {
 3782: 	alert('$error1');
 3783: 	return;
 3784:     }
 3785:     if (foundsomething==0) {
 3786: 	alert('$error2');
 3787: 	return;
 3788:     }
 3789:     vf.submit();
 3790:   }
 3791:   function flip(vf,tf) {
 3792:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3793:     var i;
 3794:     //can not pick the same destination field twice
 3795:     for (i=0;i<=vf.nfields.value;i++) {
 3796:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3797:         eval('vf.f'+i+'.selectedIndex=0;')
 3798:       }
 3799:     }
 3800:   }
 3801: ENDPICK
 3802: }
 3803: 
 3804: sub csvuploadmap_header {
 3805:     my ($request,$symb,$datatoken,$distotal)= @_;
 3806:     my $javascript;
 3807:     if ($env{'form.upfile_associate'} eq 'reverse') {
 3808: 	$javascript=&csvupload_javascript_reverse_associate();
 3809:     } else {
 3810: 	$javascript=&csvupload_javascript_forward_associate();
 3811:     }
 3812: 
 3813:     my $result='';
 3814:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
 3815:     my $ignore=&mt('Ignore First Line');
 3816:     $symb = &Apache::lonenc::check_encrypt($symb);
 3817:     $request->print(<<ENDPICK);
 3818: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3819: <h3><span class="LC_info">Uploading Class Grades</span></h3>
 3820: $result
 3821: <hr />
 3822: <h3>Identify fields</h3>
 3823: Total number of records found in file: $distotal <hr />
 3824: Enter as many fields as you can. The system will inform you and bring you back
 3825: to this page if the data selected is insufficient to run your class.<hr />
 3826: <input type="button" value="Reverse Association" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 3827: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
 3828: <input type="hidden" name="associate"  value="" />
 3829: <input type="hidden" name="phase"      value="three" />
 3830: <input type="hidden" name="datatoken"  value="$datatoken" />
 3831: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 3832: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 3833: <input type="hidden" name="upfile_associate" 
 3834:                                        value="$env{'form.upfile_associate'}" />
 3835: <input type="hidden" name="symb"       value="$symb" />
 3836: <input type="hidden" name="command"    value="csvuploadoptions" />
 3837: <hr />
 3838: ENDPICK
 3839:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
 3840:     return '';
 3841: 
 3842: }
 3843: 
 3844: sub csvupload_fields {
 3845:     my ($symb,$errorref) = @_;
 3846:     my (@parts) = &getpartlist($symb,$errorref);
 3847:     if (ref($errorref)) {
 3848:         if ($$errorref) {
 3849:             return;
 3850:         }
 3851:     }
 3852: 
 3853:     my @fields=(['ID','Student/Employee ID'],
 3854: 		['username','Student Username'],
 3855: 		['domain','Student Domain']);
 3856:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3857:     foreach my $part (sort(@parts)) {
 3858: 	my @datum;
 3859: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3860: 	my $name=$part;
 3861: 	if  (!$display) { $display = $name; }
 3862: 	@datum=($name,$display);
 3863: 	if ($name=~/^stores_(.*)_awarded/) {
 3864: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 3865: 	}
 3866: 	push(@fields,\@datum);
 3867:     }
 3868:     return (@fields);
 3869: }
 3870: 
 3871: sub csvuploadmap_footer {
 3872:     my ($request,$i,$keyfields) =@_;
 3873:     $request->print(<<ENDPICK);
 3874: </table>
 3875: <input type="hidden" name="nfields" value="$i" />
 3876: <input type="hidden" name="keyfields" value="$keyfields" />
 3877: <input type="button" onclick="javascript:verify(this.form)" value="Assign Grades" /><br />
 3878: </form>
 3879: ENDPICK
 3880: }
 3881: 
 3882: sub checkforfile_js {
 3883:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 3884:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
 3885:     function checkUpload(formname) {
 3886: 	if (formname.upfile.value == "") {
 3887: 	    alert("$alertmsg");
 3888: 	    return false;
 3889: 	}
 3890: 	formname.submit();
 3891:     }
 3892: CSVFORMJS
 3893:     return $result;
 3894: }
 3895: 
 3896: sub upcsvScores_form {
 3897:     my ($request,$symb) = @_;
 3898:     if (!$symb) {return '';}
 3899:     my $result=&checkforfile_js();
 3900:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 3901:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 3902:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource.').
 3903: 	'</b></td></tr>'."\n";
 3904:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
 3905:     my $upload=&mt("Upload Scores");
 3906:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 3907:     my $ignore=&mt('Ignore First Line');
 3908:     $symb = &Apache::lonenc::check_encrypt($symb);
 3909:     $result.=<<ENDUPFORM;
 3910: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3911: <input type="hidden" name="symb" value="$symb" />
 3912: <input type="hidden" name="command" value="csvuploadmap" />
 3913: $upfile_select
 3914: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 3915: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
 3916: </form>
 3917: ENDUPFORM
 3918:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 3919:                            &mt("How do I create a CSV file from a spreadsheet"))
 3920:     .'</td></tr></table>'."\n";
 3921:     $result.='</td></tr></table><br /><br />'."\n";
 3922:     return $result;
 3923: }
 3924: 
 3925: 
 3926: sub csvuploadmap {
 3927:     my ($request,$symb)= @_;
 3928:     if (!$symb) {return '';}
 3929: 
 3930:     my $datatoken;
 3931:     if (!$env{'form.datatoken'}) {
 3932: 	$datatoken=&Apache::loncommon::upfile_store($request);
 3933:     } else {
 3934: 	$datatoken=$env{'form.datatoken'};
 3935: 	&Apache::loncommon::load_tmp_file($request);
 3936:     }
 3937:     my @records=&Apache::loncommon::upfile_record_sep();
 3938:     if ($env{'form.noFirstLine'}) { shift(@records); }
 3939:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 3940:     my ($i,$keyfields);
 3941:     if (@records) {
 3942:         my $fieldserror;
 3943: 	my @fields=&csvupload_fields($symb,\$fieldserror);
 3944:         if ($fieldserror) {
 3945:             $request->print(&navmap_errormsg());
 3946:             return;
 3947:         }
 3948: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 3949: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 3950: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 3951: 							  \@fields);
 3952: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 3953: 	    chop($keyfields);
 3954: 	} else {
 3955: 	    unshift(@fields,['none','']);
 3956: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 3957: 							    \@fields);
 3958:             foreach my $rec (@records) {
 3959:                 my %temp = &Apache::loncommon::record_sep($rec);
 3960:                 if (%temp) {
 3961:                     $keyfields=join(',',sort(keys(%temp)));
 3962:                     last;
 3963:                 }
 3964:             }
 3965: 	}
 3966:     }
 3967:     &csvuploadmap_footer($request,$i,$keyfields);
 3968: 
 3969:     return '';
 3970: }
 3971: 
 3972: sub csvuploadoptions {
 3973:     my ($request,$symb)= @_;
 3974:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
 3975:     my $ignore=&mt('Ignore First Line');
 3976:     $request->print(<<ENDPICK);
 3977: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3978: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
 3979: <input type="hidden" name="command"    value="csvuploadassign" />
 3980: <!--
 3981: <p>
 3982: <label>
 3983:    <input type="checkbox" name="show_full_results" />
 3984:    Show a table of all changes
 3985: </label>
 3986: </p>
 3987: -->
 3988: <p>
 3989: <label>
 3990:    <input type="checkbox" name="overwite_scores" checked="checked" />
 3991:    Overwrite any existing score
 3992: </label>
 3993: </p>
 3994: ENDPICK
 3995:     my %fields=&get_fields();
 3996:     if (!defined($fields{'domain'})) {
 3997: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 3998: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
 3999:     }
 4000:     foreach my $key (sort(keys(%env))) {
 4001: 	if ($key !~ /^form\.(.*)$/) { next; }
 4002: 	my $cleankey=$1;
 4003: 	if ($cleankey eq 'command') { next; }
 4004: 	$request->print('<input type="hidden" name="'.$cleankey.
 4005: 			'"  value="'.$env{$key}.'" />'."\n");
 4006:     }
 4007:     # FIXME do a check for any duplicated user ids...
 4008:     # FIXME do a check for any invalid user ids?...
 4009:     $request->print('<input type="submit" value="Assign Grades" /><br />
 4010: <hr /></form>'."\n");
 4011:     return '';
 4012: }
 4013: 
 4014: sub get_fields {
 4015:     my %fields;
 4016:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 4017:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 4018: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 4019: 	    if ($env{'form.f'.$i} ne 'none') {
 4020: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 4021: 	    }
 4022: 	} else {
 4023: 	    if ($env{'form.f'.$i} ne 'none') {
 4024: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 4025: 	    }
 4026: 	}
 4027:     }
 4028:     return %fields;
 4029: }
 4030: 
 4031: sub csvuploadassign {
 4032:     my ($request,$symb)= @_;
 4033:     if (!$symb) {return '';}
 4034:     my $error_msg = '';
 4035:     &Apache::loncommon::load_tmp_file($request);
 4036:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 4037:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
 4038:     my %fields=&get_fields();
 4039:     $request->print('<h3>Assigning Grades</h3>');
 4040:     my $courseid=$env{'request.course.id'};
 4041:     my ($classlist) = &getclasslist('all',0);
 4042:     my @notallowed;
 4043:     my @skipped;
 4044:     my $countdone=0;
 4045:     foreach my $grade (@gradedata) {
 4046: 	my %entries=&Apache::loncommon::record_sep($grade);
 4047: 	my $domain;
 4048: 	if ($entries{$fields{'domain'}}) {
 4049: 	    $domain=$entries{$fields{'domain'}};
 4050: 	} else {
 4051: 	    $domain=$env{'form.default_domain'};
 4052: 	}
 4053: 	$domain=~s/\s//g;
 4054: 	my $username=$entries{$fields{'username'}};
 4055: 	$username=~s/\s//g;
 4056: 	if (!$username) {
 4057: 	    my $id=$entries{$fields{'ID'}};
 4058: 	    $id=~s/\s//g;
 4059: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 4060: 	    $username=$ids{$id};
 4061: 	}
 4062: 	if (!exists($$classlist{"$username:$domain"})) {
 4063: 	    my $id=$entries{$fields{'ID'}};
 4064: 	    $id=~s/\s//g;
 4065: 	    if ($id) {
 4066: 		push(@skipped,"$id:$domain");
 4067: 	    } else {
 4068: 		push(@skipped,"$username:$domain");
 4069: 	    }
 4070: 	    next;
 4071: 	}
 4072: 	my $usec=$classlist->{"$username:$domain"}[5];
 4073: 	if (!&canmodify($usec)) {
 4074: 	    push(@notallowed,"$username:$domain");
 4075: 	    next;
 4076: 	}
 4077: 	my %points;
 4078: 	my %grades;
 4079: 	foreach my $dest (keys(%fields)) {
 4080: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 4081: 		$dest eq 'domain') { next; }
 4082: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 4083: 	    if ($dest=~/stores_(.*)_points/) {
 4084: 		my $part=$1;
 4085: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 4086: 					      $symb,$domain,$username);
 4087:                 if ($wgt) {
 4088:                     $entries{$fields{$dest}}=~s/\s//g;
 4089:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 4090:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 4091:                                           : 'correct_by_override';
 4092:                     $grades{"resource.$part.awarded"}=$pcr;
 4093:                     $grades{"resource.$part.solved"}=$award;
 4094:                     $points{$part}=1;
 4095:                 } else {
 4096:                     $error_msg = "<br />" .
 4097:                         &mt("Some point values were assigned"
 4098:                             ." for problems with a weight "
 4099:                             ."of zero. These values were "
 4100:                             ."ignored.");
 4101:                 }
 4102: 	    } else {
 4103: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 4104: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 4105: 		my $store_key=$dest;
 4106: 		$store_key=~s/^stores/resource/;
 4107: 		$store_key=~s/_/\./g;
 4108: 		$grades{$store_key}=$entries{$fields{$dest}};
 4109: 	    }
 4110: 	}
 4111: 	if (! %grades) { 
 4112:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 4113:         } else {
 4114: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 4115: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 4116: 					   $env{'request.course.id'},
 4117: 					   $domain,$username);
 4118: 	   if ($result eq 'ok') {
 4119: 	      $request->print('.');
 4120: 	   } else {
 4121: 	      $request->print("<p><span class=\"LC_error\">".
 4122:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 4123:                                   "$username:$domain",$result)."</span></p>");
 4124: 	   }
 4125: 	   $request->rflush();
 4126: 	   $countdone++;
 4127:         }
 4128:     }
 4129:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
 4130:     if (@skipped) {
 4131: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
 4132:         $request->print(join(', ',@skipped));
 4133:     }
 4134:     if (@notallowed) {
 4135: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
 4136: 	$request->print(join(', ',@notallowed));
 4137:     }
 4138:     $request->print("<br />\n");
 4139:     return $error_msg;
 4140: }
 4141: #------------- end of section for handling csv file upload ---------
 4142: #
 4143: #-------------------------------------------------------------------
 4144: #
 4145: #-------------- Next few routines handle grading by page/sequence
 4146: #
 4147: #--- Select a page/sequence and a student to grade
 4148: sub pickStudentPage {
 4149:     my ($request,$symb) = @_;
 4150: 
 4151:     my $alertmsg = &mt('Please select the student you wish to grade.');
 4152:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
 4153: 
 4154: function checkPickOne(formname) {
 4155:     if (radioSelection(formname.student) == null) {
 4156: 	alert("$alertmsg");
 4157: 	return;
 4158:     }
 4159:     ptr = pullDownSelection(formname.selectpage);
 4160:     formname.page.value = formname["page"+ptr].value;
 4161:     formname.title.value = formname["title"+ptr].value;
 4162:     formname.submit();
 4163: }
 4164: 
 4165: LISTJAVASCRIPT
 4166:     &commonJSfunctions($request);
 4167: 
 4168:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4169:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4170:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4171: 
 4172:     my $result='<h3><span class="LC_info">&nbsp;'.
 4173: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 4174: 
 4175:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 4176:     my $map_error;
 4177:     my ($titles,$symbx) = &getSymbMap($map_error);
 4178:     if ($map_error) {
 4179:         $request->print(&navmap_errormsg());
 4180:         return; 
 4181:     }
 4182:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 4183: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 4184: #    my $type=($curpage =~ /\.(page|sequence)/);
 4185:     my $select = '<select name="selectpage">'."\n";
 4186:     my $ctr=0;
 4187:     foreach (@$titles) {
 4188: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4189: 	$select.='<option value="'.$ctr.'" '.
 4190: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4191: 	    '>'.$showtitle.'</option>'."\n";
 4192: 	$ctr++;
 4193:     }
 4194:     $select.= '</select>';
 4195:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
 4196: 
 4197:     $ctr=0;
 4198:     foreach (@$titles) {
 4199: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4200: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 4201: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 4202: 	$ctr++;
 4203:     }
 4204:     $result.='<input type="hidden" name="page" />'."\n".
 4205: 	'<input type="hidden" name="title" />'."\n";
 4206: 
 4207:     my $options =
 4208: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
 4209: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
 4210:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
 4211: 
 4212:     $options =
 4213: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
 4214: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
 4215: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
 4216:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
 4217:     
 4218:     $result.=&build_section_inputs();
 4219:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4220:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 4221: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 4222: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."<br />\n";
 4223: 
 4224:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
 4225: 
 4226:     $result.='&nbsp;<input type="button" '.
 4227:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 4228: 
 4229:     $request->print($result);
 4230: 
 4231:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 4232: 	&Apache::loncommon::start_data_table().
 4233: 	&Apache::loncommon::start_data_table_header_row().
 4234: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4235: 	'<th>'.&nameUserString('header').'</th>'.
 4236: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4237: 	'<th>'.&nameUserString('header').'</th>'.
 4238: 	&Apache::loncommon::end_data_table_header_row();
 4239:  
 4240:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 4241:     my $ptr = 1;
 4242:     foreach my $student (sort 
 4243: 			 {
 4244: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4245: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4246: 			     }
 4247: 			     return $a cmp $b;
 4248: 			 } (keys(%$fullname))) {
 4249: 	my ($uname,$udom) = split(/:/,$student);
 4250: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 4251:                                   : '</td>');
 4252: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 4253: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 4254: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 4255: 	$studentTable.=
 4256: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 4257:                          : '');
 4258: 	$ptr++;
 4259:     }
 4260:     if ($ptr%2 == 0) {
 4261: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 4262: 	    &Apache::loncommon::end_data_table_row();
 4263:     }
 4264:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 4265:     $studentTable.='<input type="button" '.
 4266:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 4267: 
 4268:     $request->print($studentTable);
 4269: 
 4270:     return '';
 4271: }
 4272: 
 4273: sub getSymbMap {
 4274:     my ($map_error) = @_;
 4275:     my $navmap = Apache::lonnavmaps::navmap->new();
 4276:     unless (ref($navmap)) {
 4277:         if (ref($map_error)) {
 4278:             $$map_error = 'navmap';
 4279:         }
 4280:         return;
 4281:     }
 4282:     my %symbx = ();
 4283:     my @titles = ();
 4284:     my $minder = 0;
 4285: 
 4286:     # Gather every sequence that has problems.
 4287:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 4288: 					       1,0,1);
 4289:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 4290: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 4291: 	    my $title = $minder.'.'.
 4292: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 4293: 	    push(@titles, $title); # minder in case two titles are identical
 4294: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 4295: 	    $minder++;
 4296: 	}
 4297:     }
 4298:     return \@titles,\%symbx;
 4299: }
 4300: 
 4301: #
 4302: #--- Displays a page/sequence w/wo problems, w/wo submissions
 4303: sub displayPage {
 4304:     my ($request,$symb) = @_;
 4305:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4306:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4307:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4308:     my $pageTitle = $env{'form.page'};
 4309:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4310:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4311:     my $usec=$classlist->{$env{'form.student'}}[5];
 4312: 
 4313:     #need to make sure we have the correct data for later EXT calls, 
 4314:     #thus invalidate the cache
 4315:     &Apache::lonnet::devalidatecourseresdata(
 4316:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 4317:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 4318:     &Apache::lonnet::clear_EXT_cache_status();
 4319: 
 4320:     if (!&canview($usec)) {
 4321: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
 4322: 	return;
 4323:     }
 4324:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4325:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 4326: 	'</h3>'."\n";
 4327:     $env{'form.CODE'} = uc($env{'form.CODE'});
 4328:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 4329: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 4330:     } else {
 4331: 	delete($env{'form.CODE'});
 4332:     }
 4333:     &sub_page_js($request);
 4334:     $request->print($result);
 4335: 
 4336:     my $navmap = Apache::lonnavmaps::navmap->new();
 4337:     unless (ref($navmap)) {
 4338:         $request->print(&navmap_errormsg());
 4339:         return;
 4340:     }
 4341:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 4342:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4343:     if (!$map) {
 4344: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 4345: 	return; 
 4346:     }
 4347:     my $iterator = $navmap->getIterator($map->map_start(),
 4348: 					$map->map_finish());
 4349: 
 4350:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 4351: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 4352: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 4353: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 4354: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 4355: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 4356: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4357: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
 4358: 
 4359:     if (defined($env{'form.CODE'})) {
 4360: 	$studentTable.=
 4361: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 4362:     }
 4363:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 4364: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 4365: 
 4366:     $studentTable.='&nbsp;<span class="LC_info">'.
 4367:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
 4368:         '</span>'."\n".
 4369: 	&Apache::loncommon::start_data_table().
 4370: 	&Apache::loncommon::start_data_table_header_row().
 4371: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
 4372: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 4373: 	&Apache::loncommon::end_data_table_header_row();
 4374: 
 4375:     &Apache::lonxml::clear_problem_counter();
 4376:     my ($depth,$question,$prob) = (1,1,1);
 4377:     $iterator->next(); # skip the first BEGIN_MAP
 4378:     my $curRes = $iterator->next(); # for "current resource"
 4379:     while ($depth > 0) {
 4380:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4381:         if($curRes == $iterator->END_MAP) { $depth--; }
 4382: 
 4383:         if (ref($curRes) && $curRes->is_problem()) {
 4384: 	    my $parts = $curRes->parts();
 4385:             my $title = $curRes->compTitle();
 4386: 	    my $symbx = $curRes->symb();
 4387: 	    $studentTable.=
 4388: 		&Apache::loncommon::start_data_table_row().
 4389: 		'<td align="center" valign="top" >'.$prob.
 4390: 		(scalar(@{$parts}) == 1 ? '' 
 4391: 		                        : '<br />('.&mt('[_1]&nbsp;parts)',
 4392: 							scalar(@{$parts}))
 4393: 		 ).
 4394: 		 '</td>';
 4395: 	    $studentTable.='<td valign="top">';
 4396: 	    my %form = ('CODE' => $env{'form.CODE'},);
 4397: 	    if ($env{'form.vProb'} eq 'yes' ) {
 4398: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 4399: 					     undef,'both',\%form);
 4400: 	    } else {
 4401: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 4402: 		$companswer =~ s|<form(.*?)>||g;
 4403: 		$companswer =~ s|</form>||g;
 4404: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 4405: #		    $companswer =~ s/$1/ /ms;
 4406: #		    $request->print('match='.$1."<br />\n");
 4407: #		}
 4408: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 4409: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 4410: 	    }
 4411: 
 4412: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 4413: 
 4414: 	    if ($env{'form.lastSub'} eq 'datesub') {
 4415: 		if ($record{'version'} eq '') {
 4416: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
 4417: 		} else {
 4418: 		    my %responseType = ();
 4419: 		    foreach my $partid (@{$parts}) {
 4420: 			my @responseIds =$curRes->responseIds($partid);
 4421: 			my @responseType =$curRes->responseType($partid);
 4422: 			my %responseIds;
 4423: 			for (my $i=0;$i<=$#responseIds;$i++) {
 4424: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 4425: 			}
 4426: 			$responseType{$partid} = \%responseIds;
 4427: 		    }
 4428: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 4429: 
 4430: 		}
 4431: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 4432: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 4433: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 4434: 									$env{'request.course.id'},
 4435: 									'','.submission');
 4436:  
 4437: 	    }
 4438: 	    if (&canmodify($usec)) {
 4439:             $studentTable.=&gradeBox_start();
 4440: 		foreach my $partid (@{$parts}) {
 4441: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 4442: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 4443: 		    $question++;
 4444: 		}
 4445:             $studentTable.=&gradeBox_end();
 4446: 		$prob++;
 4447: 	    }
 4448: 	    $studentTable.='</td></tr>';
 4449: 
 4450: 	}
 4451:         $curRes = $iterator->next();
 4452:     }
 4453: 
 4454:     $studentTable.=
 4455:         '</table>'."\n".
 4456:         '<input type="button" value="'.&mt('Save').'" '.
 4457:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 4458:         '</form>'."\n";
 4459:     $request->print($studentTable);
 4460: 
 4461:     return '';
 4462: }
 4463: 
 4464: sub displaySubByDates {
 4465:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 4466:     my $isCODE=0;
 4467:     my $isTask = ($symb =~/\.task$/);
 4468:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 4469:     my $studentTable=&Apache::loncommon::start_data_table().
 4470: 	&Apache::loncommon::start_data_table_header_row().
 4471: 	'<th>'.&mt('Date/Time').'</th>'.
 4472: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 4473: 	'<th>'.&mt('Submission').'</th>'.
 4474: 	'<th>'.&mt('Status').'</th>'.
 4475: 	&Apache::loncommon::end_data_table_header_row();
 4476:     my ($version);
 4477:     my %mark;
 4478:     my %orders;
 4479:     $mark{'correct_by_student'} = $checkIcon;
 4480:     if (!exists($$record{'1:timestamp'})) {
 4481: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 4482:     }
 4483: 
 4484:     my $interaction;
 4485:     my $no_increment = 1;
 4486:     for ($version=1;$version<=$$record{'version'};$version++) {
 4487: 	my $timestamp = 
 4488: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 4489: 	if (exists($$record{$version.':resource.0.version'})) {
 4490: 	    $interaction = $$record{$version.':resource.0.version'};
 4491: 	}
 4492: 
 4493: 	my $where = ($isTask ? "$version:resource.$interaction"
 4494: 		             : "$version:resource");
 4495: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 4496: 	    '<td>'.$timestamp.'</td>';
 4497: 	if ($isCODE) {
 4498: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 4499: 	}
 4500: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 4501: 	my @displaySub = ();
 4502: 	foreach my $partid (@{$parts}) {
 4503:             my $hidden;
 4504:             if (($$record{$version.':resource.'.$partid.'.type'} eq 'anonsurvey') ||
 4505:                 ($$record{$version.':resource.'.$partid.'.type'} eq 'anonsurveycred')) {
 4506:                 $hidden = 1;
 4507:             }
 4508: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
 4509: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 4510: 	    
 4511: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 4512: 	    my $display_part=&get_display_part($partid,$symb);
 4513: 	    foreach my $matchKey (@matchKey) {
 4514: 		if (exists($$record{$version.':'.$matchKey}) &&
 4515: 		    $$record{$version.':'.$matchKey} ne '') {
 4516:                     
 4517: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 4518: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 4519:                     $displaySub[0].='<span class="LC_nobreak"';
 4520:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
 4521:                                    .' <span class="LC_internal_info">'
 4522:                                    .'('.&mt('Part ID: [_1]',$responseId).')'
 4523:                                    .'</span>'
 4524:                                    .' <b>';
 4525:                     if ($hidden) {
 4526:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
 4527:                     } else {
 4528: 		        if ($$record{"$where.$partid.tries"} eq '') {
 4529: 			    $displaySub[0].=&mt('Trial not counted');
 4530: 		        } else {
 4531: 			    $displaySub[0].=&mt('Trial: [_1]',
 4532: 					    $$record{"$where.$partid.tries"});
 4533: 		        }
 4534: 		        my $responseType=($isTask ? 'Task'
 4535:                                               : $responseType->{$partid}->{$responseId});
 4536: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
 4537: 		        if (!exists($orders{$partid}->{$responseId})) {
 4538: 			    $orders{$partid}->{$responseId}=
 4539: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
 4540:                                            $no_increment);
 4541: 		        }
 4542: 		        $displaySub[0].='</b></span>'; # /nobreak
 4543: 		        $displaySub[0].='&nbsp; '.
 4544: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
 4545:                     }
 4546: 		}
 4547: 	    }
 4548: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 4549: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 4550: 				    $$record{"$where.$partid.checkedin"},
 4551: 				    $$record{"$where.$partid.checkedin.slot"}).
 4552: 					'<br />';
 4553: 	    }
 4554: 	    if (exists $$record{"$where.$partid.award"}) {
 4555: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 4556: 		    lc($$record{"$where.$partid.award"}).' '.
 4557: 		    $mark{$$record{"$where.$partid.solved"}}.
 4558: 		    '<br />';
 4559: 	    }
 4560: 	    if (exists $$record{"$where.$partid.regrader"}) {
 4561: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 4562: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4563: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 4564: 		$displaySub[2].=
 4565: 		    $$record{"$version:resource.$partid.regrader"}.
 4566: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4567: 	    }
 4568: 	}
 4569: 	# needed because old essay regrader has not parts info
 4570: 	if (exists $$record{"$version:resource.regrader"}) {
 4571: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 4572: 	}
 4573: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 4574: 	if ($displaySub[2]) {
 4575: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 4576: 	}
 4577: 	$studentTable.='&nbsp;</td>'.
 4578: 	    &Apache::loncommon::end_data_table_row();
 4579:     }
 4580:     $studentTable.=&Apache::loncommon::end_data_table();
 4581:     return $studentTable;
 4582: }
 4583: 
 4584: sub updateGradeByPage {
 4585:     my ($request,$symb) = @_;
 4586: 
 4587:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4588:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4589:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4590:     my $pageTitle = $env{'form.page'};
 4591:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4592:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4593:     my $usec=$classlist->{$env{'form.student'}}[5];
 4594:     if (!&canmodify($usec)) {
 4595: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 4596: 	return;
 4597:     }
 4598:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4599:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 4600: 	'</h3>'."\n";
 4601: 
 4602:     $request->print($result);
 4603: 
 4604: 
 4605:     my $navmap = Apache::lonnavmaps::navmap->new();
 4606:     unless (ref($navmap)) {
 4607:         $request->print(&navmap_errormsg());
 4608:         return;
 4609:     }
 4610:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 4611:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4612:     if (!$map) {
 4613: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 4614: 	return; 
 4615:     }
 4616:     my $iterator = $navmap->getIterator($map->map_start(),
 4617: 					$map->map_finish());
 4618: 
 4619:     my $studentTable=
 4620: 	&Apache::loncommon::start_data_table().
 4621: 	&Apache::loncommon::start_data_table_header_row().
 4622: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 4623: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 4624: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 4625: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 4626: 	&Apache::loncommon::end_data_table_header_row();
 4627: 
 4628:     $iterator->next(); # skip the first BEGIN_MAP
 4629:     my $curRes = $iterator->next(); # for "current resource"
 4630:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
 4631:     while ($depth > 0) {
 4632:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4633:         if($curRes == $iterator->END_MAP) { $depth--; }
 4634: 
 4635:         if (ref($curRes) && $curRes->is_problem()) {
 4636: 	    my $parts = $curRes->parts();
 4637:             my $title = $curRes->compTitle();
 4638: 	    my $symbx = $curRes->symb();
 4639: 	    $studentTable.=
 4640: 		&Apache::loncommon::start_data_table_row().
 4641: 		'<td align="center" valign="top" >'.$prob.
 4642: 		(scalar(@{$parts}) == 1 ? '' 
 4643:                                         : '<br />('.&mt('[quant,_1,&nbsp;part]',scalar(@{$parts}))
 4644: 		.')').'</td>';
 4645: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 4646: 
 4647: 	    my %newrecord=();
 4648: 	    my @displayPts=();
 4649:             my %aggregate = ();
 4650:             my $aggregateflag = 0;
 4651: 	    foreach my $partid (@{$parts}) {
 4652: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 4653: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 4654: 
 4655: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 4656: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 4657: 		my $partial = $newpts/$wgt;
 4658: 		my $score;
 4659: 		if ($partial > 0) {
 4660: 		    $score = 'correct_by_override';
 4661: 		} elsif ($newpts ne '') { #empty is taken as 0
 4662: 		    $score = 'incorrect_by_override';
 4663: 		}
 4664: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 4665: 		if ($dropMenu eq 'excused') {
 4666: 		    $partial = '';
 4667: 		    $score = 'excused';
 4668: 		} elsif ($dropMenu eq 'reset status'
 4669: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 4670: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 4671: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 4672: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 4673: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 4674: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 4675: 		    $changeflag++;
 4676: 		    $newpts = '';
 4677:                     
 4678:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 4679:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 4680:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 4681:                     if ($aggtries > 0) {
 4682:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4683:                         $aggregateflag = 1;
 4684:                     }
 4685: 		}
 4686: 		my $display_part=&get_display_part($partid,$curRes->symb());
 4687: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 4688: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4689: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 4690: 		    '&nbsp;<br />';
 4691: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4692: 		     (($score eq 'excused') ? 'excused' : $newpts).
 4693: 		    '&nbsp;<br />';
 4694: 		$question++;
 4695: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 4696: 
 4697: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 4698: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 4699: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 4700: 		    if (scalar(keys(%newrecord)) > 0);
 4701: 
 4702: 		$changeflag++;
 4703: 	    }
 4704: 	    if (scalar(keys(%newrecord)) > 0) {
 4705: 		my %record = 
 4706: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 4707: 					     $udom,$uname);
 4708: 
 4709: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 4710: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 4711: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 4712: 		    $newrecord{'resource.CODE'} = '';
 4713: 		}
 4714: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 4715: 					$udom,$uname);
 4716: 		%record = &Apache::lonnet::restore($symbx,
 4717: 						   $env{'request.course.id'},
 4718: 						   $udom,$uname);
 4719: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 4720: 					     $cdom,$cnum,$udom,$uname);
 4721: 	    }
 4722: 	    
 4723:             if ($aggregateflag) {
 4724:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4725:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 4726:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 4727:             }
 4728: 
 4729: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 4730: 		'<td valign="top">'.$displayPts[1].'</td>'.
 4731: 		&Apache::loncommon::end_data_table_row();
 4732: 
 4733: 	    $prob++;
 4734: 	}
 4735:         $curRes = $iterator->next();
 4736:     }
 4737: 
 4738:     $studentTable.=&Apache::loncommon::end_data_table();
 4739:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 4740: 		  &mt('The scores were changed for [quant,_1,problem].',
 4741: 		  $changeflag));
 4742:     $request->print($grademsg.$studentTable);
 4743: 
 4744:     return '';
 4745: }
 4746: 
 4747: #-------- end of section for handling grading by page/sequence ---------
 4748: #
 4749: #-------------------------------------------------------------------
 4750: 
 4751: #-------------------- Bubblesheet (Scantron) Grading -------------------
 4752: #
 4753: #------ start of section for handling grading by page/sequence ---------
 4754: 
 4755: =pod
 4756: 
 4757: =head1 Bubble sheet grading routines
 4758: 
 4759:   For this documentation:
 4760: 
 4761:    'scanline' refers to the full line of characters
 4762:    from the file that we are parsing that represents one entire sheet
 4763: 
 4764:    'bubble line' refers to the data
 4765:    representing the line of bubbles that are on the physical bubble sheet
 4766: 
 4767: 
 4768: The overall process is that a scanned in bubble sheet data is uploaded
 4769: into a course. When a user wants to grade, they select a
 4770: sequence/folder of resources, a file of bubble sheet info, and pick
 4771: one of the predefined configurations for what each scanline looks
 4772: like.
 4773: 
 4774: Next each scanline is checked for any errors of either 'missing
 4775: bubbles' (it's an error because it may have been mis-scanned
 4776: because too light bubbling), 'double bubble' (each bubble line should
 4777: have no more that one letter picked), invalid or duplicated CODE,
 4778: invalid student/employee ID
 4779: 
 4780: If the CODE option is used that determines the randomization of the
 4781: homework problems, either way the student/employee ID is looked up into a
 4782: username:domain.
 4783: 
 4784: During the validation phase the instructor can choose to skip scanlines. 
 4785: 
 4786: After the validation phase, there are now 3 bubble sheet files
 4787: 
 4788:   scantron_original_filename (unmodified original file)
 4789:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 4790:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 4791: 
 4792: Also there is a separate hash nohist_scantrondata that contains extra
 4793: correction information that isn't representable in the bubble sheet
 4794: file (see &scantron_getfile() for more information)
 4795: 
 4796: After all scanlines are either valid, marked as valid or skipped, then
 4797: foreach line foreach problem in the picked sequence, an ssi request is
 4798: made that simulates a user submitting their selected letter(s) against
 4799: the homework problem.
 4800: 
 4801: =over 4
 4802: 
 4803: 
 4804: 
 4805: =item defaultFormData
 4806: 
 4807:   Returns html hidden inputs used to hold context/default values.
 4808: 
 4809:  Arguments:
 4810:   $symb - $symb of the current resource 
 4811: 
 4812: =cut
 4813: 
 4814: sub defaultFormData {
 4815:     my ($symb)=@_;
 4816:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />';
 4817: }
 4818: 
 4819: 
 4820: =pod 
 4821: 
 4822: =item getSequenceDropDown
 4823: 
 4824:    Return html dropdown of possible sequences to grade
 4825:  
 4826:  Arguments:
 4827:    $symb - $symb of the current resource
 4828:    $map_error - ref to scalar which will container error if
 4829:                 $navmap object is unavailable in &getSymbMap().
 4830: 
 4831: =cut
 4832: 
 4833: sub getSequenceDropDown {
 4834:     my ($symb,$map_error)=@_;
 4835:     my $result='<select name="selectpage">'."\n";
 4836:     my ($titles,$symbx) = &getSymbMap($map_error);
 4837:     if (ref($map_error)) {
 4838:         return if ($$map_error);
 4839:     }
 4840:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 4841:     my $ctr=0;
 4842:     foreach (@$titles) {
 4843: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4844: 	$result.='<option value="'.$$symbx{$_}.'" '.
 4845: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4846: 	    '>'.$showtitle.'</option>'."\n";
 4847: 	$ctr++;
 4848:     }
 4849:     $result.= '</select>';
 4850:     return $result;
 4851: }
 4852: 
 4853: my %bubble_lines_per_response;     # no. bubble lines for each response.
 4854:                                    # key is zero-based index - 0, 1, 2 ...
 4855: 
 4856: my %first_bubble_line;             # First bubble line no. for each bubble.
 4857: 
 4858: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 4859:                                    # matchresponse or rankresponse, where 
 4860:                                    # an individual response can have multiple 
 4861:                                    # lines
 4862: 
 4863: my %responsetype_per_response;     # responsetype for each response
 4864: 
 4865: # Save and restore the bubble lines array to the form env.
 4866: 
 4867: 
 4868: sub save_bubble_lines {
 4869:     foreach my $line (keys(%bubble_lines_per_response)) {
 4870: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 4871: 	$env{"form.scantron.first_bubble_line.$line"} =
 4872: 	    $first_bubble_line{$line};
 4873:         $env{"form.scantron.sub_bubblelines.$line"} = 
 4874:             $subdivided_bubble_lines{$line};
 4875:         $env{"form.scantron.responsetype.$line"} =
 4876:             $responsetype_per_response{$line};
 4877:     }
 4878: }
 4879: 
 4880: 
 4881: sub restore_bubble_lines {
 4882:     my $line = 0;
 4883:     %bubble_lines_per_response = ();
 4884:     while ($env{"form.scantron.bubblelines.$line"}) {
 4885: 	my $value = $env{"form.scantron.bubblelines.$line"};
 4886: 	$bubble_lines_per_response{$line} = $value;
 4887: 	$first_bubble_line{$line}  =
 4888: 	    $env{"form.scantron.first_bubble_line.$line"};
 4889:         $subdivided_bubble_lines{$line} =
 4890:             $env{"form.scantron.sub_bubblelines.$line"};
 4891:         $responsetype_per_response{$line} =
 4892:             $env{"form.scantron.responsetype.$line"};
 4893: 	$line++;
 4894:     }
 4895: }
 4896: 
 4897: #  Given the parsed scanline, get the response for 
 4898: #  'answer' number n:
 4899: 
 4900: sub get_response_bubbles {
 4901:     my ($parsed_line, $response)  = @_;
 4902: 
 4903:     my $bubble_line = $first_bubble_line{$response-1} +1;
 4904:     my $bubble_lines= $bubble_lines_per_response{$response-1};
 4905:     
 4906:     my $selected = "";
 4907: 
 4908:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
 4909: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
 4910: 	$bubble_line++;
 4911:     }
 4912:     return $selected;
 4913: }
 4914: 
 4915: =pod 
 4916: 
 4917: =item scantron_filenames
 4918: 
 4919:    Returns a list of the scantron files in the current course 
 4920: 
 4921: =cut
 4922: 
 4923: sub scantron_filenames {
 4924:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4925:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4926:     my $getpropath = 1;
 4927:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
 4928:                                        $getpropath);
 4929:     my @possiblenames;
 4930:     foreach my $filename (sort(@files)) {
 4931: 	($filename)=split(/&/,$filename);
 4932: 	if ($filename!~/^scantron_orig_/) { next ; }
 4933: 	$filename=~s/^scantron_orig_//;
 4934: 	push(@possiblenames,$filename);
 4935:     }
 4936:     return @possiblenames;
 4937: }
 4938: 
 4939: =pod 
 4940: 
 4941: =item scantron_uploads
 4942: 
 4943:    Returns  html drop-down list of scantron files in current course.
 4944: 
 4945:  Arguments:
 4946:    $file2grade - filename to set as selected in the dropdown
 4947: 
 4948: =cut
 4949: 
 4950: sub scantron_uploads {
 4951:     my ($file2grade) = @_;
 4952:     my $result=	'<select name="scantron_selectfile">';
 4953:     $result.="<option></option>";
 4954:     foreach my $filename (sort(&scantron_filenames())) {
 4955: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 4956:     }
 4957:     $result.="</select>";
 4958:     return $result;
 4959: }
 4960: 
 4961: =pod 
 4962: 
 4963: =item scantron_scantab
 4964: 
 4965:   Returns html drop down of the scantron formats in the scantronformat.tab
 4966:   file.
 4967: 
 4968: =cut
 4969: 
 4970: sub scantron_scantab {
 4971:     my $result='<select name="scantron_format">'."\n";
 4972:     $result.='<option></option>'."\n";
 4973:     my @lines = &get_scantronformat_file();
 4974:     if (@lines > 0) {
 4975:         foreach my $line (@lines) {
 4976:             next if (($line =~ /^\#/) || ($line eq ''));
 4977: 	    my ($name,$descrip)=split(/:/,$line);
 4978: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 4979:         }
 4980:     }
 4981:     $result.='</select>'."\n";
 4982:     return $result;
 4983: }
 4984: 
 4985: =pod
 4986: 
 4987: =item get_scantronformat_file
 4988: 
 4989:   Returns an array containing lines from the scantron format file for
 4990:   the domain of the course.
 4991: 
 4992:   If a url for a custom.tab file is listed in domain's configuration.db, 
 4993:   lines are from this file.
 4994: 
 4995:   Otherwise, if a default.tab has been published in RES space by the 
 4996:   domainconfig user, lines are from this file.
 4997: 
 4998:   Otherwise, fall back to getting lines from the legacy file on the
 4999:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
 5000: 
 5001: =cut
 5002: 
 5003: sub get_scantronformat_file {
 5004:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5005:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
 5006:     my $gottab = 0;
 5007:     my @lines;
 5008:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 5009:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 5010:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 5011:             if ($formatfile ne '-1') {
 5012:                 @lines = split("\n",$formatfile,-1);
 5013:                 $gottab = 1;
 5014:             }
 5015:         }
 5016:     }
 5017:     if (!$gottab) {
 5018:         my $confname = $cdom.'-domainconfig';
 5019:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 5020:         my $formatfile =  &Apache::lonnet::getfile($default);
 5021:         if ($formatfile ne '-1') {
 5022:             @lines = split("\n",$formatfile,-1);
 5023:             $gottab = 1;
 5024:         }
 5025:     }
 5026:     if (!$gottab) {
 5027:         my @domains = &Apache::lonnet::current_machine_domains();
 5028:         if (grep(/^\Q$cdom\E$/,@domains)) {
 5029:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 5030:             @lines = <$fh>;
 5031:             close($fh);
 5032:         } else {
 5033:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
 5034:             @lines = <$fh>;
 5035:             close($fh);
 5036:         }
 5037:     }
 5038:     return @lines;
 5039: }
 5040: 
 5041: =pod 
 5042: 
 5043: =item scantron_CODElist
 5044: 
 5045:   Returns html drop down of the saved CODE lists from current course,
 5046:   generated from earlier printings.
 5047: 
 5048: =cut
 5049: 
 5050: sub scantron_CODElist {
 5051:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5052:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5053:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 5054:     my $namechoice='<option></option>';
 5055:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 5056: 	if ($name =~ /^error: 2 /) { next; }
 5057: 	if ($name =~ /^type\0/) { next; }
 5058: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 5059:     }
 5060:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 5061:     return $namechoice;
 5062: }
 5063: 
 5064: =pod 
 5065: 
 5066: =item scantron_CODEunique
 5067: 
 5068:   Returns the html for "Each CODE to be used once" radio.
 5069: 
 5070: =cut
 5071: 
 5072: sub scantron_CODEunique {
 5073:     my $result='<span class="LC_nobreak">
 5074:                  <label><input type="radio" name="scantron_CODEunique"
 5075:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 5076:                 </span>
 5077:                 <span class="LC_nobreak">
 5078:                  <label><input type="radio" name="scantron_CODEunique"
 5079:                         value="no" />'.&mt('No').' </label>
 5080:                 </span>';
 5081:     return $result;
 5082: }
 5083: 
 5084: =pod 
 5085: 
 5086: =item scantron_selectphase
 5087: 
 5088:   Generates the initial screen to start the bubble sheet process.
 5089:   Allows for - starting a grading run.
 5090:              - downloading existing scan data (original, corrected
 5091:                                                 or skipped info)
 5092: 
 5093:              - uploading new scan data
 5094: 
 5095:  Arguments:
 5096:   $r          - The Apache request object
 5097:   $file2grade - name of the file that contain the scanned data to score
 5098: 
 5099: =cut
 5100: 
 5101: sub scantron_selectphase {
 5102:     my ($r,$file2grade,$symb) = @_;
 5103:     if (!$symb) {return '';}
 5104:     my $map_error;
 5105:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
 5106:     if ($map_error) {
 5107:         $r->print('<br />'.&navmap_errormsg().'<br />');
 5108:         return;
 5109:     }
 5110:     my $default_form_data=&defaultFormData($symb);
 5111:     my $file_selector=&scantron_uploads($file2grade);
 5112:     my $format_selector=&scantron_scantab();
 5113:     my $CODE_selector=&scantron_CODElist();
 5114:     my $CODE_unique=&scantron_CODEunique();
 5115:     my $result;
 5116: 
 5117:     $ssi_error = 0;
 5118: 
 5119:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 5120:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 5121: 
 5122: 	# Chunk of form to prompt for a scantron file upload.
 5123: 
 5124:         $r->print('
 5125:     <br />
 5126:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5127:        '.&Apache::loncommon::start_data_table_header_row().'
 5128:             <th>
 5129:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
 5130:             </th>
 5131:        '.&Apache::loncommon::end_data_table_header_row().'
 5132:        '.&Apache::loncommon::start_data_table_row().'
 5133:             <td>
 5134: ');
 5135:     my $default_form_data=&defaultFormData($symb);
 5136:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5137:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 5138:     $r->print(&Apache::lonhtmlcommon::scripttag('
 5139:     function checkUpload(formname) {
 5140: 	if (formname.upfile.value == "") {
 5141: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
 5142: 	    return false;
 5143: 	}
 5144: 	formname.submit();
 5145:     }'));
 5146:     $r->print('
 5147:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 5148:                 '.$default_form_data.'
 5149:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 5150:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 5151:                 <input name="command" value="scantronupload_save" type="hidden" />
 5152:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
 5153:                 <br />
 5154:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 5155:               </form>
 5156: ');
 5157: 
 5158:         $r->print('
 5159:             </td>
 5160:        '.&Apache::loncommon::end_data_table_row().'
 5161:        '.&Apache::loncommon::end_data_table().'
 5162: ');
 5163:     }
 5164: 
 5165:     # Chunk of form to prompt for a file to grade and how:
 5166: 
 5167:     $result.= '
 5168:     <br />
 5169:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 5170:     <input type="hidden" name="command" value="scantron_warning" />
 5171:     '.$default_form_data.'
 5172:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5173:        '.&Apache::loncommon::start_data_table_header_row().'
 5174:             <th colspan="2">
 5175:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 5176:             </th>
 5177:        '.&Apache::loncommon::end_data_table_header_row().'
 5178:        '.&Apache::loncommon::start_data_table_row().'
 5179:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 5180:        '.&Apache::loncommon::end_data_table_row().'
 5181:        '.&Apache::loncommon::start_data_table_row().'
 5182:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
 5183:        '.&Apache::loncommon::end_data_table_row().'
 5184:        '.&Apache::loncommon::start_data_table_row().'
 5185:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
 5186:        '.&Apache::loncommon::end_data_table_row().'
 5187:        '.&Apache::loncommon::start_data_table_row().'
 5188:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 5189:        '.&Apache::loncommon::end_data_table_row().'
 5190:        '.&Apache::loncommon::start_data_table_row().'
 5191:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 5192:        '.&Apache::loncommon::end_data_table_row().'
 5193:        '.&Apache::loncommon::start_data_table_row().'
 5194: 	    <td> '.&mt('Options:').' </td>
 5195:             <td>
 5196: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 5197:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 5198:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 5199: 	    </td>
 5200:        '.&Apache::loncommon::end_data_table_row().'
 5201:        '.&Apache::loncommon::start_data_table_row().'
 5202:             <td colspan="2">
 5203:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
 5204:             </td>
 5205:        '.&Apache::loncommon::end_data_table_row().'
 5206:     '.&Apache::loncommon::end_data_table().'
 5207:     </form>
 5208: ';
 5209:    
 5210:     $r->print($result);
 5211: 
 5212: 
 5213: 
 5214:     # Chunk of the form that prompts to view a scoring office file,
 5215:     # corrected file, skipped records in a file.
 5216: 
 5217:     $r->print('
 5218:    <br />
 5219:    <form action="/adm/grades" name="scantron_download">
 5220:      '.$default_form_data.'
 5221:      <input type="hidden" name="command" value="scantron_download" />
 5222:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5223:        '.&Apache::loncommon::start_data_table_header_row().'
 5224:               <th>
 5225:                 &nbsp;'.&mt('Download a scoring office file').'
 5226:               </th>
 5227:        '.&Apache::loncommon::end_data_table_header_row().'
 5228:        '.&Apache::loncommon::start_data_table_row().'
 5229:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 5230:                 <br />
 5231:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 5232:        '.&Apache::loncommon::end_data_table_row().'
 5233:      '.&Apache::loncommon::end_data_table().'
 5234:    </form>
 5235:    <br />
 5236: ');
 5237: 
 5238:     &Apache::lonpickcode::code_list($r,2);
 5239: 
 5240:     $r->print('<br /><form method="post" name="checkscantron">'.
 5241:              $default_form_data."\n".
 5242:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 5243:              &Apache::loncommon::start_data_table_header_row()."\n".
 5244:              '<th colspan="2">
 5245:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
 5246:              '</th>'."\n".
 5247:               &Apache::loncommon::end_data_table_header_row()."\n".
 5248:               &Apache::loncommon::start_data_table_row()."\n".
 5249:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 5250:               '<td> '.$sequence_selector.' </td>'.
 5251:               &Apache::loncommon::end_data_table_row()."\n".
 5252:               &Apache::loncommon::start_data_table_row()."\n".
 5253:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 5254:               '<td> '.$file_selector.' </td>'."\n".
 5255:               &Apache::loncommon::end_data_table_row()."\n".
 5256:               &Apache::loncommon::start_data_table_row()."\n".
 5257:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 5258:               '<td> '.$format_selector.' </td>'."\n".
 5259:               &Apache::loncommon::end_data_table_row()."\n".
 5260:               &Apache::loncommon::start_data_table_row()."\n".
 5261:               '<td> '.&mt('Options').' </td>'."\n".
 5262:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
 5263:               &Apache::loncommon::end_data_table_row()."\n".
 5264:               &Apache::loncommon::start_data_table_row()."\n".
 5265:               '<td colspan="2">'."\n".
 5266:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 5267:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
 5268:               '</td>'."\n".
 5269:               &Apache::loncommon::end_data_table_row()."\n".
 5270:               &Apache::loncommon::end_data_table()."\n".
 5271:               '</form><br />');
 5272:     return;
 5273: }
 5274: 
 5275: =pod
 5276: 
 5277: =item get_scantron_config
 5278: 
 5279:    Parse and return the scantron configuration line selected as a
 5280:    hash of configuration file fields.
 5281: 
 5282:  Arguments:
 5283:     which - the name of the configuration to parse from the file.
 5284: 
 5285: 
 5286:  Returns:
 5287:             If the named configuration is not in the file, an empty
 5288:             hash is returned.
 5289:     a hash with the fields
 5290:       name         - internal name for the this configuration setup
 5291:       description  - text to display to operator that describes this config
 5292:       CODElocation - if 0 or the string 'none'
 5293:                           - no CODE exists for this config
 5294:                      if -1 || the string 'letter'
 5295:                           - a CODE exists for this config and is
 5296:                             a string of letters
 5297:                      Unsupported value (but planned for future support)
 5298:                           if a positive integer
 5299:                                - The CODE exists as the first n items from
 5300:                                  the question section of the form
 5301:                           if the string 'number'
 5302:                                - The CODE exists for this config and is
 5303:                                  a string of numbers
 5304:       CODEstart   - (only matter if a CODE exists) column in the line where
 5305:                      the CODE starts
 5306:       CODElength  - length of the CODE
 5307:       IDstart     - column where the student/employee ID starts
 5308:       IDlength    - length of the student/employee ID info
 5309:       Qstart      - column where the information from the bubbled
 5310:                     'questions' start
 5311:       Qlength     - number of columns comprising a single bubble line from
 5312:                     the sheet. (usually either 1 or 10)
 5313:       Qon         - either a single character representing the character used
 5314:                     to signal a bubble was chosen in the positional setup, or
 5315:                     the string 'letter' if the letter of the chosen bubble is
 5316:                     in the final, or 'number' if a number representing the
 5317:                     chosen bubble is in the file (1->A 0->J)
 5318:       Qoff        - the character used to represent that a bubble was
 5319:                     left blank
 5320:       PaperID     - if the scanning process generates a unique number for each
 5321:                     sheet scanned the column that this ID number starts in
 5322:       PaperIDlength - number of columns that comprise the unique ID number
 5323:                       for the sheet of paper
 5324:       FirstName   - column that the first name starts in
 5325:       FirstNameLength - number of columns that the first name spans
 5326:  
 5327:       LastName    - column that the last name starts in
 5328:       LastNameLength - number of columns that the last name spans
 5329: 
 5330: =cut
 5331: 
 5332: sub get_scantron_config {
 5333:     my ($which) = @_;
 5334:     my @lines = &get_scantronformat_file();
 5335:     my %config;
 5336:     #FIXME probably should move to XML it has already gotten a bit much now
 5337:     foreach my $line (@lines) {
 5338: 	my ($name,$descrip)=split(/:/,$line);
 5339: 	if ($name ne $which ) { next; }
 5340: 	chomp($line);
 5341: 	my @config=split(/:/,$line);
 5342: 	$config{'name'}=$config[0];
 5343: 	$config{'description'}=$config[1];
 5344: 	$config{'CODElocation'}=$config[2];
 5345: 	$config{'CODEstart'}=$config[3];
 5346: 	$config{'CODElength'}=$config[4];
 5347: 	$config{'IDstart'}=$config[5];
 5348: 	$config{'IDlength'}=$config[6];
 5349: 	$config{'Qstart'}=$config[7];
 5350:  	$config{'Qlength'}=$config[8];
 5351: 	$config{'Qoff'}=$config[9];
 5352: 	$config{'Qon'}=$config[10];
 5353: 	$config{'PaperID'}=$config[11];
 5354: 	$config{'PaperIDlength'}=$config[12];
 5355: 	$config{'FirstName'}=$config[13];
 5356: 	$config{'FirstNamelength'}=$config[14];
 5357: 	$config{'LastName'}=$config[15];
 5358: 	$config{'LastNamelength'}=$config[16];
 5359: 	last;
 5360:     }
 5361:     return %config;
 5362: }
 5363: 
 5364: =pod 
 5365: 
 5366: =item username_to_idmap
 5367: 
 5368:     creates a hash keyed by student/employee ID with values of the corresponding
 5369:     student username:domain.
 5370: 
 5371:   Arguments:
 5372: 
 5373:     $classlist - reference to the class list hash. This is a hash
 5374:                  keyed by student name:domain  whose elements are references
 5375:                  to arrays containing various chunks of information
 5376:                  about the student. (See loncoursedata for more info).
 5377: 
 5378:   Returns
 5379:     %idmap - the constructed hash
 5380: 
 5381: =cut
 5382: 
 5383: sub username_to_idmap {
 5384:     my ($classlist)= @_;
 5385:     my %idmap;
 5386:     foreach my $student (keys(%$classlist)) {
 5387: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
 5388: 	    $student;
 5389:     }
 5390:     return %idmap;
 5391: }
 5392: 
 5393: =pod
 5394: 
 5395: =item scantron_fixup_scanline
 5396: 
 5397:    Process a requested correction to a scanline.
 5398: 
 5399:   Arguments:
 5400:     $scantron_config   - hash from &get_scantron_config()
 5401:     $scan_data         - hash of correction information 
 5402:                           (see &scantron_getfile())
 5403:     $line              - existing scanline
 5404:     $whichline         - line number of the passed in scanline
 5405:     $field             - type of change to process 
 5406:                          (either 
 5407:                           'ID'     -> correct the student/employee ID
 5408:                           'CODE'   -> correct the CODE
 5409:                           'answer' -> fixup the submitted answers)
 5410:     
 5411:    $args               - hash of additional info,
 5412:                           - 'ID' 
 5413:                                'newid' -> studentID to use in replacement
 5414:                                           of existing one
 5415:                           - 'CODE' 
 5416:                                'CODE_ignore_dup' - set to true if duplicates
 5417:                                                    should be ignored.
 5418: 	                       'CODE' - is new code or 'use_unfound'
 5419:                                         if the existing unfound code should
 5420:                                         be used as is
 5421:                           - 'answer'
 5422:                                'response' - new answer or 'none' if blank
 5423:                                'question' - the bubble line to change
 5424:                                'questionnum' - the question identifier,
 5425:                                                may include subquestion. 
 5426: 
 5427:   Returns:
 5428:     $line - the modified scanline
 5429: 
 5430:   Side effects: 
 5431:     $scan_data - may be updated
 5432: 
 5433: =cut
 5434: 
 5435: 
 5436: sub scantron_fixup_scanline {
 5437:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 5438:     if ($field eq 'ID') {
 5439: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 5440: 	    return ($line,1,'New value too large');
 5441: 	}
 5442: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 5443: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 5444: 				     $args->{'newid'});
 5445: 	}
 5446: 	substr($line,$$scantron_config{'IDstart'}-1,
 5447: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 5448: 	if ($args->{'newid'}=~/^\s*$/) {
 5449: 	    &scan_data($scan_data,"$whichline.user",
 5450: 		       $args->{'username'}.':'.$args->{'domain'});
 5451: 	}
 5452:     } elsif ($field eq 'CODE') {
 5453: 	if ($args->{'CODE_ignore_dup'}) {
 5454: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 5455: 	}
 5456: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 5457: 	if ($args->{'CODE'} ne 'use_unfound') {
 5458: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 5459: 		return ($line,1,'New CODE value too large');
 5460: 	    }
 5461: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 5462: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 5463: 	    }
 5464: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 5465: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 5466: 	}
 5467:     } elsif ($field eq 'answer') {
 5468: 	my $length=$scantron_config->{'Qlength'};
 5469: 	my $off=$scantron_config->{'Qoff'};
 5470: 	my $on=$scantron_config->{'Qon'};
 5471: 	my $answer=${off}x$length;
 5472: 	if ($args->{'response'} eq 'none') {
 5473: 	    &scan_data($scan_data,
 5474: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 5475: 	} else {
 5476: 	    if ($on eq 'letter') {
 5477: 		my @alphabet=('A'..'Z');
 5478: 		$answer=$alphabet[$args->{'response'}];
 5479: 	    } elsif ($on eq 'number') {
 5480: 		$answer=$args->{'response'}+1;
 5481: 		if ($answer == 10) { $answer = '0'; }
 5482: 	    } else {
 5483: 		substr($answer,$args->{'response'},1)=$on;
 5484: 	    }
 5485: 	    &scan_data($scan_data,
 5486: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 5487: 	}
 5488: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 5489: 	substr($line,$where-1,$length)=$answer;
 5490:     }
 5491:     return $line;
 5492: }
 5493: 
 5494: =pod
 5495: 
 5496: =item scan_data
 5497: 
 5498:     Edit or look up  an item in the scan_data hash.
 5499: 
 5500:   Arguments:
 5501:     $scan_data  - The hash (see scantron_getfile)
 5502:     $key        - shorthand of the key to edit (actual key is
 5503:                   scantronfilename_key).
 5504:     $data        - New value of the hash entry.
 5505:     $delete      - If true, the entry is removed from the hash.
 5506: 
 5507:   Returns:
 5508:     The new value of the hash table field (undefined if deleted).
 5509: 
 5510: =cut
 5511: 
 5512: 
 5513: sub scan_data {
 5514:     my ($scan_data,$key,$value,$delete)=@_;
 5515:     my $filename=$env{'form.scantron_selectfile'};
 5516:     if (defined($value)) {
 5517: 	$scan_data->{$filename.'_'.$key} = $value;
 5518:     }
 5519:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 5520:     return $scan_data->{$filename.'_'.$key};
 5521: }
 5522: 
 5523: # ----- These first few routines are general use routines.----
 5524: 
 5525: # Return the number of occurences of a pattern in a string.
 5526: 
 5527: sub occurence_count {
 5528:     my ($string, $pattern) = @_;
 5529: 
 5530:     my @matches = ($string =~ /$pattern/g);
 5531: 
 5532:     return scalar(@matches);
 5533: }
 5534: 
 5535: 
 5536: # Take a string known to have digits and convert all the
 5537: # digits into letters in the range J,A..I.
 5538: 
 5539: sub digits_to_letters {
 5540:     my ($input) = @_;
 5541: 
 5542:     my @alphabet = ('J', 'A'..'I');
 5543: 
 5544:     my @input    = split(//, $input);
 5545:     my $output ='';
 5546:     for (my $i = 0; $i < scalar(@input); $i++) {
 5547: 	if ($input[$i] =~ /\d/) {
 5548: 	    $output .= $alphabet[$input[$i]];
 5549: 	} else {
 5550: 	    $output .= $input[$i];
 5551: 	}
 5552:     }
 5553:     return $output;
 5554: }
 5555: 
 5556: =pod 
 5557: 
 5558: =item scantron_parse_scanline
 5559: 
 5560:   Decodes a scanline from the selected scantron file
 5561: 
 5562:  Arguments:
 5563:     line             - The text of the scantron file line to process
 5564:     whichline        - Line number
 5565:     scantron_config  - Hash describing the format of the scantron lines.
 5566:     scan_data        - Hash of extra information about the scanline
 5567:                        (see scantron_getfile for more information)
 5568:     just_header      - True if should not process question answers but only
 5569:                        the stuff to the left of the answers.
 5570:  Returns:
 5571:    Hash containing the result of parsing the scanline
 5572: 
 5573:    Keys are all proceeded by the string 'scantron.'
 5574: 
 5575:        CODE    - the CODE in use for this scanline
 5576:        useCODE - 1 if the CODE is invalid but it usage has been forced
 5577:                  by the operator
 5578:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 5579:                             CODEs were selected, but the usage has been
 5580:                             forced by the operator
 5581:        ID  - student/employee ID
 5582:        PaperID - if used, the ID number printed on the sheet when the 
 5583:                  paper was scanned
 5584:        FirstName - first name from the sheet
 5585:        LastName  - last name from the sheet
 5586: 
 5587:      if just_header was not true these key may also exist
 5588: 
 5589:        missingerror - a list of bubble ranges that are considered to be answers
 5590:                       to a single question that don't have any bubbles filled in.
 5591:                       Of the form questionnumber:firstbubblenumber:count.
 5592:        doubleerror  - a list of bubble ranges that are considered to be answers
 5593:                       to a single question that have more than one bubble filled in.
 5594:                       Of the form questionnumber::firstbubblenumber:count
 5595:    
 5596:                 In the above, count is the number of bubble responses in the
 5597:                 input line needed to represent the possible answers to the question.
 5598:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 5599:                 per line would have count = 2.
 5600: 
 5601:        maxquest     - the number of the last bubble line that was parsed
 5602: 
 5603:        (<number> starts at 1)
 5604:        <number>.answer - zero or more letters representing the selected
 5605:                          letters from the scanline for the bubble line 
 5606:                          <number>.
 5607:                          if blank there was either no bubble or there where
 5608:                          multiple bubbles, (consult the keys missingerror and
 5609:                          doubleerror if this is an error condition)
 5610: 
 5611: =cut
 5612: 
 5613: sub scantron_parse_scanline {
 5614:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
 5615: 
 5616:     my %record;
 5617:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 5618:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 5619:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
 5620:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 5621: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 5622: 	if ($$scantron_config{'CODElocation'} < 0 ||
 5623: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 5624: 	    $$scantron_config{'CODElocation'} eq 'number') {
 5625: 	    $record{'scantron.CODE'}=substr($data,
 5626: 					    $$scantron_config{'CODEstart'}-1,
 5627: 					    $$scantron_config{'CODElength'});
 5628: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 5629: 		$record{'scantron.useCODE'}=1;
 5630: 	    }
 5631: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 5632: 		$record{'scantron.CODE_ignore_dup'}=1;
 5633: 	    }
 5634: 	} else {
 5635: 	    #FIXME interpret first N questions
 5636: 	}
 5637:     }
 5638:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 5639: 				  $$scantron_config{'IDlength'});
 5640:     $record{'scantron.PaperID'}=
 5641: 	substr($data,$$scantron_config{'PaperID'}-1,
 5642: 	       $$scantron_config{'PaperIDlength'});
 5643:     $record{'scantron.FirstName'}=
 5644: 	substr($data,$$scantron_config{'FirstName'}-1,
 5645: 	       $$scantron_config{'FirstNamelength'});
 5646:     $record{'scantron.LastName'}=
 5647: 	substr($data,$$scantron_config{'LastName'}-1,
 5648: 	       $$scantron_config{'LastNamelength'});
 5649:     if ($just_header) { return \%record; }
 5650: 
 5651:     my @alphabet=('A'..'Z');
 5652:     my $questnum=0;
 5653:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 5654: 
 5655:     chomp($questions);		# Get rid of any trailing \n.
 5656:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 5657:     while (length($questions)) {
 5658: 	my $answers_needed = $bubble_lines_per_response{$questnum};
 5659:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 5660:                              || 1;
 5661:         $questnum++;
 5662:         my $quest_id = $questnum;
 5663:         my $currentquest = substr($questions,0,$answer_length);
 5664:         $questions       = substr($questions,$answer_length);
 5665:         if (length($currentquest) < $answer_length) { next; }
 5666: 
 5667:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
 5668:             my $subquestnum = 1;
 5669:             my $subquestions = $currentquest;
 5670:             my @subanswers_needed = 
 5671:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
 5672:             foreach my $subans (@subanswers_needed) {
 5673:                 my $subans_length =
 5674:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 5675:                 my $currsubquest = substr($subquestions,0,$subans_length);
 5676:                 $subquestions   = substr($subquestions,$subans_length);
 5677:                 $quest_id = "$questnum.$subquestnum";
 5678:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 5679:                     ($$scantron_config{'Qon'} eq 'number')) {
 5680:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 5681:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 5682:                         \@alphabet,\%record,$scantron_config,$scan_data);
 5683:                 } else {
 5684:                     $ansnum = &scantron_validator_positional($ansnum,
 5685:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
 5686:                 }
 5687:                 $subquestnum ++;
 5688:             }
 5689:         } else {
 5690:             if (($$scantron_config{'Qon'} eq 'letter') ||
 5691:                 ($$scantron_config{'Qon'} eq 'number')) {
 5692:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 5693:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5694:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5695:             } else {
 5696:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 5697:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5698:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5699:             }
 5700:         }
 5701:     }
 5702:     $record{'scantron.maxquest'}=$questnum;
 5703:     return \%record;
 5704: }
 5705: 
 5706: sub scantron_validator_lettnum {
 5707:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 5708:         $alphabet,$record,$scantron_config,$scan_data) = @_;
 5709: 
 5710:     # Qon 'letter' implies for each slot in currquest we have:
 5711:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 5712:     #    about anything else (esp. a value of Qoff) for missing
 5713:     #    bubbles.
 5714:     #
 5715:     # Qon 'number' implies each slot gives a digit that indexes the
 5716:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 5717:     #    and * or ? for double bubbles on a single line.
 5718:     #
 5719: 
 5720:     my $matchon;
 5721:     if ($$scantron_config{'Qon'} eq 'letter') {
 5722:         $matchon = '[A-Z]';
 5723:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 5724:         $matchon = '\d';
 5725:     }
 5726:     my $occurrences = 0;
 5727:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5728:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5729:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5730:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5731:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5732:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5733:         my @singlelines = split('',$currquest);
 5734:         foreach my $entry (@singlelines) {
 5735:             $occurrences = &occurence_count($entry,$matchon);
 5736:             if ($occurrences > 1) {
 5737:                 last;
 5738:             }
 5739:         } 
 5740:     } else {
 5741:         $occurrences = &occurence_count($currquest,$matchon); 
 5742:     }
 5743:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 5744:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5745:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5746:             my $bubble = substr($currquest,$ans,1);
 5747:             if ($bubble =~ /$matchon/ ) {
 5748:                 if ($$scantron_config{'Qon'} eq 'number') {
 5749:                     if ($bubble == 0) {
 5750:                         $bubble = 10; 
 5751:                     }
 5752:                     $record->{"scantron.$ansnum.answer"} = 
 5753:                         $alphabet->[$bubble-1];
 5754:                 } else {
 5755:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 5756:                 }
 5757:             } else {
 5758:                 $record->{"scantron.$ansnum.answer"}='';
 5759:             }
 5760:             $ansnum++;
 5761:         }
 5762:     } elsif (!defined($currquest)
 5763:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 5764:             || (&occurence_count($currquest,$matchon) == 0)) {
 5765:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5766:             $record->{"scantron.$ansnum.answer"}='';
 5767:             $ansnum++;
 5768:         }
 5769:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5770:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 5771:         }
 5772:     } else {
 5773:         if ($$scantron_config{'Qon'} eq 'number') {
 5774:             $currquest = &digits_to_letters($currquest);            
 5775:         }
 5776:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5777:             my $bubble = substr($currquest,$ans,1);
 5778:             $record->{"scantron.$ansnum.answer"} = $bubble;
 5779:             $ansnum++;
 5780:         }
 5781:     }
 5782:     return $ansnum;
 5783: }
 5784: 
 5785: sub scantron_validator_positional {
 5786:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 5787:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
 5788: 
 5789:     # Otherwise there's a positional notation;
 5790:     # each bubble line requires Qlength items, and there are filled in
 5791:     # bubbles for each case where there 'Qon' characters.
 5792:     #
 5793: 
 5794:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 5795: 
 5796:     # If the split only gives us one element.. the full length of the
 5797:     # answer string, no bubbles are filled in:
 5798: 
 5799:     if ($answers_needed eq '') {
 5800:         return;
 5801:     }
 5802: 
 5803:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 5804:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5805:             $record->{"scantron.$ansnum.answer"}='';
 5806:             $ansnum++;
 5807:         }
 5808:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5809:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 5810:         }
 5811:     } elsif (scalar(@array) == 2) {
 5812:         my $location = length($array[0]);
 5813:         my $line_num = int($location / $$scantron_config{'Qlength'});
 5814:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 5815:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5816:             if ($ans eq $line_num) {
 5817:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 5818:             } else {
 5819:                 $record->{"scantron.$ansnum.answer"} = ' ';
 5820:             }
 5821:             $ansnum++;
 5822:          }
 5823:     } else {
 5824:         #  If there's more than one instance of a bubble character
 5825:         #  That's a double bubble; with positional notation we can
 5826:         #  record all the bubbles filled in as well as the
 5827:         #  fact this response consists of multiple bubbles.
 5828:         #
 5829:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5830:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5831:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5832:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5833:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5834:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5835:             my $doubleerror = 0;
 5836:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 5837:                    (!$doubleerror)) {
 5838:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 5839:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 5840:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 5841:                if (length(@currarray) > 2) {
 5842:                    $doubleerror = 1;
 5843:                } 
 5844:             }
 5845:             if ($doubleerror) {
 5846:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5847:             }
 5848:         } else {
 5849:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5850:         }
 5851:         my $item = $ansnum;
 5852:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5853:             $record->{"scantron.$item.answer"} = '';
 5854:             $item ++;
 5855:         }
 5856: 
 5857:         my @ans=@array;
 5858:         my $i=0;
 5859:         my $increment = 0;
 5860:         while ($#ans) {
 5861:             $i+=length($ans[0]) + $increment;
 5862:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 5863:             my $bubble = $i%$$scantron_config{'Qlength'};
 5864:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 5865:             shift(@ans);
 5866:             $increment = 1;
 5867:         }
 5868:         $ansnum += $answers_needed;
 5869:     }
 5870:     return $ansnum;
 5871: }
 5872: 
 5873: =pod
 5874: 
 5875: =item scantron_add_delay
 5876: 
 5877:    Adds an error message that occurred during the grading phase to a
 5878:    queue of messages to be shown after grading pass is complete
 5879: 
 5880:  Arguments:
 5881:    $delayqueue  - arrary ref of hash ref of error messages
 5882:    $scanline    - the scanline that caused the error
 5883:    $errormesage - the error message
 5884:    $errorcode   - a numeric code for the error
 5885: 
 5886:  Side Effects:
 5887:    updates the $delayqueue to have a new hash ref of the error
 5888: 
 5889: =cut
 5890: 
 5891: sub scantron_add_delay {
 5892:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 5893:     push(@$delayqueue,
 5894: 	 {'line' => $scanline, 'emsg' => $errormessage,
 5895: 	  'ecode' => $errorcode }
 5896: 	 );
 5897: }
 5898: 
 5899: =pod
 5900: 
 5901: =item scantron_find_student
 5902: 
 5903:    Finds the username for the current scanline
 5904: 
 5905:   Arguments:
 5906:    $scantron_record - hash result from scantron_parse_scanline
 5907:    $scan_data       - hash of correction information 
 5908:                       (see &scantron_getfile() form more information)
 5909:    $idmap           - hash from &username_to_idmap()
 5910:    $line            - number of current scanline
 5911:  
 5912:   Returns:
 5913:    Either 'username:domain' or undef if unknown
 5914: 
 5915: =cut
 5916: 
 5917: sub scantron_find_student {
 5918:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 5919:     my $scanID=$$scantron_record{'scantron.ID'};
 5920:     if ($scanID =~ /^\s*$/) {
 5921:  	return &scan_data($scan_data,"$line.user");
 5922:     }
 5923:     foreach my $id (keys(%$idmap)) {
 5924:  	if (lc($id) eq lc($scanID)) {
 5925:  	    return $$idmap{$id};
 5926:  	}
 5927:     }
 5928:     return undef;
 5929: }
 5930: 
 5931: =pod
 5932: 
 5933: =item scantron_filter
 5934: 
 5935:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 5936:    hidden resources was selected
 5937: 
 5938: =cut
 5939: 
 5940: sub scantron_filter {
 5941:     my ($curres)=@_;
 5942: 
 5943:     if (ref($curres) && $curres->is_problem()) {
 5944: 	# if the user has asked to not have either hidden
 5945: 	# or 'randomout' controlled resources to be graded
 5946: 	# don't include them
 5947: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 5948: 	    && $curres->randomout) {
 5949: 	    return 0;
 5950: 	}
 5951: 	return 1;
 5952:     }
 5953:     return 0;
 5954: }
 5955: 
 5956: =pod
 5957: 
 5958: =item scantron_process_corrections
 5959: 
 5960:    Gets correction information out of submitted form data and corrects
 5961:    the scanline
 5962: 
 5963: =cut
 5964: 
 5965: sub scantron_process_corrections {
 5966:     my ($r) = @_;
 5967:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 5968:     my ($scanlines,$scan_data)=&scantron_getfile();
 5969:     my $classlist=&Apache::loncoursedata::get_classlist();
 5970:     my $which=$env{'form.scantron_line'};
 5971:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 5972:     my ($skip,$err,$errmsg);
 5973:     if ($env{'form.scantron_skip_record'}) {
 5974: 	$skip=1;
 5975:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 5976: 	my $newstudent=$env{'form.scantron_username'}.':'.
 5977: 	    $env{'form.scantron_domain'};
 5978: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 5979: 	($line,$err,$errmsg)=
 5980: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 5981: 				     'ID',{'newid'=>$newid,
 5982: 				    'username'=>$env{'form.scantron_username'},
 5983: 				    'domain'=>$env{'form.scantron_domain'}});
 5984:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 5985: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 5986: 	my $newCODE;
 5987: 	my %args;
 5988: 	if      ($resolution eq 'use_unfound') {
 5989: 	    $newCODE='use_unfound';
 5990: 	} elsif ($resolution eq 'use_found') {
 5991: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 5992: 	} elsif ($resolution eq 'use_typed') {
 5993: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 5994: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 5995: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 5996: 	}
 5997: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 5998: 	    $args{'CODE_ignore_dup'}=1;
 5999: 	}
 6000: 	$args{'CODE'}=$newCODE;
 6001: 	($line,$err,$errmsg)=
 6002: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6003: 				     'CODE',\%args);
 6004:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 6005: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 6006: 	    ($line,$err,$errmsg)=
 6007: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 6008: 					 $which,'answer',
 6009: 					 { 'question'=>$question,
 6010: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 6011:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 6012: 	    if ($err) { last; }
 6013: 	}
 6014:     }
 6015:     if ($err) {
 6016: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
 6017:     } else {
 6018: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 6019: 	&scantron_putfile($scanlines,$scan_data);
 6020:     }
 6021: }
 6022: 
 6023: =pod
 6024: 
 6025: =item reset_skipping_status
 6026: 
 6027:    Forgets the current set of remember skipped scanlines (and thus
 6028:    reverts back to considering all lines in the
 6029:    scantron_skipped_<filename> file)
 6030: 
 6031: =cut
 6032: 
 6033: sub reset_skipping_status {
 6034:     my ($scanlines,$scan_data)=&scantron_getfile();
 6035:     &scan_data($scan_data,'remember_skipping',undef,1);
 6036:     &scantron_putfile(undef,$scan_data);
 6037: }
 6038: 
 6039: =pod
 6040: 
 6041: =item start_skipping
 6042: 
 6043:    Marks a scanline to be skipped. 
 6044: 
 6045: =cut
 6046: 
 6047: sub start_skipping {
 6048:     my ($scan_data,$i)=@_;
 6049:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6050:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 6051: 	$remembered{$i}=2;
 6052:     } else {
 6053: 	$remembered{$i}=1;
 6054:     }
 6055:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 6056: }
 6057: 
 6058: =pod
 6059: 
 6060: =item should_be_skipped
 6061: 
 6062:    Checks whether a scanline should be skipped.
 6063: 
 6064: =cut
 6065: 
 6066: sub should_be_skipped {
 6067:     my ($scanlines,$scan_data,$i)=@_;
 6068:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 6069: 	# not redoing old skips
 6070: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 6071: 	return 0;
 6072:     }
 6073:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6074: 
 6075:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 6076: 	return 0;
 6077:     }
 6078:     return 1;
 6079: }
 6080: 
 6081: =pod
 6082: 
 6083: =item remember_current_skipped
 6084: 
 6085:    Discovers what scanlines are in the scantron_skipped_<filename>
 6086:    file and remembers them into scan_data for later use.
 6087: 
 6088: =cut
 6089: 
 6090: sub remember_current_skipped {
 6091:     my ($scanlines,$scan_data)=&scantron_getfile();
 6092:     my %to_remember;
 6093:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6094: 	if ($scanlines->{'skipped'}[$i]) {
 6095: 	    $to_remember{$i}=1;
 6096: 	}
 6097:     }
 6098: 
 6099:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 6100:     &scantron_putfile(undef,$scan_data);
 6101: }
 6102: 
 6103: =pod
 6104: 
 6105: =item check_for_error
 6106: 
 6107:     Checks if there was an error when attempting to remove a specific
 6108:     scantron_.. bubble sheet data file. Prints out an error if
 6109:     something went wrong.
 6110: 
 6111: =cut
 6112: 
 6113: sub check_for_error {
 6114:     my ($r,$result)=@_;
 6115:     if ($result ne 'ok' && $result ne 'not_found' ) {
 6116: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 6117:     }
 6118: }
 6119: 
 6120: =pod
 6121: 
 6122: =item scantron_warning_screen
 6123: 
 6124:    Interstitial screen to make sure the operator has selected the
 6125:    correct options before we start the validation phase.
 6126: 
 6127: =cut
 6128: 
 6129: sub scantron_warning_screen {
 6130:     my ($button_text)=@_;
 6131:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 6132:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6133:     my $CODElist;
 6134:     if ($scantron_config{'CODElocation'} &&
 6135: 	$scantron_config{'CODEstart'} &&
 6136: 	$scantron_config{'CODElength'}) {
 6137: 	$CODElist=$env{'form.scantron_CODElist'};
 6138: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
 6139: 	$CODElist=
 6140: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 6141: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 6142:     }
 6143:     return ('
 6144: <p>
 6145: <span class="LC_warning">
 6146: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
 6147: </p>
 6148: <table>
 6149: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 6150: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 6151: '.$CODElist.'
 6152: </table>
 6153: <br />
 6154: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
 6155: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
 6156: 
 6157: <br />
 6158: ');
 6159: }
 6160: 
 6161: =pod
 6162: 
 6163: =item scantron_do_warning
 6164: 
 6165:    Check if the operator has picked something for all required
 6166:    fields. Error out if something is missing.
 6167: 
 6168: =cut
 6169: 
 6170: sub scantron_do_warning {
 6171:     my ($r,$symb)=@_;
 6172:     if (!$symb) {return '';}
 6173:     my $default_form_data=&defaultFormData($symb);
 6174:     $r->print(&scantron_form_start().$default_form_data);
 6175:     if ( $env{'form.selectpage'} eq '' ||
 6176: 	 $env{'form.scantron_selectfile'} eq '' ||
 6177: 	 $env{'form.scantron_format'} eq '' ) {
 6178: 	$r->print("<p>".&mt('You have forgetten to specify some information. Please go Back and try again.')."</p>");
 6179: 	if ( $env{'form.selectpage'} eq '') {
 6180: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 6181: 	} 
 6182: 	if ( $env{'form.scantron_selectfile'} eq '') {
 6183: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a file that contains the student\'s response data.').'</span></p>');
 6184: 	} 
 6185: 	if ( $env{'form.scantron_format'} eq '') {
 6186: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a the format of the student\'s response data.').'</span></p>');
 6187: 	} 
 6188:     } else {
 6189: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
 6190: 	$r->print('
 6191: '.$warning.'
 6192: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 6193: <input type="hidden" name="command" value="scantron_validate" />
 6194: ');
 6195:     }
 6196:     $r->print("</form><br />");
 6197:     return '';
 6198: }
 6199: 
 6200: =pod
 6201: 
 6202: =item scantron_form_start
 6203: 
 6204:     html hidden input for remembering all selected grading options
 6205: 
 6206: =cut
 6207: 
 6208: sub scantron_form_start {
 6209:     my ($max_bubble)=@_;
 6210:     my $result= <<SCANTRONFORM;
 6211: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 6212:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 6213:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 6214:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 6215:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 6216:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 6217:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 6218:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 6219:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 6220:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 6221: SCANTRONFORM
 6222: 
 6223:   my $line = 0;
 6224:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 6225:        my $chunk =
 6226: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 6227:        $chunk .=
 6228: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 6229:        $chunk .= 
 6230:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 6231:        $chunk .=
 6232:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 6233:        $result .= $chunk;
 6234:        $line++;
 6235:    }
 6236:     return $result;
 6237: }
 6238: 
 6239: =pod
 6240: 
 6241: =item scantron_validate_file
 6242: 
 6243:     Dispatch routine for doing validation of a bubble sheet data file.
 6244: 
 6245:     Also processes any necessary information resets that need to
 6246:     occur before validation begins (ignore previous corrections,
 6247:     restarting the skipped records processing)
 6248: 
 6249: =cut
 6250: 
 6251: sub scantron_validate_file {
 6252:     my ($r,$symb) = @_;
 6253:     if (!$symb) {return '';}
 6254:     my $default_form_data=&defaultFormData($symb);
 6255:     
 6256:     # do the detection of only doing skipped records first befroe we delete
 6257:     # them when doing the corrections reset
 6258:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 6259: 	&reset_skipping_status();
 6260:     }
 6261:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 6262: 	&remember_current_skipped();
 6263: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 6264:     }
 6265: 
 6266:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 6267: 	&check_for_error($r,&scantron_remove_file('corrected'));
 6268: 	&check_for_error($r,&scantron_remove_file('skipped'));
 6269: 	&check_for_error($r,&scantron_remove_scan_data());
 6270: 	$env{'form.scantron_options_ignore'}='done';
 6271:     }
 6272: 
 6273:     if ($env{'form.scantron_corrections'}) {
 6274: 	&scantron_process_corrections($r);
 6275:     }
 6276:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 6277:     #get the student pick code ready
 6278:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 6279:     my $nav_error;
 6280:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
 6281:     if ($nav_error) {
 6282:         $r->print(&navmap_errormsg());
 6283:         return '';
 6284:     }
 6285:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 6286:     $r->print($result);
 6287:     
 6288:     my @validate_phases=( 'sequence',
 6289: 			  'ID',
 6290: 			  'CODE',
 6291: 			  'doublebubble',
 6292: 			  'missingbubbles');
 6293:     if (!$env{'form.validatepass'}) {
 6294: 	$env{'form.validatepass'} = 0;
 6295:     }
 6296:     my $currentphase=$env{'form.validatepass'};
 6297: 
 6298: 
 6299:     my $stop=0;
 6300:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 6301: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 6302: 	$r->rflush();
 6303: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 6304: 	{
 6305: 	    no strict 'refs';
 6306: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 6307: 	}
 6308:     }
 6309:     if (!$stop) {
 6310: 	my $warning=&scantron_warning_screen('Start Grading');
 6311: 	$r->print(&mt('Validation process complete.').'<br />'.
 6312:                   $warning.
 6313:                   &mt('Perform verification for each student after storage of submissions?').
 6314:                   '&nbsp;<span class="LC_nobreak"><label>'.
 6315:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 6316:                   ('&nbsp;'x3).'<label>'.
 6317:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 6318:                   '</label></span><br />'.
 6319:                   &mt('Grading will take longer if you use verification.').'<br />'.
 6320:                   &mt("Alternatively, the 'Review bubblesheet data' utility (see grading menu) can be used for all students after grading is complete.").'<br /><br />'.
 6321:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 6322:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 6323:     } else {
 6324: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 6325: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 6326:     }
 6327:     if ($stop) {
 6328: 	if ($validate_phases[$currentphase] eq 'sequence') {
 6329: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 6330: 	    $r->print(' '.&mt('this error').' <br />');
 6331: 
 6332: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
 6333: 	} else {
 6334:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 6335: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 6336:             } else {
 6337:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 6338:             }
 6339: 	    $r->print(' '.&mt('using corrected info').' <br />');
 6340: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 6341: 	    $r->print(" ".&mt("this scanline saving it for later."));
 6342: 	}
 6343:     }
 6344:     $r->print(" </form><br />");
 6345:     return '';
 6346: }
 6347: 
 6348: 
 6349: =pod
 6350: 
 6351: =item scantron_remove_file
 6352: 
 6353:    Removes the requested bubble sheet data file, makes sure that
 6354:    scantron_original_<filename> is never removed
 6355: 
 6356: 
 6357: =cut
 6358: 
 6359: sub scantron_remove_file {
 6360:     my ($which)=@_;
 6361:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6362:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6363:     my $file='scantron_';
 6364:     if ($which eq 'corrected' || $which eq 'skipped') {
 6365: 	$file.=$which.'_';
 6366:     } else {
 6367: 	return 'refused';
 6368:     }
 6369:     $file.=$env{'form.scantron_selectfile'};
 6370:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 6371: }
 6372: 
 6373: 
 6374: =pod
 6375: 
 6376: =item scantron_remove_scan_data
 6377: 
 6378:    Removes all scan_data correction for the requested bubble sheet
 6379:    data file.  (In the case that both the are doing skipped records we need
 6380:    to remember the old skipped lines for the time being so that element
 6381:    persists for a while.)
 6382: 
 6383: =cut
 6384: 
 6385: sub scantron_remove_scan_data {
 6386:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6387:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6388:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 6389:     my @todelete;
 6390:     my $filename=$env{'form.scantron_selectfile'};
 6391:     foreach my $key (@keys) {
 6392: 	if ($key=~/^\Q$filename\E_/) {
 6393: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 6394: 		$key=~/remember_skipping/) {
 6395: 		next;
 6396: 	    }
 6397: 	    push(@todelete,$key);
 6398: 	}
 6399:     }
 6400:     my $result;
 6401:     if (@todelete) {
 6402: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 6403: 				       \@todelete,$cdom,$cname);
 6404:     } else {
 6405: 	$result = 'ok';
 6406:     }
 6407:     return $result;
 6408: }
 6409: 
 6410: 
 6411: =pod
 6412: 
 6413: =item scantron_getfile
 6414: 
 6415:     Fetches the requested bubble sheet data file (all 3 versions), and
 6416:     the scan_data hash
 6417:   
 6418:   Arguments:
 6419:     None
 6420: 
 6421:   Returns:
 6422:     2 hash references
 6423: 
 6424:      - first one has 
 6425:          orig      -
 6426:          corrected -
 6427:          skipped   -  each of which points to an array ref of the specified
 6428:                       file broken up into individual lines
 6429:          count     - number of scanlines
 6430:  
 6431:      - second is the scan_data hash possible keys are
 6432:        ($number refers to scanline numbered $number and thus the key affects
 6433:         only that scanline
 6434:         $bubline refers to the specific bubble line element and the aspects
 6435:         refers to that specific bubble line element)
 6436: 
 6437:        $number.user - username:domain to use
 6438:        $number.CODE_ignore_dup 
 6439:                     - ignore the duplicate CODE error 
 6440:        $number.useCODE
 6441:                     - use the CODE in the scanline as is
 6442:        $number.no_bubble.$bubline
 6443:                     - it is valid that there is no bubbled in bubble
 6444:                       at $number $bubline
 6445:        remember_skipping
 6446:                     - a frozen hash containing keys of $number and values
 6447:                       of either 
 6448:                         1 - we are on a 'do skipped records pass' and plan
 6449:                             on processing this line
 6450:                         2 - we are on a 'do skipped records pass' and this
 6451:                             scanline has been marked to skip yet again
 6452: 
 6453: =cut
 6454: 
 6455: sub scantron_getfile {
 6456:     #FIXME really would prefer a scantron directory
 6457:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6458:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6459:     my $lines;
 6460:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6461: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 6462:     my %scanlines;
 6463:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 6464:     my $temp=$scanlines{'orig'};
 6465:     $scanlines{'count'}=$#$temp;
 6466: 
 6467:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6468: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 6469:     if ($lines eq '-1') {
 6470: 	$scanlines{'corrected'}=[];
 6471:     } else {
 6472: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 6473:     }
 6474:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6475: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 6476:     if ($lines eq '-1') {
 6477: 	$scanlines{'skipped'}=[];
 6478:     } else {
 6479: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 6480:     }
 6481:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 6482:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 6483:     my %scan_data = @tmp;
 6484:     return (\%scanlines,\%scan_data);
 6485: }
 6486: 
 6487: =pod
 6488: 
 6489: =item lonnet_putfile
 6490: 
 6491:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 6492: 
 6493:  Arguments:
 6494:    $contents - data to store
 6495:    $filename - filename to store $contents into
 6496: 
 6497:  Returns:
 6498:    result value from &Apache::lonnet::finishuserfileupload
 6499: 
 6500: =cut
 6501: 
 6502: sub lonnet_putfile {
 6503:     my ($contents,$filename)=@_;
 6504:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6505:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6506:     $env{'form.sillywaytopassafilearound'}=$contents;
 6507:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 6508: 
 6509: }
 6510: 
 6511: =pod
 6512: 
 6513: =item scantron_putfile
 6514: 
 6515:     Stores the current version of the bubble sheet data files, and the
 6516:     scan_data hash. (Does not modify the original version only the
 6517:     corrected and skipped versions.
 6518: 
 6519:  Arguments:
 6520:     $scanlines - hash ref that looks like the first return value from
 6521:                  &scantron_getfile()
 6522:     $scan_data - hash ref that looks like the second return value from
 6523:                  &scantron_getfile()
 6524: 
 6525: =cut
 6526: 
 6527: sub scantron_putfile {
 6528:     my ($scanlines,$scan_data) = @_;
 6529:     #FIXME really would prefer a scantron directory
 6530:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6531:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6532:     if ($scanlines) {
 6533: 	my $prefix='scantron_';
 6534: # no need to update orig, shouldn't change
 6535: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 6536: #		    $env{'form.scantron_selectfile'});
 6537: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 6538: 			$prefix.'corrected_'.
 6539: 			$env{'form.scantron_selectfile'});
 6540: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 6541: 			$prefix.'skipped_'.
 6542: 			$env{'form.scantron_selectfile'});
 6543:     }
 6544:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 6545: }
 6546: 
 6547: =pod
 6548: 
 6549: =item scantron_get_line
 6550: 
 6551:    Returns the correct version of the scanline
 6552: 
 6553:  Arguments:
 6554:     $scanlines - hash ref that looks like the first return value from
 6555:                  &scantron_getfile()
 6556:     $scan_data - hash ref that looks like the second return value from
 6557:                  &scantron_getfile()
 6558:     $i         - number of the requested line (starts at 0)
 6559: 
 6560:  Returns:
 6561:    A scanline, (either the original or the corrected one if it
 6562:    exists), or undef if the requested scanline should be
 6563:    skipped. (Either because it's an skipped scanline, or it's an
 6564:    unskipped scanline and we are not doing a 'do skipped scanlines'
 6565:    pass.
 6566: 
 6567: =cut
 6568: 
 6569: sub scantron_get_line {
 6570:     my ($scanlines,$scan_data,$i)=@_;
 6571:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 6572:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 6573:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 6574:     return $scanlines->{'orig'}[$i]; 
 6575: }
 6576: 
 6577: =pod
 6578: 
 6579: =item scantron_todo_count
 6580: 
 6581:     Counts the number of scanlines that need processing.
 6582: 
 6583:  Arguments:
 6584:     $scanlines - hash ref that looks like the first return value from
 6585:                  &scantron_getfile()
 6586:     $scan_data - hash ref that looks like the second return value from
 6587:                  &scantron_getfile()
 6588: 
 6589:  Returns:
 6590:     $count - number of scanlines to process
 6591: 
 6592: =cut
 6593: 
 6594: sub get_todo_count {
 6595:     my ($scanlines,$scan_data)=@_;
 6596:     my $count=0;
 6597:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6598: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6599: 	if ($line=~/^[\s\cz]*$/) { next; }
 6600: 	$count++;
 6601:     }
 6602:     return $count;
 6603: }
 6604: 
 6605: =pod
 6606: 
 6607: =item scantron_put_line
 6608: 
 6609:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
 6610:     data file.
 6611: 
 6612:  Arguments:
 6613:     $scanlines - hash ref that looks like the first return value from
 6614:                  &scantron_getfile()
 6615:     $scan_data - hash ref that looks like the second return value from
 6616:                  &scantron_getfile()
 6617:     $i         - line number to update
 6618:     $newline   - contents of the updated scanline
 6619:     $skip      - if true make the line for skipping and update the
 6620:                  'skipped' file
 6621: 
 6622: =cut
 6623: 
 6624: sub scantron_put_line {
 6625:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 6626:     if ($skip) {
 6627: 	$scanlines->{'skipped'}[$i]=$newline;
 6628: 	&start_skipping($scan_data,$i);
 6629: 	return;
 6630:     }
 6631:     $scanlines->{'corrected'}[$i]=$newline;
 6632: }
 6633: 
 6634: =pod
 6635: 
 6636: =item scantron_clear_skip
 6637: 
 6638:    Remove a line from the 'skipped' file
 6639: 
 6640:  Arguments:
 6641:     $scanlines - hash ref that looks like the first return value from
 6642:                  &scantron_getfile()
 6643:     $scan_data - hash ref that looks like the second return value from
 6644:                  &scantron_getfile()
 6645:     $i         - line number to update
 6646: 
 6647: =cut
 6648: 
 6649: sub scantron_clear_skip {
 6650:     my ($scanlines,$scan_data,$i)=@_;
 6651:     if (exists($scanlines->{'skipped'}[$i])) {
 6652: 	undef($scanlines->{'skipped'}[$i]);
 6653: 	return 1;
 6654:     }
 6655:     return 0;
 6656: }
 6657: 
 6658: =pod
 6659: 
 6660: =item scantron_filter_not_exam
 6661: 
 6662:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 6663:    filter out resources that are not marked as 'exam' mode
 6664: 
 6665: =cut
 6666: 
 6667: sub scantron_filter_not_exam {
 6668:     my ($curres)=@_;
 6669:     
 6670:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 6671: 	# if the user has asked to not have either hidden
 6672: 	# or 'randomout' controlled resources to be graded
 6673: 	# don't include them
 6674: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6675: 	    && $curres->randomout) {
 6676: 	    return 0;
 6677: 	}
 6678: 	return 1;
 6679:     }
 6680:     return 0;
 6681: }
 6682: 
 6683: =pod
 6684: 
 6685: =item scantron_validate_sequence
 6686: 
 6687:     Validates the selected sequence, checking for resource that are
 6688:     not set to exam mode.
 6689: 
 6690: =cut
 6691: 
 6692: sub scantron_validate_sequence {
 6693:     my ($r,$currentphase) = @_;
 6694: 
 6695:     my $navmap=Apache::lonnavmaps::navmap->new();
 6696:     unless (ref($navmap)) {
 6697:         $r->print(&navmap_errormsg());
 6698:         return (1,$currentphase);
 6699:     }
 6700:     my (undef,undef,$sequence)=
 6701: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 6702: 
 6703:     my $map=$navmap->getResourceByUrl($sequence);
 6704: 
 6705:     $r->print('<input type="hidden" name="validate_sequence_exam"
 6706:                                     value="ignore" />');
 6707:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 6708: 	my @resources=
 6709: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 6710: 	if (@resources) {
 6711: 	    $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>");
 6712: 	    return (1,$currentphase);
 6713: 	}
 6714:     }
 6715: 
 6716:     return (0,$currentphase+1);
 6717: }
 6718: 
 6719: 
 6720: 
 6721: sub scantron_validate_ID {
 6722:     my ($r,$currentphase) = @_;
 6723:     
 6724:     #get student info
 6725:     my $classlist=&Apache::loncoursedata::get_classlist();
 6726:     my %idmap=&username_to_idmap($classlist);
 6727: 
 6728:     #get scantron line setup
 6729:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6730:     my ($scanlines,$scan_data)=&scantron_getfile();
 6731: 
 6732:     my $nav_error;
 6733:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble_lines.. array.
 6734:     if ($nav_error) {
 6735:         $r->print(&navmap_errormsg());
 6736:         return(1,$currentphase);
 6737:     }
 6738: 
 6739:     my %found=('ids'=>{},'usernames'=>{});
 6740:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6741: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6742: 	if ($line=~/^[\s\cz]*$/) { next; }
 6743: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 6744: 						 $scan_data);
 6745: 	my $id=$$scan_record{'scantron.ID'};
 6746: 	my $found;
 6747: 	foreach my $checkid (keys(%idmap)) {
 6748: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 6749: 	}
 6750: 	if ($found) {
 6751: 	    my $username=$idmap{$found};
 6752: 	    if ($found{'ids'}{$found}) {
 6753: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6754: 					 $line,'duplicateID',$found);
 6755: 		return(1,$currentphase);
 6756: 	    } elsif ($found{'usernames'}{$username}) {
 6757: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6758: 					 $line,'duplicateID',$username);
 6759: 		return(1,$currentphase);
 6760: 	    }
 6761: 	    #FIXME store away line we previously saw the ID on to use above
 6762: 	    $found{'ids'}{$found}++;
 6763: 	    $found{'usernames'}{$username}++;
 6764: 	} else {
 6765: 	    if ($id =~ /^\s*$/) {
 6766: 		my $username=&scan_data($scan_data,"$i.user");
 6767: 		if (defined($username) && $found{'usernames'}{$username}) {
 6768: 		    &scantron_get_correction($r,$i,$scan_record,
 6769: 					     \%scantron_config,
 6770: 					     $line,'duplicateID',$username);
 6771: 		    return(1,$currentphase);
 6772: 		} elsif (!defined($username)) {
 6773: 		    &scantron_get_correction($r,$i,$scan_record,
 6774: 					     \%scantron_config,
 6775: 					     $line,'incorrectID');
 6776: 		    return(1,$currentphase);
 6777: 		}
 6778: 		$found{'usernames'}{$username}++;
 6779: 	    } else {
 6780: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6781: 					 $line,'incorrectID');
 6782: 		return(1,$currentphase);
 6783: 	    }
 6784: 	}
 6785:     }
 6786: 
 6787:     return (0,$currentphase+1);
 6788: }
 6789: 
 6790: 
 6791: sub scantron_get_correction {
 6792:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
 6793: #FIXME in the case of a duplicated ID the previous line, probably need
 6794: #to show both the current line and the previous one and allow skipping
 6795: #the previous one or the current one
 6796: 
 6797:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 6798: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6799: 			    " for PaperID <tt>[_1]</tt>",
 6800: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
 6801:     } else {
 6802: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6803: 			    " in scanline [_1] <pre>[_2]</pre>",
 6804: 			    $i,$line)."</p> \n");
 6805:     }
 6806:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
 6807: 			  "The name on the paper is [_2],[_3]",
 6808: 			  $$scan_record{'scantron.ID'},
 6809: 			  $$scan_record{'scantron.LastName'},
 6810: 			  $$scan_record{'scantron.FirstName'})."</p>";
 6811: 
 6812:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 6813:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 6814:                            # Array populated for doublebubble or
 6815:     my @lines_to_correct;  # missingbubble errors to build javascript
 6816:                            # to validate radio button checking   
 6817: 
 6818:     if ($error =~ /ID$/) {
 6819: 	if ($error eq 'incorrectID') {
 6820: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
 6821: 		      "</p>\n");
 6822: 	} elsif ($error eq 'duplicateID') {
 6823: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 6824: 	}
 6825: 	$r->print($message);
 6826: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6827: 	$r->print("\n<ul><li> ");
 6828: 	#FIXME it would be nice if this sent back the user ID and
 6829: 	#could do partial userID matches
 6830: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 6831: 				       'scantron_username','scantron_domain'));
 6832: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 6833: 	$r->print("\n@".
 6834: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 6835: 
 6836: 	$r->print('</li>');
 6837:     } elsif ($error =~ /CODE$/) {
 6838: 	if ($error eq 'incorrectCODE') {
 6839: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 6840: 	} elsif ($error eq 'duplicateCODE') {
 6841: 	    $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");
 6842: 	}
 6843: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
 6844: 			    $$scan_record{'scantron.CODE'})."<br />\n");
 6845: 	$r->print($message);
 6846: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6847: 	$r->print("\n<br /> ");
 6848: 	my $i=0;
 6849: 	if ($error eq 'incorrectCODE' 
 6850: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 6851: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 6852: 	    if ($closest > 0) {
 6853: 		foreach my $testcode (@{$closest}) {
 6854: 		    my $checked='';
 6855: 		    if (!$i) { $checked=' checked="checked"'; }
 6856: 		    $r->print("
 6857:    <label>
 6858:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
 6859:        ".&mt("Use the similar CODE [_1] instead.",
 6860: 	    "<b><tt>".$testcode."</tt></b>")."
 6861:     </label>
 6862:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 6863: 		    $r->print("\n<br />");
 6864: 		    $i++;
 6865: 		}
 6866: 	    }
 6867: 	}
 6868: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 6869: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
 6870: 	    $r->print("
 6871:     <label>
 6872:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
 6873:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
 6874: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 6875:     </label>");
 6876: 	    $r->print("\n<br />");
 6877: 	}
 6878: 
 6879: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
 6880: function change_radio(field) {
 6881:     var slct=document.scantronupload.scantron_CODE_resolution;
 6882:     var i;
 6883:     for (i=0;i<slct.length;i++) {
 6884:         if (slct[i].value==field) { slct[i].checked=true; }
 6885:     }
 6886: }
 6887: ENDSCRIPT
 6888: 	my $href="/adm/pickcode?".
 6889: 	   "form=".&escape("scantronupload").
 6890: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 6891: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 6892: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 6893: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 6894: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 6895: 	    $r->print("
 6896:     <label>
 6897:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 6898:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 6899: 	     "<a target='_blank' href='$href'>","</a>")."
 6900:     </label> 
 6901:     ".&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\')" />'));
 6902: 	    $r->print("\n<br />");
 6903: 	}
 6904: 	$r->print("
 6905:     <label>
 6906:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 6907:        ".&mt("Use [_1] as the CODE.",
 6908: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 6909: 	$r->print("\n<br /><br />");
 6910:     } elsif ($error eq 'doublebubble') {
 6911: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 6912: 
 6913: 	# The form field scantron_questions is acutally a list of line numbers.
 6914: 	# represented by this form so:
 6915: 
 6916: 	my $line_list = &questions_to_line_list($arg);
 6917: 
 6918: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 6919: 		  $line_list.'" />');
 6920: 	$r->print($message);
 6921: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 6922: 	foreach my $question (@{$arg}) {
 6923: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 6924:                                                    $scan_record, $error);
 6925:             push(@lines_to_correct,@linenums);
 6926: 	}
 6927:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 6928:     } elsif ($error eq 'missingbubble') {
 6929: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
 6930: 	$r->print($message);
 6931: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 6932: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 6933: 
 6934: 	# The form field scantron_questions is actually a list of line numbers not
 6935: 	# a list of question numbers. Therefore:
 6936: 	#
 6937: 	
 6938: 	my $line_list = &questions_to_line_list($arg);
 6939: 
 6940: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 6941: 		  $line_list.'" />');
 6942: 	foreach my $question (@{$arg}) {
 6943: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 6944:                                                    $scan_record, $error);
 6945:             push(@lines_to_correct,@linenums);
 6946: 	}
 6947:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 6948:     } else {
 6949: 	$r->print("\n<ul>");
 6950:     }
 6951:     $r->print("\n</li></ul>");
 6952: }
 6953: 
 6954: sub verify_bubbles_checked {
 6955:     my (@ansnums) = @_;
 6956:     my $ansnumstr = join('","',@ansnums);
 6957:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 6958:     my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
 6959: function verify_bubble_radio(form) {
 6960:     var ansnumArray = new Array ("$ansnumstr");
 6961:     var need_bubble_count = 0;
 6962:     for (var i=0; i<ansnumArray.length; i++) {
 6963:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 6964:             var bubble_picked = 0; 
 6965:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 6966:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 6967:                     bubble_picked = 1;
 6968:                 }
 6969:             }
 6970:             if (bubble_picked == 0) {
 6971:                 need_bubble_count ++;
 6972:             }
 6973:         }
 6974:     }
 6975:     if (need_bubble_count) {
 6976:         alert("$warning");
 6977:         return;
 6978:     }
 6979:     form.submit(); 
 6980: }
 6981: ENDSCRIPT
 6982:     return $output;
 6983: }
 6984: 
 6985: =pod
 6986: 
 6987: =item  questions_to_line_list
 6988: 
 6989: Converts a list of questions into a string of comma separated
 6990: line numbers in the answer sheet used by the questions.  This is
 6991: used to fill in the scantron_questions form field.
 6992: 
 6993:   Arguments:
 6994:      questions    - Reference to an array of questions.
 6995: 
 6996: =cut
 6997: 
 6998: 
 6999: sub questions_to_line_list {
 7000:     my ($questions) = @_;
 7001:     my @lines;
 7002: 
 7003:     foreach my $item (@{$questions}) {
 7004:         my $question = $item;
 7005:         my ($first,$count,$last);
 7006:         if ($item =~ /^(\d+)\.(\d+)$/) {
 7007:             $question = $1;
 7008:             my $subquestion = $2;
 7009:             $first = $first_bubble_line{$question-1} + 1;
 7010:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7011:             my $subcount = 1;
 7012:             while ($subcount<$subquestion) {
 7013:                 $first += $subans[$subcount-1];
 7014:                 $subcount ++;
 7015:             }
 7016:             $count = $subans[$subquestion-1];
 7017:         } else {
 7018: 	    $first   = $first_bubble_line{$question-1} + 1;
 7019: 	    $count   = $bubble_lines_per_response{$question-1};
 7020:         }
 7021:         $last = $first+$count-1;
 7022:         push(@lines, ($first..$last));
 7023:     }
 7024:     return join(',', @lines);
 7025: }
 7026: 
 7027: =pod 
 7028: 
 7029: =item prompt_for_corrections
 7030: 
 7031: Prompts for a potentially multiline correction to the
 7032: user's bubbling (factors out common code from scantron_get_correction
 7033: for multi and missing bubble cases).
 7034: 
 7035:  Arguments:
 7036:    $r           - Apache request object.
 7037:    $question    - The question number to prompt for.
 7038:    $scan_config - The scantron file configuration hash.
 7039:    $scan_record - Reference to the hash that has the the parsed scanlines.
 7040:    $error       - Type of error
 7041: 
 7042:  Implicit inputs:
 7043:    %bubble_lines_per_response   - Starting line numbers for each question.
 7044:                                   Numbered from 0 (but question numbers are from
 7045:                                   1.
 7046:    %first_bubble_line           - Starting bubble line for each question.
 7047:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 7048:                                   type problems render as separate sub-questions, 
 7049:                                   in exam mode. This hash contains a 
 7050:                                   comma-separated list of the lines per 
 7051:                                   sub-question.
 7052:    %responsetype_per_response   - essayresponse, formularesponse,
 7053:                                   stringresponse, imageresponse, reactionresponse,
 7054:                                   and organicresponse type problem parts can have
 7055:                                   multiple lines per response if the weight
 7056:                                   assigned exceeds 10.  In this case, only
 7057:                                   one bubble per line is permitted, but more 
 7058:                                   than one line might contain bubbles, e.g.
 7059:                                   bubbling of: line 1 - J, line 2 - J, 
 7060:                                   line 3 - B would assign 22 points.  
 7061: 
 7062: =cut
 7063: 
 7064: sub prompt_for_corrections {
 7065:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
 7066:     my ($current_line,$lines);
 7067:     my @linenums;
 7068:     my $questionnum = $question;
 7069:     if ($question =~ /^(\d+)\.(\d+)$/) {
 7070:         $question = $1;
 7071:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7072:         my $subquestion = $2;
 7073:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7074:         my $subcount = 1;
 7075:         while ($subcount<$subquestion) {
 7076:             $current_line += $subans[$subcount-1];
 7077:             $subcount ++;
 7078:         }
 7079:         $lines = $subans[$subquestion-1];
 7080:     } else {
 7081:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7082:         $lines        = $bubble_lines_per_response{$question-1};
 7083:     }
 7084:     if ($lines > 1) {
 7085:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 7086:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
 7087:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
 7088:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
 7089:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
 7090:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
 7091:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
 7092:             $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 />');
 7093:         } else {
 7094:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 7095:         }
 7096:     }
 7097:     for (my $i =0; $i < $lines; $i++) {
 7098:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 7099: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
 7100: 	        		  $questionnum,$error,split('', $selected));
 7101:         push(@linenums,$current_line);
 7102: 	$current_line++;
 7103:     }
 7104:     if ($lines > 1) {
 7105: 	$r->print("<hr /><br />");
 7106:     }
 7107:     return @linenums;
 7108: }
 7109: 
 7110: =pod
 7111: 
 7112: =item scantron_bubble_selector
 7113:   
 7114:    Generates the html radiobuttons to correct a single bubble line
 7115:    possibly showing the existing the selected bubbles if known
 7116: 
 7117:  Arguments:
 7118:     $r           - Apache request object
 7119:     $scan_config - hash from &get_scantron_config()
 7120:     $line        - Number of the line being displayed.
 7121:     $questionnum - Question number (may include subquestion)
 7122:     $error       - Type of error.
 7123:     @selected    - Array of bubbles picked on this line.
 7124: 
 7125: =cut
 7126: 
 7127: sub scantron_bubble_selector {
 7128:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 7129:     my $max=$$scan_config{'Qlength'};
 7130: 
 7131:     my $scmode=$$scan_config{'Qon'};
 7132:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
 7133: 
 7134:     my @alphabet=('A'..'Z');
 7135:     $r->print(&Apache::loncommon::start_data_table().
 7136:               &Apache::loncommon::start_data_table_row());
 7137:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 7138:     for (my $i=0;$i<$max+1;$i++) {
 7139: 	$r->print("\n".'<td align="center">');
 7140: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 7141: 	else { $r->print('&nbsp;'); }
 7142: 	$r->print('</td>');
 7143:     }
 7144:     $r->print(&Apache::loncommon::end_data_table_row().
 7145:               &Apache::loncommon::start_data_table_row());
 7146:     for (my $i=0;$i<$max;$i++) {
 7147: 	$r->print("\n".
 7148: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 7149: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 7150:     }
 7151:     my $nobub_checked = ' ';
 7152:     if ($error eq 'missingbubble') {
 7153:         $nobub_checked = ' checked = "checked" ';
 7154:     }
 7155:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 7156: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 7157:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 7158:               $line.'" value="'.$questionnum.'" /></td>');
 7159:     $r->print(&Apache::loncommon::end_data_table_row().
 7160:               &Apache::loncommon::end_data_table());
 7161: }
 7162: 
 7163: =pod
 7164: 
 7165: =item num_matches
 7166: 
 7167:    Counts the number of characters that are the same between the two arguments.
 7168: 
 7169:  Arguments:
 7170:    $orig - CODE from the scanline
 7171:    $code - CODE to match against
 7172: 
 7173:  Returns:
 7174:    $count - integer count of the number of same characters between the
 7175:             two arguments
 7176: 
 7177: =cut
 7178: 
 7179: sub num_matches {
 7180:     my ($orig,$code) = @_;
 7181:     my @code=split(//,$code);
 7182:     my @orig=split(//,$orig);
 7183:     my $same=0;
 7184:     for (my $i=0;$i<scalar(@code);$i++) {
 7185: 	if ($code[$i] eq $orig[$i]) { $same++; }
 7186:     }
 7187:     return $same;
 7188: }
 7189: 
 7190: =pod
 7191: 
 7192: =item scantron_get_closely_matching_CODEs
 7193: 
 7194:    Cycles through all CODEs and finds the set that has the greatest
 7195:    number of same characters as the provided CODE
 7196: 
 7197:  Arguments:
 7198:    $allcodes - hash ref returned by &get_codes()
 7199:    $CODE     - CODE from the current scanline
 7200: 
 7201:  Returns:
 7202:    2 element list
 7203:     - first elements is number of how closely matching the best fit is 
 7204:       (5 means best set has 5 matching characters)
 7205:     - second element is an arrary ref containing the set of valid CODEs
 7206:       that best fit the passed in CODE
 7207: 
 7208: =cut
 7209: 
 7210: sub scantron_get_closely_matching_CODEs {
 7211:     my ($allcodes,$CODE)=@_;
 7212:     my @CODEs;
 7213:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 7214: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 7215:     }
 7216: 
 7217:     return ($#CODEs,$CODEs[-1]);
 7218: }
 7219: 
 7220: =pod
 7221: 
 7222: =item get_codes
 7223: 
 7224:    Builds a hash which has keys of all of the valid CODEs from the selected
 7225:    set of remembered CODEs.
 7226: 
 7227:  Arguments:
 7228:   $old_name - name of the set of remembered CODEs
 7229:   $cdom     - domain of the course
 7230:   $cnum     - internal course name
 7231: 
 7232:  Returns:
 7233:   %allcodes - keys are the valid CODEs, values are all 1
 7234: 
 7235: =cut
 7236: 
 7237: sub get_codes {
 7238:     my ($old_name, $cdom, $cnum) = @_;
 7239:     if (!$old_name) {
 7240: 	$old_name=$env{'form.scantron_CODElist'};
 7241:     }
 7242:     if (!$cdom) {
 7243: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 7244:     }
 7245:     if (!$cnum) {
 7246: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 7247:     }
 7248:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 7249: 				    $cdom,$cnum);
 7250:     my %allcodes;
 7251:     if ($result{"type\0$old_name"} eq 'number') {
 7252: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 7253:     } else {
 7254: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 7255:     }
 7256:     return %allcodes;
 7257: }
 7258: 
 7259: =pod
 7260: 
 7261: =item scantron_validate_CODE
 7262: 
 7263:    Validates all scanlines in the selected file to not have any
 7264:    invalid or underspecified CODEs and that none of the codes are
 7265:    duplicated if this was requested.
 7266: 
 7267: =cut
 7268: 
 7269: sub scantron_validate_CODE {
 7270:     my ($r,$currentphase) = @_;
 7271:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7272:     if ($scantron_config{'CODElocation'} &&
 7273: 	$scantron_config{'CODEstart'} &&
 7274: 	$scantron_config{'CODElength'}) {
 7275: 	if (!defined($env{'form.scantron_CODElist'})) {
 7276: 	    &FIXME_blow_up()
 7277: 	}
 7278:     } else {
 7279: 	return (0,$currentphase+1);
 7280:     }
 7281:     
 7282:     my %usedCODEs;
 7283: 
 7284:     my %allcodes=&get_codes();
 7285: 
 7286:     my $nav_error;
 7287:     &scantron_get_maxbubble(\$nav_error); # parse needs the lines per response array.
 7288:     if ($nav_error) {
 7289:         $r->print(&navmap_errormsg());
 7290:         return(1,$currentphase);
 7291:     }
 7292: 
 7293:     my ($scanlines,$scan_data)=&scantron_getfile();
 7294:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7295: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7296: 	if ($line=~/^[\s\cz]*$/) { next; }
 7297: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7298: 						 $scan_data);
 7299: 	my $CODE=$$scan_record{'scantron.CODE'};
 7300: 	my $error=0;
 7301: 	if (!&Apache::lonnet::validCODE($CODE)) {
 7302: 	    &scantron_get_correction($r,$i,$scan_record,
 7303: 				     \%scantron_config,
 7304: 				     $line,'incorrectCODE',\%allcodes);
 7305: 	    return(1,$currentphase);
 7306: 	}
 7307: 	if (%allcodes && !exists($allcodes{$CODE}) 
 7308: 	    && !$$scan_record{'scantron.useCODE'}) {
 7309: 	    &scantron_get_correction($r,$i,$scan_record,
 7310: 				     \%scantron_config,
 7311: 				     $line,'incorrectCODE',\%allcodes);
 7312: 	    return(1,$currentphase);
 7313: 	}
 7314: 	if (exists($usedCODEs{$CODE}) 
 7315: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 7316: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 7317: 	    &scantron_get_correction($r,$i,$scan_record,
 7318: 				     \%scantron_config,
 7319: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 7320: 	    return(1,$currentphase);
 7321: 	}
 7322: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 7323:     }
 7324:     return (0,$currentphase+1);
 7325: }
 7326: 
 7327: =pod
 7328: 
 7329: =item scantron_validate_doublebubble
 7330: 
 7331:    Validates all scanlines in the selected file to not have any
 7332:    bubble lines with multiple bubbles marked.
 7333: 
 7334: =cut
 7335: 
 7336: sub scantron_validate_doublebubble {
 7337:     my ($r,$currentphase) = @_;
 7338:     #get student info
 7339:     my $classlist=&Apache::loncoursedata::get_classlist();
 7340:     my %idmap=&username_to_idmap($classlist);
 7341: 
 7342:     #get scantron line setup
 7343:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7344:     my ($scanlines,$scan_data)=&scantron_getfile();
 7345:     my $nav_error;
 7346:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble line array.
 7347:     if ($nav_error) {
 7348:         $r->print(&navmap_errormsg());
 7349:         return(1,$currentphase);
 7350:     }
 7351: 
 7352:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7353: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7354: 	if ($line=~/^[\s\cz]*$/) { next; }
 7355: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7356: 						 $scan_data);
 7357: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 7358: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 7359: 				 'doublebubble',
 7360: 				 $$scan_record{'scantron.doubleerror'});
 7361:     	return (1,$currentphase);
 7362:     }
 7363:     return (0,$currentphase+1);
 7364: }
 7365: 
 7366: 
 7367: sub scantron_get_maxbubble {
 7368:     my ($nav_error) = @_;
 7369:     if (defined($env{'form.scantron_maxbubble'}) &&
 7370: 	$env{'form.scantron_maxbubble'}) {
 7371: 	&restore_bubble_lines();
 7372: 	return $env{'form.scantron_maxbubble'};
 7373:     }
 7374: 
 7375:     my (undef, undef, $sequence) =
 7376: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7377: 
 7378:     my $navmap=Apache::lonnavmaps::navmap->new();
 7379:     unless (ref($navmap)) {
 7380:         if (ref($nav_error)) {
 7381:             $$nav_error = 1;
 7382:         }
 7383:         return;
 7384:     }
 7385:     my $map=$navmap->getResourceByUrl($sequence);
 7386:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7387: 
 7388:     &Apache::lonxml::clear_problem_counter();
 7389: 
 7390:     my $uname       = $env{'user.name'};
 7391:     my $udom        = $env{'user.domain'};
 7392:     my $cid         = $env{'request.course.id'};
 7393:     my $total_lines = 0;
 7394:     %bubble_lines_per_response = ();
 7395:     %first_bubble_line         = ();
 7396:     %subdivided_bubble_lines   = ();
 7397:     %responsetype_per_response = ();
 7398: 
 7399:     my $response_number = 0;
 7400:     my $bubble_line     = 0;
 7401:     foreach my $resource (@resources) {
 7402:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom);
 7403:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 7404: 	    foreach my $part_id (@{$parts}) {
 7405:                 my $lines;
 7406: 
 7407: 	        # TODO - make this a persistent hash not an array.
 7408: 
 7409:                 # optionresponse, matchresponse and rankresponse type items 
 7410:                 # render as separate sub-questions in exam mode.
 7411:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 7412:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 7413:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 7414:                     my ($numbub,$numshown);
 7415:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 7416:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 7417:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 7418:                         }
 7419:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 7420:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 7421:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 7422:                         }
 7423:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 7424:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 7425:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 7426:                         }
 7427:                     }
 7428:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 7429:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 7430:                     }
 7431:                     my $bubbles_per_line = 10;
 7432:                     my $inner_bubble_lines = int($numbub/$bubbles_per_line);
 7433:                     if (($numbub % $bubbles_per_line) != 0) {
 7434:                         $inner_bubble_lines++;
 7435:                     }
 7436:                     for (my $i=0; $i<$numshown; $i++) {
 7437:                         $subdivided_bubble_lines{$response_number} .= 
 7438:                             $inner_bubble_lines.',';
 7439:                     }
 7440:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 7441:                     $lines = $numshown * $inner_bubble_lines;
 7442:                 } else {
 7443:                     $lines = $analysis->{"$part_id.bubble_lines"};
 7444:                 } 
 7445: 
 7446:                 $first_bubble_line{$response_number} = $bubble_line;
 7447: 	        $bubble_lines_per_response{$response_number} = $lines;
 7448:                 $responsetype_per_response{$response_number} = 
 7449:                     $analysis->{$part_id.'.type'};
 7450: 	        $response_number++;
 7451: 
 7452: 	        $bubble_line +=  $lines;
 7453: 	        $total_lines +=  $lines;
 7454: 	    }
 7455:         }
 7456:     }
 7457:     &Apache::lonnet::delenv('scantron.');
 7458: 
 7459:     &save_bubble_lines();
 7460:     $env{'form.scantron_maxbubble'} =
 7461: 	$total_lines;
 7462:     return $env{'form.scantron_maxbubble'};
 7463: }
 7464: 
 7465: sub scantron_validate_missingbubbles {
 7466:     my ($r,$currentphase) = @_;
 7467:     #get student info
 7468:     my $classlist=&Apache::loncoursedata::get_classlist();
 7469:     my %idmap=&username_to_idmap($classlist);
 7470: 
 7471:     #get scantron line setup
 7472:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7473:     my ($scanlines,$scan_data)=&scantron_getfile();
 7474:     my $nav_error;
 7475:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
 7476:     if ($nav_error) {
 7477:         return(1,$currentphase);
 7478:     }
 7479:     if (!$max_bubble) { $max_bubble=2**31; }
 7480:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7481: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7482: 	if ($line=~/^[\s\cz]*$/) { next; }
 7483: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7484: 						 $scan_data);
 7485: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 7486: 	my @to_correct;
 7487: 	
 7488: 	# Probably here's where the error is...
 7489: 
 7490: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 7491:             my $lastbubble;
 7492:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 7493:                my $question = $1;
 7494:                my $subquestion = $2;
 7495:                if (!defined($first_bubble_line{$question -1})) { next; }
 7496:                my $first = $first_bubble_line{$question-1};
 7497:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7498:                my $subcount = 1;
 7499:                while ($subcount<$subquestion) {
 7500:                    $first += $subans[$subcount-1];
 7501:                    $subcount ++;
 7502:                }
 7503:                my $count = $subans[$subquestion-1];
 7504:                $lastbubble = $first + $count;
 7505:             } else {
 7506:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
 7507:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
 7508:             }
 7509:             if ($lastbubble > $max_bubble) { next; }
 7510: 	    push(@to_correct,$missing);
 7511: 	}
 7512: 	if (@to_correct) {
 7513: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7514: 				     $line,'missingbubble',\@to_correct);
 7515: 	    return (1,$currentphase);
 7516: 	}
 7517: 
 7518:     }
 7519:     return (0,$currentphase+1);
 7520: }
 7521: 
 7522: 
 7523: sub scantron_process_students {
 7524:     my ($r,$symb) = @_;
 7525: 
 7526:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7527:     if (!$symb) {
 7528: 	return '';
 7529:     }
 7530:     my $default_form_data=&defaultFormData($symb);
 7531: 
 7532:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7533:     my ($scanlines,$scan_data)=&scantron_getfile();
 7534:     my $classlist=&Apache::loncoursedata::get_classlist();
 7535:     my %idmap=&username_to_idmap($classlist);
 7536:     my $navmap=Apache::lonnavmaps::navmap->new();
 7537:     unless (ref($navmap)) {
 7538:         $r->print(&navmap_errormsg());
 7539:         return '';
 7540:     }  
 7541:     my $map=$navmap->getResourceByUrl($sequence);
 7542:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7543:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
 7544:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 7545:                             \%grader_randomlists_by_symb);
 7546:     my $resource_error;
 7547:     foreach my $resource (@resources) {
 7548:         my $ressymb;
 7549:         if (ref($resource)) {
 7550:             $ressymb = $resource->symb();
 7551:         } else {
 7552:             $resource_error = 1;
 7553:             last;
 7554:         }
 7555:         my ($analysis,$parts) =
 7556:             &scantron_partids_tograde($resource,$env{'request.course.id'},
 7557:                                       $env{'user.name'},$env{'user.domain'},1);
 7558:         $grader_partids_by_symb{$ressymb} = $parts;
 7559:         if (ref($analysis) eq 'HASH') {
 7560:             if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 7561:                 $grader_randomlists_by_symb{$ressymb} = 
 7562:                     $analysis->{'parts_withrandomlist'};
 7563:             }
 7564:         }
 7565:     }
 7566:     if ($resource_error) {
 7567:         $r->print(&navmap_errormsg());
 7568:         return '';
 7569:     }
 7570: 
 7571:     my ($uname,$udom);
 7572:     my $result= <<SCANTRONFORM;
 7573: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 7574:   <input type="hidden" name="command" value="scantron_configphase" />
 7575:   $default_form_data
 7576: SCANTRONFORM
 7577:     $r->print($result);
 7578: 
 7579:     my @delayqueue;
 7580:     my (%completedstudents,%scandata);
 7581:     
 7582:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 7583:     my $count=&get_todo_count($scanlines,$scan_data);
 7584:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet Status',
 7585:  				    'Bubblesheet Progress',$count,
 7586: 				    'inline',undef,'scantronupload');
 7587:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 7588: 					  'Processing first student');
 7589:     $r->print('<br />');
 7590:     my $start=&Time::HiRes::time();
 7591:     my $i=-1;
 7592:     my $started;
 7593: 
 7594:     my $nav_error;
 7595:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
 7596:     if ($nav_error) {
 7597:         $r->print(&navmap_errormsg());
 7598:         return '';
 7599:     }
 7600: 
 7601:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 7602:     # the user and return.
 7603: 
 7604:     if ($ssi_error) {
 7605: 	$r->print("</form>");
 7606: 	&ssi_print_error($r);
 7607:         &Apache::lonnet::remove_lock($lock);
 7608: 	return '';		# Dunno why the other returns return '' rather than just returning.
 7609:     }
 7610: 
 7611:     my %lettdig = &letter_to_digits();
 7612:     my $numletts = scalar(keys(%lettdig));
 7613: 
 7614:     while ($i<$scanlines->{'count'}) {
 7615:  	($uname,$udom)=('','');
 7616:  	$i++;
 7617:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7618:  	if ($line=~/^[\s\cz]*$/) { next; }
 7619: 	if ($started) {
 7620: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 7621: 						     'last student');
 7622: 	}
 7623: 	$started=1;
 7624:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7625:  						 $scan_data);
 7626:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 7627:  					      \%idmap,$i)) {
 7628:   	    &scantron_add_delay(\@delayqueue,$line,
 7629:  				'Unable to find a student that matches',1);
 7630:  	    next;
 7631:   	}
 7632:  	if (exists $completedstudents{$uname}) {
 7633:  	    &scantron_add_delay(\@delayqueue,$line,
 7634:  				'Student '.$uname.' has multiple sheets',2);
 7635:  	    next;
 7636:  	}
 7637:   	($uname,$udom)=split(/:/,$uname);
 7638: 
 7639:         my (%partids_by_symb,$res_error);
 7640:         foreach my $resource (@resources) {
 7641:             my $ressymb;
 7642:             if (ref($resource)) {
 7643:                 $ressymb = $resource->symb();
 7644:             } else {
 7645:                 $res_error = 1;
 7646:                 last;
 7647:             }
 7648:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 7649:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 7650:                 my ($analysis,$parts) =
 7651:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom);
 7652:                 $partids_by_symb{$ressymb} = $parts;
 7653:             } else {
 7654:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
 7655:             }
 7656:         }
 7657: 
 7658:         if ($res_error) {
 7659:             &scantron_add_delay(\@delayqueue,$line,
 7660:                                 'An error occurred while grading student '.$uname,2);
 7661:             next;
 7662:         }
 7663: 
 7664: 	&Apache::lonxml::clear_problem_counter();
 7665:   	&Apache::lonnet::appenv($scan_record);
 7666: 
 7667: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 7668: 	    &scantron_putfile($scanlines,$scan_data);
 7669: 	}
 7670: 	
 7671:         my $scancode;
 7672:         if ((exists($scan_record->{'scantron.CODE'})) &&
 7673:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 7674:             $scancode = $scan_record->{'scantron.CODE'};
 7675:         } else {
 7676:             $scancode = '';
 7677:         }
 7678: 
 7679:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 7680:                                    \@resources,\%partids_by_symb) eq 'ssi_error') {
 7681:             $ssi_error = 0; # So end of handler error message does not trigger.
 7682:             $r->print("</form>");
 7683:             &ssi_print_error($r);
 7684:             &Apache::lonnet::remove_lock($lock);
 7685:             return '';      # Why return ''?  Beats me.
 7686:         }
 7687: 
 7688: 	$completedstudents{$uname}={'line'=>$line};
 7689:         if ($env{'form.verifyrecord'}) {
 7690:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 7691:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 7692:             chomp($studentdata);
 7693:             $studentdata =~ s/\r$//;
 7694:             my $studentrecord = '';
 7695:             my $counter = -1;
 7696:             foreach my $resource (@resources) {
 7697:                 my $ressymb = $resource->symb();
 7698:                 ($counter,my $recording) =
 7699:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 7700:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
 7701:                                              \%scantron_config,\%lettdig,$numletts);
 7702:                 $studentrecord .= $recording;
 7703:             }
 7704:             if ($studentrecord ne $studentdata) {
 7705:                 &Apache::lonxml::clear_problem_counter();
 7706:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 7707:                                            \@resources,\%partids_by_symb) eq 'ssi_error') {
 7708:                     $ssi_error = 0; # So end of handler error message does not trigger.
 7709:                     $r->print("</form>");
 7710:                     &ssi_print_error($r);
 7711:                     &Apache::lonnet::remove_lock($lock);
 7712:                     delete($completedstudents{$uname});
 7713:                     return '';
 7714:                 }
 7715:                 $counter = -1;
 7716:                 $studentrecord = '';
 7717:                 foreach my $resource (@resources) {
 7718:                     my $ressymb = $resource->symb();
 7719:                     ($counter,my $recording) =
 7720:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 7721:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 7722:                                                  \%scantron_config,\%lettdig,$numletts);
 7723:                     $studentrecord .= $recording;
 7724:                 }
 7725:                 if ($studentrecord ne $studentdata) {
 7726:                     $r->print('<p><span class="LC_error">');
 7727:                     if ($scancode eq '') {
 7728:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2].',
 7729:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 7730:                     } else {
 7731:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2] and CODE: [_3].',
 7732:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 7733:                     }
 7734:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 7735:                               &Apache::loncommon::start_data_table_header_row()."\n".
 7736:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 7737:                               &Apache::loncommon::end_data_table_header_row()."\n".
 7738:                               &Apache::loncommon::start_data_table_row().
 7739:                               '<td>'.&mt('Bubble Sheet').'</td>'.
 7740:                               '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
 7741:                               &Apache::loncommon::end_data_table_row().
 7742:                               &Apache::loncommon::start_data_table_row().
 7743:                               '<td>Stored submissions</td>'.
 7744:                               '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
 7745:                               &Apache::loncommon::end_data_table_row().
 7746:                               &Apache::loncommon::end_data_table().'</p>');
 7747:                 } else {
 7748:                     $r->print('<br /><span class="LC_warning">'.
 7749:                              &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 />'.
 7750:                              &mt("As a consequence, this user's submission history records two tries.").
 7751:                                  '</span><br />');
 7752:                 }
 7753:             }
 7754:         }
 7755:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 7756:     } continue {
 7757: 	&Apache::lonxml::clear_problem_counter();
 7758: 	&Apache::lonnet::delenv('scantron.');
 7759:     }
 7760:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 7761:     &Apache::lonnet::remove_lock($lock);
 7762: #    my $lasttime = &Time::HiRes::time()-$start;
 7763: #    $r->print("<p>took $lasttime</p>");
 7764: 
 7765:     $r->print("</form>");
 7766:     return '';
 7767: }
 7768: 
 7769: sub graders_resources_pass {
 7770:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb) = @_;
 7771:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
 7772:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
 7773:         foreach my $resource (@{$resources}) {
 7774:             my $ressymb = $resource->symb();
 7775:             my ($analysis,$parts) =
 7776:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
 7777:                                           $env{'user.name'},$env{'user.domain'},1);
 7778:             $grader_partids_by_symb->{$ressymb} = $parts;
 7779:             if (ref($analysis) eq 'HASH') {
 7780:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 7781:                     $grader_randomlists_by_symb->{$ressymb} =
 7782:                         $analysis->{'parts_withrandomlist'};
 7783:                 }
 7784:             }
 7785:         }
 7786:     }
 7787:     return;
 7788: }
 7789: 
 7790: sub grade_student_bubbles {
 7791:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts) = @_;
 7792:     if (ref($resources) eq 'ARRAY') {
 7793:         my $count = 0;
 7794:         foreach my $resource (@{$resources}) {
 7795:             my $ressymb = $resource->symb();
 7796:             my %form = ('submitted'      => 'scantron',
 7797:                         'grade_target'   => 'grade',
 7798:                         'grade_username' => $uname,
 7799:                         'grade_domain'   => $udom,
 7800:                         'grade_courseid' => $env{'request.course.id'},
 7801:                         'grade_symb'     => $ressymb,
 7802:                         'CODE'           => $scancode
 7803:                        );
 7804:             if (ref($parts) eq 'HASH') {
 7805:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 7806:                     foreach my $part (@{$parts->{$ressymb}}) {
 7807:                         $form{'scantron_questnum_start.'.$part} =
 7808:                             1+$env{'form.scantron.first_bubble_line.'.$count};
 7809:                         $count++;
 7810:                     }
 7811:                 }
 7812:             }
 7813:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 7814:             return 'ssi_error' if ($ssi_error);
 7815:             last if (&Apache::loncommon::connection_aborted($r));
 7816:         }
 7817:     }
 7818:     return;
 7819: }
 7820: 
 7821: sub scantron_upload_scantron_data {
 7822:     my ($r,$symb)=@_;
 7823:     my $dom = $env{'request.role.domain'};
 7824:     my $domdesc = &Apache::lonnet::domain($dom,'description');
 7825:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
 7826:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 7827: 							  'domainid',
 7828: 							  'coursename',$dom);
 7829:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
 7830:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
 7831:     my $default_form_data=&defaultFormData($symb);
 7832:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
 7833:     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.");
 7834:     $r->print(&Apache::lonhtmlcommon::scripttag('
 7835:     function checkUpload(formname) {
 7836: 	if (formname.upfile.value == "") {
 7837: 	    alert("'.$nofile_alert.'");
 7838: 	    return false;
 7839: 	}
 7840:         if (formname.courseid.value == "") {
 7841:             alert("'.$nocourseid_alert.'");
 7842:             return false;
 7843:         }
 7844: 	formname.submit();
 7845:     }
 7846: 
 7847:     function ToSyllabus() {
 7848:         var cdom = '."'$dom'".';
 7849:         var cnum = document.rules.courseid.value;
 7850:         if (cdom == "" || cdom == null) {
 7851:             return;
 7852:         }
 7853:         if (cnum == "" || cnum == null) {
 7854:            return;
 7855:         }
 7856:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
 7857:                             "height=350,width=350,scrollbars=yes,menubar=no");
 7858:         return;
 7859:     }
 7860: 
 7861: '));
 7862:     $r->print('
 7863: <h3>'.&mt('Send scanned bubblesheet data to a course').'</h3>
 7864: 
 7865: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 7866: '.$default_form_data.
 7867:   &Apache::lonhtmlcommon::start_pick_box().
 7868:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
 7869:   '<input name="courseid" type="text" size="30" />'.$select_link.
 7870:   &Apache::lonhtmlcommon::row_closure().
 7871:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
 7872:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
 7873:   &Apache::lonhtmlcommon::row_closure().
 7874:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
 7875:   '<input name="domainid" type="hidden" />'.$domdesc.
 7876:   &Apache::lonhtmlcommon::row_closure().
 7877:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
 7878:   '<input type="file" name="upfile" size="50" />'.
 7879:   &Apache::lonhtmlcommon::row_closure(1).
 7880:   &Apache::lonhtmlcommon::end_pick_box().'<br />
 7881: 
 7882: <input name="command" value="scantronupload_save" type="hidden" />
 7883: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 7884: </form>
 7885: ');
 7886:     return '';
 7887: }
 7888: 
 7889: 
 7890: sub scantron_upload_scantron_data_save {
 7891:     my($r,$symb)=@_;
 7892:     my $doanotherupload=
 7893: 	'<br /><form action="/adm/grades" method="post">'."\n".
 7894: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 7895: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 7896: 	'</form>'."\n";
 7897:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 7898: 	!&Apache::lonnet::allowed('usc',
 7899: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 7900: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
 7901: 	unless ($symb) {
 7902: 	    $r->print($doanotherupload);
 7903: 	}
 7904: 	return '';
 7905:     }
 7906:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 7907:     my $uploadedfile;
 7908:     $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
 7909:     if (length($env{'form.upfile'}) < 2) {
 7910:         $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>'));
 7911:     } else {
 7912:         my $result = 
 7913:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
 7914:                                             $env{'form.courseid'},$env{'form.domainid'});
 7915: 	if ($result =~ m{^/uploaded/}) {
 7916: 	    $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
 7917:                           '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
 7918: 			  '<span class="LC_filename">'.$result.'</span>'));
 7919:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
 7920:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
 7921:                                                        $env{'form.courseid'},$uploadedfile));
 7922: 	} else {
 7923: 	    $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
 7924:                           '<span class="LC_error">','</span>',$result,
 7925: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 7926: 	}
 7927:     }
 7928:     if ($symb) {
 7929: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
 7930:     } else {
 7931: 	$r->print($doanotherupload);
 7932:     }
 7933:     return '';
 7934: }
 7935: 
 7936: sub validate_uploaded_scantron_file {
 7937:     my ($cdom,$cname,$fname) = @_;
 7938:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
 7939:     my @lines;
 7940:     if ($scanlines ne '-1') {
 7941:         @lines=split("\n",$scanlines,-1);
 7942:     }
 7943:     my $output;
 7944:     if (@lines) {
 7945:         my (%counts,$max_match_format);
 7946:         my ($max_match_count,$max_match_pct) = (0,0);
 7947:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
 7948:         my %idmap = &username_to_idmap($classlist);
 7949:         foreach my $key (keys(%idmap)) {
 7950:             my $lckey = lc($key);
 7951:             $idmap{$lckey} = $idmap{$key};
 7952:         }
 7953:         my %unique_formats;
 7954:         my @formatlines = &get_scantronformat_file();
 7955:         foreach my $line (@formatlines) {
 7956:             chomp($line);
 7957:             my @config = split(/:/,$line);
 7958:             my $idstart = $config[5];
 7959:             my $idlength = $config[6];
 7960:             if (($idstart ne '') && ($idlength > 0)) {
 7961:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
 7962:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
 7963:                 } else {
 7964:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
 7965:                 }
 7966:             }
 7967:         }
 7968:         foreach my $key (keys(%unique_formats)) {
 7969:             my ($idstart,$idlength) = split(':',$key);
 7970:             %{$counts{$key}} = (
 7971:                                'found'   => 0,
 7972:                                'total'   => 0,
 7973:                               );
 7974:             foreach my $line (@lines) {
 7975:                 next if ($line =~ /^#/);
 7976:                 next if ($line =~ /^[\s\cz]*$/);
 7977:                 my $id = substr($line,$idstart-1,$idlength);
 7978:                 $id = lc($id);
 7979:                 if (exists($idmap{$id})) {
 7980:                     $counts{$key}{'found'} ++;
 7981:                 }
 7982:                 $counts{$key}{'total'} ++;
 7983:             }
 7984:             if ($counts{$key}{'total'}) {
 7985:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
 7986:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
 7987:                     $max_match_pct = $percent_match;
 7988:                     $max_match_format = $key;
 7989:                     $max_match_count = $counts{$key}{'total'};
 7990:                 }
 7991:             }
 7992:         }
 7993:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
 7994:             my $format_descs;
 7995:             my $numwithformat = @{$unique_formats{$max_match_format}};
 7996:             for (my $i=0; $i<$numwithformat; $i++) {
 7997:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
 7998:                 if ($i<$numwithformat-2) {
 7999:                     $format_descs .= '"<i>'.$desc.'</i>", ';
 8000:                 } elsif ($i==$numwithformat-2) {
 8001:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
 8002:                 } elsif ($i==$numwithformat-1) {
 8003:                     $format_descs .= '"<i>'.$desc.'</i>"';
 8004:                 }
 8005:             }
 8006:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
 8007:             $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).
 8008:                        '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
 8009:                        '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
 8010:                        '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
 8011:                                   '<i>'.$cdom.'</i>').'</li>'.
 8012:                        '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
 8013:                        '<li>'.&mt('The course roster is not up to date').'</li>'.
 8014:                        '</ul>';
 8015:         }
 8016:     } else {
 8017:         $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
 8018:     }
 8019:     return $output;
 8020: }
 8021: 
 8022: sub valid_file {
 8023:     my ($requested_file)=@_;
 8024:     foreach my $filename (sort(&scantron_filenames())) {
 8025: 	if ($requested_file eq $filename) { return 1; }
 8026:     }
 8027:     return 0;
 8028: }
 8029: 
 8030: sub scantron_download_scantron_data {
 8031:     my ($r,$symb)=@_;
 8032:     my $default_form_data=&defaultFormData($symb);
 8033:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 8034:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8035:     my $file=$env{'form.scantron_selectfile'};
 8036:     if (! &valid_file($file)) {
 8037: 	$r->print('
 8038: 	<p>
 8039: 	    '.&mt('The requested file name was invalid.').'
 8040:         </p>
 8041: ');
 8042: 	return;
 8043:     }
 8044:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 8045:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 8046:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 8047:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 8048:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 8049:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 8050:     $r->print('
 8051:     <p>
 8052: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
 8053: 	      '<a href="'.$orig.'">','</a>').'
 8054:     </p>
 8055:     <p>
 8056: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 8057: 	      '<a href="'.$corrected.'">','</a>').'
 8058:     </p>
 8059:     <p>
 8060: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 8061: 	      '<a href="'.$skipped.'">','</a>').'
 8062:     </p>
 8063: ');
 8064:     return '';
 8065: }
 8066: 
 8067: sub checkscantron_results {
 8068:     my ($r,$symb) = @_;
 8069:     if (!$symb) {return '';}
 8070:     my $cid = $env{'request.course.id'};
 8071:     my %lettdig = &letter_to_digits();
 8072:     my $numletts = scalar(keys(%lettdig));
 8073:     my $cnum = $env{'course.'.$cid.'.num'};
 8074:     my $cdom = $env{'course.'.$cid.'.domain'};
 8075:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8076:     my %record;
 8077:     my %scantron_config =
 8078:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
 8079:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
 8080:     my $classlist=&Apache::loncoursedata::get_classlist();
 8081:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 8082:     my $navmap=Apache::lonnavmaps::navmap->new();
 8083:     unless (ref($navmap)) {
 8084:         $r->print(&navmap_errormsg());
 8085:         return '';
 8086:     }
 8087:     my $map=$navmap->getResourceByUrl($sequence);
 8088:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8089:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
 8090:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,                             \%grader_randomlists_by_symb);
 8091: 
 8092:     my ($uname,$udom);
 8093:     my (%scandata,%lastname,%bylast);
 8094:     $r->print('
 8095: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 8096: 
 8097:     my @delayqueue;
 8098:     my %completedstudents;
 8099: 
 8100:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
 8101:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet/Submissions Comparison Status',
 8102:                                     'Progress of Bubblesheet Data/Submission Records Comparison',$count,
 8103:                                     'inline',undef,'checkscantron');
 8104:     my ($username,$domain,$started);
 8105:     my $nav_error;
 8106:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
 8107:     if ($nav_error) {
 8108:         $r->print(&navmap_errormsg());
 8109:         return '';
 8110:     }
 8111: 
 8112:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 8113:                                           'Processing first student');
 8114:     my $start=&Time::HiRes::time();
 8115:     my $i=-1;
 8116: 
 8117:     while ($i<$scanlines->{'count'}) {
 8118:         ($username,$domain,$uname)=('','','');
 8119:         $i++;
 8120:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 8121:         if ($line=~/^[\s\cz]*$/) { next; }
 8122:         if ($started) {
 8123:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 8124:                                                      'last student');
 8125:         }
 8126:         $started=1;
 8127:         my $scan_record=
 8128:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 8129:                                                      $scan_data);
 8130:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
 8131:                                                               \%idmap,$i)) {
 8132:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 8133:                                 'Unable to find a student that matches',1);
 8134:             next;
 8135:         }
 8136:         if (exists $completedstudents{$uname}) {
 8137:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 8138:                                 'Student '.$uname.' has multiple sheets',2);
 8139:             next;
 8140:         }
 8141:         my $pid = $scan_record->{'scantron.ID'};
 8142:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 8143:         push(@{$bylast{$lastname{$pid}}},$pid);
 8144:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 8145:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 8146:         chomp($scandata{$pid});
 8147:         $scandata{$pid} =~ s/\r$//;
 8148:         ($username,$domain)=split(/:/,$uname);
 8149:         my $counter = -1;
 8150:         foreach my $resource (@resources) {
 8151:             my $parts;
 8152:             my $ressymb = $resource->symb();
 8153:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 8154:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 8155:                 (my $analysis,$parts) =
 8156:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$username,$domain);
 8157:             } else {
 8158:                 $parts = $grader_partids_by_symb{$ressymb};
 8159:             }
 8160:             ($counter,my $recording) =
 8161:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
 8162:                                          $scandata{$pid},$parts,
 8163:                                          \%scantron_config,\%lettdig,$numletts);
 8164:             $record{$pid} .= $recording;
 8165:         }
 8166:     }
 8167:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 8168:     $r->print('<br />');
 8169:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 8170:     $passed = 0;
 8171:     $failed = 0;
 8172:     $numstudents = 0;
 8173:     foreach my $last (sort(keys(%bylast))) {
 8174:         if (ref($bylast{$last}) eq 'ARRAY') {
 8175:             foreach my $pid (sort(@{$bylast{$last}})) {
 8176:                 my $showscandata = $scandata{$pid};
 8177:                 my $showrecord = $record{$pid};
 8178:                 $showscandata =~ s/\s/&nbsp;/g;
 8179:                 $showrecord =~ s/\s/&nbsp;/g;
 8180:                 if ($scandata{$pid} eq $record{$pid}) {
 8181:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 8182:                     $okstudents .= '<tr class="'.$css_class.'">'.
 8183: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 8184: '</tr>'."\n".
 8185: '<tr class="'.$css_class.'">'."\n".
 8186: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
 8187:                     $passed ++;
 8188:                 } else {
 8189:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
 8190:                     $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".
 8191: '</tr>'."\n".
 8192: '<tr class="'.$css_class.'">'."\n".
 8193: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
 8194: '</tr>'."\n";
 8195:                     $failed ++;
 8196:                 }
 8197:                 $numstudents ++;
 8198:             }
 8199:         }
 8200:     }
 8201:     $r->print('<p>'.&mt('Comparison of bubblesheet data (including corrections) with corresponding submission records (most recent submission) for <b>[quant,_1,student]</b>  ([_2] scantron lines/student).',$numstudents,$env{'form.scantron_maxbubble'}).'</p>');
 8202:     $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>');
 8203:     if ($passed) {
 8204:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
 8205:         $r->print(&Apache::loncommon::start_data_table()."\n".
 8206:                  &Apache::loncommon::start_data_table_header_row()."\n".
 8207:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 8208:                  &Apache::loncommon::end_data_table_header_row()."\n".
 8209:                  $okstudents."\n".
 8210:                  &Apache::loncommon::end_data_table().'<br />');
 8211:     }
 8212:     if ($failed) {
 8213:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
 8214:         $r->print(&Apache::loncommon::start_data_table()."\n".
 8215:                  &Apache::loncommon::start_data_table_header_row()."\n".
 8216:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 8217:                  &Apache::loncommon::end_data_table_header_row()."\n".
 8218:                  $badstudents."\n".
 8219:                  &Apache::loncommon::end_data_table()).'<br />'.
 8220:                  &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.');  
 8221:     }
 8222:     $r->print('</form><br />');
 8223:     return;
 8224: }
 8225: 
 8226: sub verify_scantron_grading {
 8227:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
 8228:         $scantron_config,$lettdig,$numletts) = @_;
 8229:     my ($record,%expected,%startpos);
 8230:     return ($counter,$record) if (!ref($resource));
 8231:     return ($counter,$record) if (!$resource->is_problem());
 8232:     my $symb = $resource->symb();
 8233:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
 8234:     foreach my $part_id (@{$partids}) {
 8235:         $counter ++;
 8236:         $expected{$part_id} = 0;
 8237:         if ($env{"form.scantron.sub_bubblelines.$counter"}) {
 8238:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
 8239:             foreach my $item (@sub_lines) {
 8240:                 $expected{$part_id} += $item;
 8241:             }
 8242:         } else {
 8243:             $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
 8244:         }
 8245:         $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
 8246:     }
 8247:     if ($symb) {
 8248:         my %recorded;
 8249:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
 8250:         if ($returnhash{'version'}) {
 8251:             my %lasthash=();
 8252:             my $version;
 8253:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 8254:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 8255:                     $lasthash{$key}=$returnhash{$version.':'.$key};
 8256:                 }
 8257:             }
 8258:             foreach my $key (keys(%lasthash)) {
 8259:                 if ($key =~ /\.scantron$/) {
 8260:                     my $value = &unescape($lasthash{$key});
 8261:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
 8262:                     if ($value eq '') {
 8263:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
 8264:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
 8265:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8266:                             }
 8267:                         }
 8268:                     } else {
 8269:                         my @tocheck;
 8270:                         my @items = split(//,$value);
 8271:                         if (($scantron_config->{'Qon'} eq 'letter') ||
 8272:                             ($scantron_config->{'Qon'} eq 'number')) {
 8273:                             if (@items < $expected{$part_id}) {
 8274:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
 8275:                                 my @singles = split(//,$fragment);
 8276:                                 foreach my $pos (@singles) {
 8277:                                     if ($pos eq ' ') {
 8278:                                         push(@tocheck,$pos);
 8279:                                     } else {
 8280:                                         my $next = shift(@items);
 8281:                                         push(@tocheck,$next);
 8282:                                     }
 8283:                                 }
 8284:                             } else {
 8285:                                 @tocheck = @items;
 8286:                             }
 8287:                             foreach my $letter (@tocheck) {
 8288:                                 if ($scantron_config->{'Qon'} eq 'letter') {
 8289:                                     if ($letter !~ /^[A-J]$/) {
 8290:                                         $letter = $scantron_config->{'Qoff'};
 8291:                                     }
 8292:                                     $recorded{$part_id} .= $letter;
 8293:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
 8294:                                     my $digit;
 8295:                                     if ($letter !~ /^[A-J]$/) {
 8296:                                         $digit = $scantron_config->{'Qoff'};
 8297:                                     } else {
 8298:                                         $digit = $lettdig->{$letter};
 8299:                                     }
 8300:                                     $recorded{$part_id} .= $digit;
 8301:                                 }
 8302:                             }
 8303:                         } else {
 8304:                             @tocheck = @items;
 8305:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
 8306:                                 my $curr_sub = shift(@tocheck);
 8307:                                 my $digit;
 8308:                                 if ($curr_sub =~ /^[A-J]$/) {
 8309:                                     $digit = $lettdig->{$curr_sub}-1;
 8310:                                 }
 8311:                                 if ($curr_sub eq 'J') {
 8312:                                     $digit += scalar($numletts);
 8313:                                 }
 8314:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 8315:                                     if ($j == $digit) {
 8316:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
 8317:                                     } else {
 8318:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8319:                                     }
 8320:                                 }
 8321:                             }
 8322:                         }
 8323:                     }
 8324:                 }
 8325:             }
 8326:         }
 8327:         foreach my $part_id (@{$partids}) {
 8328:             if ($recorded{$part_id} eq '') {
 8329:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
 8330:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 8331:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8332:                     }
 8333:                 }
 8334:             }
 8335:             $record .= $recorded{$part_id};
 8336:         }
 8337:     }
 8338:     return ($counter,$record);
 8339: }
 8340: 
 8341: sub letter_to_digits { 
 8342:     my %lettdig = (
 8343:                     A => 1,
 8344:                     B => 2,
 8345:                     C => 3,
 8346:                     D => 4,
 8347:                     E => 5,
 8348:                     F => 6,
 8349:                     G => 7,
 8350:                     H => 8,
 8351:                     I => 9,
 8352:                     J => 0,
 8353:                   );
 8354:     return %lettdig;
 8355: }
 8356: 
 8357: 
 8358: #-------- end of section for handling grading scantron forms -------
 8359: #
 8360: #-------------------------------------------------------------------
 8361: 
 8362: #-------------------------- Menu interface -------------------------
 8363: #
 8364: #--- Href with symb and command ---
 8365: 
 8366: sub href_symb_cmd {
 8367:     my ($symb,$cmd)=@_;
 8368:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&command='.$cmd;
 8369: }
 8370: 
 8371: sub grading_menu {
 8372:     my ($request,$symb) = @_;
 8373:     if (!$symb) {return '';}
 8374: 
 8375:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 8376:                   'command'=>'individual');
 8377:     
 8378:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8379: 
 8380:     $fields{'command'}='ungraded';
 8381:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8382: 
 8383:     $fields{'command'}='table';
 8384:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8385: 
 8386:     $fields{'command'}='all_for_one';
 8387:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8388: 
 8389:     $fields{'command'} = 'csvform';
 8390:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8391:     
 8392:     $fields{'command'} = 'processclicker';
 8393:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8394:     
 8395:     $fields{'command'} = 'scantron_selectphase';
 8396:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8397: 
 8398:     $fields{'command'} = 'initialverifyreceipt';
 8399:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8400:     
 8401:     my @menu = ({	categorytitle=>'Hand Grading',
 8402:             items =>[
 8403:                         {	linktext => 'Select individual students to grade',
 8404:                     		url => $url1a,
 8405:                     		permission => 'F',
 8406:                     		icon => 'edit-find-replace.png',
 8407:                     		linktitle => 'Grade current resource for a selection of students.'
 8408:                         }, 
 8409:                         {       linktext => 'Grade ungraded submissions.',
 8410:                                 url => $url1b,
 8411:                                 permission => 'F',
 8412:                                 icon => 'edit-find-replace.png',
 8413:                                 linktitle => 'Grade all submissions that have not been graded yet.'
 8414:                         },
 8415: 
 8416:                         {       linktext => 'Grading table',
 8417:                                 url => $url1c,
 8418:                                 permission => 'F',
 8419:                                 icon => 'edit-find-replace.png',
 8420:                                 linktitle => 'Grade current resource for all students.'
 8421:                         },
 8422:                         {       linktext => 'Grade page/folder for one student',
 8423:                                 url => $url1d,
 8424:                                 permission => 'F',
 8425:                                 icon => 'edit-find-replace.png',
 8426:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
 8427:                         }]},
 8428:                          { categorytitle=>'Automated Grading',
 8429:                items =>[
 8430: 
 8431:                 	    {	linktext => 'Upload Scores',
 8432:                     		url => $url2,
 8433:                     		permission => 'F',
 8434:                     		icon => 'uploadscores.png',
 8435:                     		linktitle => 'Specify a file containing the class scores for current resource.'
 8436:                 	    },
 8437:                 	    {	linktext => 'Process Clicker',
 8438:                     		url => $url3,
 8439:                     		permission => 'F',
 8440:                     		icon => 'addClickerInfoFile.png',
 8441:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
 8442:                 	    },
 8443:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
 8444:                     		url => $url4,
 8445:                     		permission => 'F',
 8446:                     		icon => 'stat.png',
 8447:                     		linktitle => 'Grade scantron exams, upload/download scantron data files, and review previously graded scantron exams.'
 8448:                 	    },
 8449:                             {   linktext => 'Verify Receipt Number',
 8450:                                 url => $url5,
 8451:                                 permission => 'F',
 8452:                                 icon => 'edit-find-replace.png',
 8453:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
 8454:                             }
 8455: 
 8456:                     ]
 8457:             });
 8458: 
 8459:     # Create the menu
 8460:     my $Str;
 8461:     $Str .= '<form method="post" action="" name="gradingMenu">';
 8462:     $Str .= '<input type="hidden" name="command" value="" />'.
 8463:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 8464: 
 8465:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
 8466:     return $Str;    
 8467: }
 8468: 
 8469: 
 8470: sub ungraded {
 8471:     my ($request)=@_;
 8472:     &submit_options($request);
 8473: }
 8474: 
 8475: sub submit_options_sequence {
 8476:     my ($request,$symb) = @_;
 8477:     if (!$symb) {return '';}
 8478:     &commonJSfunctions($request);
 8479:     my $result;
 8480: 
 8481:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8482:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 8483:     $result.='
 8484: <h2>
 8485:   '.&mt('Grade page/folder for one student').'
 8486: </h2>'.
 8487:             &selectfield(0).
 8488:             '<input type="hidden" name="command" value="pickStudentPage" />
 8489:             <div>
 8490:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 8491:             </div>
 8492:         </div>
 8493:   </form>';
 8494:     return $result;
 8495: }
 8496: 
 8497: sub submit_options_table {
 8498:     my ($request,$symb) = @_;
 8499:     if (!$symb) {return '';}
 8500:     &commonJSfunctions($request);
 8501:     my $result;
 8502: 
 8503:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8504:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 8505: 
 8506:     $result.='
 8507: <h2>
 8508:   '.&mt('Grading table').'
 8509: </h2>'.
 8510:             &selectfield(0).
 8511:             '<input type="hidden" name="command" value="viewgrades" />
 8512:             <div>
 8513:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 8514:             </div>
 8515:         </div>
 8516:   </form>';
 8517:     return $result;
 8518: }
 8519: 
 8520: 
 8521: 
 8522: #--- Displays the submissions first page -------
 8523: sub submit_options {
 8524:     my ($request,$symb) = @_;
 8525:     if (!$symb) {return '';}
 8526: 
 8527:     &commonJSfunctions($request);
 8528:     my $result;
 8529: 
 8530:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8531: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 8532:     $result.='
 8533: <h2>
 8534:   '.&mt('Select individual students to grade').'
 8535: </h2>'.&selectfield(1).'
 8536:                 <input type="hidden" name="command" value="submission" /> 
 8537: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
 8538:             </div>
 8539:           </div>
 8540: 
 8541: 
 8542:   </form>';
 8543:     return $result;
 8544: }
 8545: 
 8546: sub selectfield {
 8547:    my ($full)=@_;
 8548:    my $result='<div class="LC_columnSection">
 8549:   
 8550:     <fieldset>
 8551:       <legend>
 8552:        '.&mt('Sections').'
 8553:       </legend>
 8554:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
 8555:     </fieldset>
 8556:   
 8557:     <fieldset>
 8558:       <legend>
 8559:         '.&mt('Groups').'
 8560:       </legend>
 8561:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
 8562:     </fieldset>
 8563:   
 8564:     <fieldset>
 8565:       <legend>
 8566:         '.&mt('Access Status').'
 8567:       </legend>
 8568:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
 8569:     </fieldset>';
 8570:     if ($full) {
 8571:        $result.='
 8572:     <fieldset>
 8573:       <legend>
 8574:         '.&mt('Submission Status').'
 8575:       </legend>'.
 8576:        &Apache::loncommon::select_form('all','submitonly',
 8577:           (&Apache::lonlocal::texthash(
 8578:              'yes'       => 'with submissions',
 8579:              'queued'    => 'in grading queue',
 8580:              'graded'    => 'with ungraded submissions',
 8581:              'incorrect' => 'with incorrect submissions',
 8582:              'all'       => 'with any status'),
 8583:              'select_form_order' => ['yes','queued','graded','incorrect','all'])).
 8584:    '</fieldset>';
 8585:     }
 8586:     $result.='</div><br />';
 8587:     return $result;
 8588: }
 8589: 
 8590: sub reset_perm {
 8591:     undef(%perm);
 8592: }
 8593: 
 8594: sub init_perm {
 8595:     &reset_perm();
 8596:     foreach my $test_perm ('vgr','mgr','opa') {
 8597: 
 8598: 	my $scope = $env{'request.course.id'};
 8599: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
 8600: 
 8601: 	    $scope .= '/'.$env{'request.course.sec'};
 8602: 	    if ( $perm{$test_perm}=
 8603: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
 8604: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
 8605: 	    } else {
 8606: 		delete($perm{$test_perm});
 8607: 	    }
 8608: 	}
 8609:     }
 8610: }
 8611: 
 8612: sub gather_clicker_ids {
 8613:     my %clicker_ids;
 8614: 
 8615:     my $classlist = &Apache::loncoursedata::get_classlist();
 8616: 
 8617:     # Set up a couple variables.
 8618:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
 8619:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
 8620:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
 8621: 
 8622:     foreach my $student (keys(%$classlist)) {
 8623:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
 8624:         my $username = $classlist->{$student}->[$username_idx];
 8625:         my $domain   = $classlist->{$student}->[$domain_idx];
 8626:         my $clickers =
 8627: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
 8628:         foreach my $id (split(/\,/,$clickers)) {
 8629:             $id=~s/^[\#0]+//;
 8630:             $id=~s/[\-\:]//g;
 8631:             if (exists($clicker_ids{$id})) {
 8632: 		$clicker_ids{$id}.=','.$username.':'.$domain;
 8633:             } else {
 8634: 		$clicker_ids{$id}=$username.':'.$domain;
 8635:             }
 8636:         }
 8637:     }
 8638:     return %clicker_ids;
 8639: }
 8640: 
 8641: sub gather_adv_clicker_ids {
 8642:     my %clicker_ids;
 8643:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 8644:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8645:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
 8646:     foreach my $element (sort(keys(%coursepersonnel))) {
 8647:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
 8648:             my ($puname,$pudom)=split(/\:/,$person);
 8649:             my $clickers =
 8650: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
 8651:             foreach my $id (split(/\,/,$clickers)) {
 8652: 		$id=~s/^[\#0]+//;
 8653:                 $id=~s/[\-\:]//g;
 8654: 		if (exists($clicker_ids{$id})) {
 8655: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
 8656: 		} else {
 8657: 		    $clicker_ids{$id}=$puname.':'.$pudom;
 8658: 		}
 8659:             }
 8660:         }
 8661:     }
 8662:     return %clicker_ids;
 8663: }
 8664: 
 8665: sub clicker_grading_parameters {
 8666:     return ('gradingmechanism' => 'scalar',
 8667:             'upfiletype' => 'scalar',
 8668:             'specificid' => 'scalar',
 8669:             'pcorrect' => 'scalar',
 8670:             'pincorrect' => 'scalar');
 8671: }
 8672: 
 8673: sub process_clicker {
 8674:     my ($r,$symb)=@_;
 8675:     if (!$symb) {return '';}
 8676:     my $result=&checkforfile_js();
 8677:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 8678:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 8679:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource.').
 8680:         '</b></td></tr>'."\n";
 8681:     $result.='<tr bgcolor="#ffffe6"><td>'."\n";
 8682: # Attempt to restore parameters from last session, set defaults if not present
 8683:     my %Saveable_Parameters=&clicker_grading_parameters();
 8684:     &Apache::loncommon::restore_course_settings('grades_clicker',
 8685:                                                  \%Saveable_Parameters);
 8686:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
 8687:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
 8688:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
 8689:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
 8690: 
 8691:     my %checked;
 8692:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
 8693:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
 8694:           $checked{$gradingmechanism}=' checked="checked"';
 8695:        }
 8696:     }
 8697: 
 8698:     my $upload=&mt("Upload File");
 8699:     my $type=&mt("Type");
 8700:     my $attendance=&mt("Award points just for participation");
 8701:     my $personnel=&mt("Correctness determined from response by course personnel");
 8702:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
 8703:     my $given=&mt("Correctness determined from given list of answers").' '.
 8704:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
 8705:     my $pcorrect=&mt("Percentage points for correct solution");
 8706:     my $pincorrect=&mt("Percentage points for incorrect solution");
 8707:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
 8708: 						   ('iclicker' => 'i>clicker',
 8709:                                                     'interwrite' => 'interwrite PRS'));
 8710:     $symb = &Apache::lonenc::check_encrypt($symb);
 8711:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
 8712: function sanitycheck() {
 8713: // Accept only integer percentages
 8714:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
 8715:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
 8716: // Find out grading choice
 8717:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8718:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
 8719:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
 8720:       }
 8721:    }
 8722: // By default, new choice equals user selection
 8723:    newgradingchoice=gradingchoice;
 8724: // Not good to give more points for false answers than correct ones
 8725:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
 8726:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
 8727:    }
 8728: // If new choice is attendance only, and old choice was correctness-based, restore defaults
 8729:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
 8730:       document.forms.gradesupload.pcorrect.value=100;
 8731:       document.forms.gradesupload.pincorrect.value=100;
 8732:    }
 8733: // If the values are different, cannot be attendance only
 8734:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
 8735:        (gradingchoice=='attendance')) {
 8736:        newgradingchoice='personnel';
 8737:    }
 8738: // Change grading choice to new one
 8739:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8740:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
 8741:          document.forms.gradesupload.gradingmechanism[i].checked=true;
 8742:       } else {
 8743:          document.forms.gradesupload.gradingmechanism[i].checked=false;
 8744:       }
 8745:    }
 8746: // Remember the old state
 8747:    document.forms.gradesupload.waschecked.value=newgradingchoice;
 8748: }
 8749: ENDUPFORM
 8750:     $result.= <<ENDUPFORM;
 8751: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 8752: <input type="hidden" name="symb" value="$symb" />
 8753: <input type="hidden" name="command" value="processclickerfile" />
 8754: <input type="file" name="upfile" size="50" />
 8755: <br /><label>$type: $selectform</label>
 8756: <br /><label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
 8757: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
 8758: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
 8759: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
 8760: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
 8761: <br />&nbsp;&nbsp;&nbsp;
 8762: <input type="text" name="givenanswer" size="50" />
 8763: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
 8764: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
 8765: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
 8766: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 8767: </form>'
 8768: ENDUPFORM
 8769:     $result.='</td></tr></table>'."\n".
 8770:              '</td></tr></table><br /><br />'."\n";
 8771:     return $result;
 8772: }
 8773: 
 8774: sub process_clicker_file {
 8775:     my ($r,$symb)=@_;
 8776:     if (!$symb) {return '';}
 8777: 
 8778:     my %Saveable_Parameters=&clicker_grading_parameters();
 8779:     &Apache::loncommon::store_course_settings('grades_clicker',
 8780:                                               \%Saveable_Parameters);
 8781:     my $result='';
 8782:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
 8783: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
 8784: 	return $result;
 8785:     }
 8786:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
 8787:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
 8788:         return $result;
 8789:     }
 8790:     my $foundgiven=0;
 8791:     if ($env{'form.gradingmechanism'} eq 'given') {
 8792:         $env{'form.givenanswer'}=~s/^\s*//gs;
 8793:         $env{'form.givenanswer'}=~s/\s*$//gs;
 8794:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-]+/\,/g;
 8795:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
 8796:         my @answers=split(/\,/,$env{'form.givenanswer'});
 8797:         $foundgiven=$#answers+1;
 8798:     }
 8799:     my %clicker_ids=&gather_clicker_ids();
 8800:     my %correct_ids;
 8801:     if ($env{'form.gradingmechanism'} eq 'personnel') {
 8802: 	%correct_ids=&gather_adv_clicker_ids();
 8803:     }
 8804:     if ($env{'form.gradingmechanism'} eq 'specific') {
 8805: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
 8806: 	   $correct_id=~tr/a-z/A-Z/;
 8807: 	   $correct_id=~s/\s//gs;
 8808: 	   $correct_id=~s/^[\#0]+//;
 8809:            $correct_id=~s/[\-\:]//g;
 8810:            if ($correct_id) {
 8811: 	      $correct_ids{$correct_id}='specified';
 8812:            }
 8813:         }
 8814:     }
 8815:     if ($env{'form.gradingmechanism'} eq 'attendance') {
 8816: 	$result.=&mt('Score based on attendance only');
 8817:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
 8818:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
 8819:     } else {
 8820: 	my $number=0;
 8821: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
 8822: 	foreach my $id (sort(keys(%correct_ids))) {
 8823: 	    $result.='<br /><tt>'.$id.'</tt> - ';
 8824: 	    if ($correct_ids{$id} eq 'specified') {
 8825: 		$result.=&mt('specified');
 8826: 	    } else {
 8827: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
 8828: 		$result.=&Apache::loncommon::plainname($uname,$udom);
 8829: 	    }
 8830: 	    $number++;
 8831: 	}
 8832:         $result.="</p>\n";
 8833: 	if ($number==0) {
 8834: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
 8835: 	    return $result;
 8836: 	}
 8837:     }
 8838:     if (length($env{'form.upfile'}) < 2) {
 8839:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
 8840: 		     '<span class="LC_error">',
 8841: 		     '</span>',
 8842: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
 8843:         return $result;
 8844:     }
 8845: 
 8846: # Were able to get all the info needed, now analyze the file
 8847: 
 8848:     $result.=&Apache::loncommon::studentbrowser_javascript();
 8849:     $symb = &Apache::lonenc::check_encrypt($symb);
 8850:     my $heading=&mt('Scanning clicker file');
 8851:     $result.=(<<ENDHEADER);
 8852: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 8853: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 8854: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 8855: <form method="post" action="/adm/grades" name="clickeranalysis">
 8856: <input type="hidden" name="symb" value="$symb" />
 8857: <input type="hidden" name="command" value="assignclickergrades" />
 8858: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
 8859: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
 8860: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
 8861: ENDHEADER
 8862:     if ($env{'form.gradingmechanism'} eq 'given') {
 8863:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
 8864:     } 
 8865:     my %responses;
 8866:     my @questiontitles;
 8867:     my $errormsg='';
 8868:     my $number=0;
 8869:     if ($env{'form.upfiletype'} eq 'iclicker') {
 8870: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
 8871:     }
 8872:     if ($env{'form.upfiletype'} eq 'interwrite') {
 8873:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
 8874:     }
 8875:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
 8876:              '<input type="hidden" name="number" value="'.$number.'" />'.
 8877:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
 8878:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
 8879:              '<br />';
 8880:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
 8881:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
 8882:        return $result;
 8883:     } 
 8884: # Remember Question Titles
 8885: # FIXME: Possibly need delimiter other than ":"
 8886:     for (my $i=0;$i<$number;$i++) {
 8887:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
 8888:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
 8889:     }
 8890:     my $correct_count=0;
 8891:     my $student_count=0;
 8892:     my $unknown_count=0;
 8893: # Match answers with usernames
 8894: # FIXME: Possibly need delimiter other than ":"
 8895:     foreach my $id (keys(%responses)) {
 8896:        if ($correct_ids{$id}) {
 8897:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
 8898:           $correct_count++;
 8899:        } elsif ($clicker_ids{$id}) {
 8900:           if ($clicker_ids{$id}=~/\,/) {
 8901: # More than one user with the same clicker!
 8902:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
 8903:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 8904:                            "<select name='multi".$id."'>";
 8905:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
 8906:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
 8907:              }
 8908:              $result.='</select>';
 8909:              $unknown_count++;
 8910:           } else {
 8911: # Good: found one and only one user with the right clicker
 8912:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
 8913:              $student_count++;
 8914:           }
 8915:        } else {
 8916:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
 8917:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 8918:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
 8919:                    "\n".&mt("Domain").": ".
 8920:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
 8921:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
 8922:           $unknown_count++;
 8923:        }
 8924:     }
 8925:     $result.='<hr />'.
 8926:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
 8927:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
 8928:        if ($correct_count==0) {
 8929:           $errormsg.="Found no correct answers answers for grading!";
 8930:        } elsif ($correct_count>1) {
 8931:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
 8932:        }
 8933:     }
 8934:     if ($number<1) {
 8935:        $errormsg.="Found no questions.";
 8936:     }
 8937:     if ($errormsg) {
 8938:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
 8939:     } else {
 8940:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
 8941:     }
 8942:     $result.='</form></td></tr></table>'."\n".
 8943:              '</td></tr></table><br /><br />'."\n";
 8944:     return $result;
 8945: }
 8946: 
 8947: sub iclicker_eval {
 8948:     my ($questiontitles,$responses)=@_;
 8949:     my $number=0;
 8950:     my $errormsg='';
 8951:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 8952:         my %components=&Apache::loncommon::record_sep($line);
 8953:         my @entries=map {$components{$_}} (sort(keys(%components)));
 8954: 	if ($entries[0] eq 'Question') {
 8955: 	    for (my $i=3;$i<$#entries;$i+=6) {
 8956: 		$$questiontitles[$number]=$entries[$i];
 8957: 		$number++;
 8958: 	    }
 8959: 	}
 8960: 	if ($entries[0]=~/^\#/) {
 8961: 	    my $id=$entries[0];
 8962: 	    my @idresponses;
 8963: 	    $id=~s/^[\#0]+//;
 8964: 	    for (my $i=0;$i<$number;$i++) {
 8965: 		my $idx=3+$i*6;
 8966: 		push(@idresponses,$entries[$idx]);
 8967: 	    }
 8968: 	    $$responses{$id}=join(',',@idresponses);
 8969: 	}
 8970:     }
 8971:     return ($errormsg,$number);
 8972: }
 8973: 
 8974: sub interwrite_eval {
 8975:     my ($questiontitles,$responses)=@_;
 8976:     my $number=0;
 8977:     my $errormsg='';
 8978:     my $skipline=1;
 8979:     my $questionnumber=0;
 8980:     my %idresponses=();
 8981:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 8982:         my %components=&Apache::loncommon::record_sep($line);
 8983:         my @entries=map {$components{$_}} (sort(keys(%components)));
 8984:         if ($entries[1] eq 'Time') { $skipline=0; next; }
 8985:         if ($entries[1] eq 'Response') { $skipline=1; }
 8986:         next if $skipline;
 8987:         if ($entries[0]!=$questionnumber) {
 8988:            $questionnumber=$entries[0];
 8989:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
 8990:            $number++;
 8991:         }
 8992:         my $id=$entries[4];
 8993:         $id=~s/^[\#0]+//;
 8994:         $id=~s/^v\d*\://i;
 8995:         $id=~s/[\-\:]//g;
 8996:         $idresponses{$id}[$number]=$entries[6];
 8997:     }
 8998:     foreach my $id (keys(%idresponses)) {
 8999:        $$responses{$id}=join(',',@{$idresponses{$id}});
 9000:        $$responses{$id}=~s/^\s*\,//;
 9001:     }
 9002:     return ($errormsg,$number);
 9003: }
 9004: 
 9005: sub assign_clicker_grades {
 9006:     my ($r,$symb)=@_;
 9007:     if (!$symb) {return '';}
 9008: # See which part we are saving to
 9009:     my $res_error;
 9010:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 9011:     if ($res_error) {
 9012:         return &navmap_errormsg();
 9013:     }
 9014: # FIXME: This should probably look for the first handgradeable part
 9015:     my $part=$$partlist[0];
 9016: # Start screen output
 9017:     my $result='';
 9018: 
 9019:     my $heading=&mt('Assigning grades based on clicker file');
 9020:     $result.=(<<ENDHEADER);
 9021: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 9022: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 9023: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 9024: ENDHEADER
 9025: # Get correct result
 9026: # FIXME: Possibly need delimiter other than ":"
 9027:     my @correct=();
 9028:     my $gradingmechanism=$env{'form.gradingmechanism'};
 9029:     my $number=$env{'form.number'};
 9030:     if ($gradingmechanism ne 'attendance') {
 9031:        foreach my $key (keys(%env)) {
 9032:           if ($key=~/^form\.correct\:/) {
 9033:              my @input=split(/\,/,$env{$key});
 9034:              for (my $i=0;$i<=$#input;$i++) {
 9035:                  if (($correct[$i]) && ($input[$i]) &&
 9036:                      ($correct[$i] ne $input[$i])) {
 9037:                     $result.='<br /><span class="LC_warning">'.
 9038:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
 9039:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
 9040:                  } elsif ($input[$i]) {
 9041:                     $correct[$i]=$input[$i];
 9042:                  }
 9043:              }
 9044:           }
 9045:        }
 9046:        for (my $i=0;$i<$number;$i++) {
 9047:           if (!$correct[$i]) {
 9048:              $result.='<br /><span class="LC_error">'.
 9049:                       &mt('No correct result given for question "[_1]"!',
 9050:                           $env{'form.question:'.$i}).'</span>';
 9051:           }
 9052:        }
 9053:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
 9054:     }
 9055: # Start grading
 9056:     my $pcorrect=$env{'form.pcorrect'};
 9057:     my $pincorrect=$env{'form.pincorrect'};
 9058:     my $storecount=0;
 9059:     foreach my $key (keys(%env)) {
 9060:        my $user='';
 9061:        if ($key=~/^form\.student\:(.*)$/) {
 9062:           $user=$1;
 9063:        }
 9064:        if ($key=~/^form\.unknown\:(.*)$/) {
 9065:           my $id=$1;
 9066:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
 9067:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
 9068:           } elsif ($env{'form.multi'.$id}) {
 9069:              $user=$env{'form.multi'.$id};
 9070:           }
 9071:        }
 9072:        if ($user) { 
 9073:           my @answer=split(/\,/,$env{$key});
 9074:           my $sum=0;
 9075:           my $realnumber=$number;
 9076:           for (my $i=0;$i<$number;$i++) {
 9077:              if  ($correct[$i] eq '-') {
 9078:                 $realnumber--;
 9079:              } elsif ($answer[$i]) {
 9080:                 if ($gradingmechanism eq 'attendance') {
 9081:                    $sum+=$pcorrect;
 9082:                 } elsif ($correct[$i] eq '*') {
 9083:                    $sum+=$pcorrect;
 9084:                 } else {
 9085:                    if ($answer[$i] eq $correct[$i]) {
 9086:                       $sum+=$pcorrect;
 9087:                    } else {
 9088:                       $sum+=$pincorrect;
 9089:                    }
 9090:                 }
 9091:              }
 9092:           }
 9093:           my $ave=$sum/(100*$realnumber);
 9094: # Store
 9095:           my ($username,$domain)=split(/\:/,$user);
 9096:           my %grades=();
 9097:           $grades{"resource.$part.solved"}='correct_by_override';
 9098:           $grades{"resource.$part.awarded"}=$ave;
 9099:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 9100:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
 9101:                                                  $env{'request.course.id'},
 9102:                                                  $domain,$username);
 9103:           if ($returncode ne 'ok') {
 9104:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
 9105:           } else {
 9106:              $storecount++;
 9107:           }
 9108:        }
 9109:     }
 9110: # We are done
 9111:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
 9112:              '</td></tr></table>'."\n".
 9113:              '</td></tr></table><br /><br />'."\n";
 9114:     return $result;
 9115: }
 9116: 
 9117: sub navmap_errormsg {
 9118:     return '<div class="LC_error">'.
 9119:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
 9120:            &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>').
 9121:            '</div>';
 9122: }
 9123: 
 9124: sub startpage {
 9125:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag) = @_;
 9126:     unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
 9127:     $r->print(&Apache::loncommon::start_page('Grading',undef,
 9128:                                           {'bread_crumbs' => $crumbs}));
 9129:     unless ($nodisplayflag) {
 9130:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag));
 9131:     }
 9132: }
 9133: 
 9134: sub handler {
 9135:     my $request=$_[0];
 9136:     &reset_caches();
 9137:     if ($env{'browser.mathml'}) {
 9138: 	&Apache::loncommon::content_type($request,'text/xml');
 9139:     } else {
 9140: 	&Apache::loncommon::content_type($request,'text/html');
 9141:     }
 9142:     $request->send_http_header;
 9143:     return '' if $request->header_only;
 9144:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
 9145: 
 9146: # see what command we need to execute
 9147: 
 9148:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
 9149:     my $command=$commands[0];
 9150: 
 9151:     if ($#commands > 0) {
 9152: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
 9153:     }
 9154: 
 9155: # see what the symb is
 9156: 
 9157:     my $symb=$env{'form.symb'};
 9158:     unless ($symb) {
 9159:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
 9160:        $symb=&Apache::lonnet::symbread($url);
 9161:     }
 9162:     &Apache::lonenc::check_decrypt(\$symb);                             
 9163: 
 9164:     $ssi_error = 0;
 9165:     if ($symb eq '' && $command eq '') {
 9166: #
 9167: # Not called from a resource
 9168: #    
 9169: 
 9170:     } else {
 9171: 	&init_perm();
 9172: 	if ($command eq 'submission' && $perm{'vgr'}) {
 9173:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}]);
 9174: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
 9175: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
 9176:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
 9177:                                        {href=>'',text=>'Select student'}],1,1);
 9178: 	    &pickStudentPage($request,$symb);
 9179: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
 9180:             &startpage($request,$symb,
 9181:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
 9182:                                        {href=>'',text=>'Select student'},
 9183:                                        {href=>'',text=>'Grade student'}],1,1);
 9184: 	    &displayPage($request,$symb);
 9185: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
 9186:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
 9187:                                        {href=>'',text=>'Select student'},
 9188:                                        {href=>'',text=>'Grade student'},
 9189:                                        {href=>'',text=>'Store grades'}],1,1);
 9190: 	    &updateGradeByPage($request,$symb);
 9191: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
 9192:             &startpage($request,$symb,[{href=>'',text=>'...'},
 9193:                                        {href=>'',text=>'Modify grades'}]);
 9194: 	    &processGroup($request,$symb);
 9195: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
 9196:             &startpage($request,$symb);
 9197: 	    $request->print(&grading_menu($request,$symb));
 9198: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
 9199:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
 9200: 	    $request->print(&submit_options($request,$symb));
 9201:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
 9202:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}]);
 9203:             $request->print(&listStudents($request,$symb,'graded'));
 9204:         } elsif ($command eq 'table' && $perm{'vgr'}) {
 9205:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
 9206:             $request->print(&submit_options_table($request,$symb));
 9207:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
 9208:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
 9209:             $request->print(&submit_options_sequence($request,$symb));
 9210: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
 9211:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
 9212: 	    $request->print(&viewgrades($request,$symb));
 9213: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
 9214:             &startpage($request,$symb);
 9215: 	    $request->print(&processHandGrade($request,$symb));
 9216: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
 9217:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
 9218:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
 9219:                                                                              text=>"Modify grades"},
 9220:                                        {href=>'', text=>"Store grades"}]);
 9221: 	    $request->print(&editgrades($request,$symb));
 9222:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
 9223:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
 9224:             $request->print(&initialverifyreceipt($request,$symb));
 9225: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
 9226:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
 9227:                                        {href=>'',text=>'Verification Result'}]);
 9228: 	    $request->print(&verifyreceipt($request,$symb));
 9229:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
 9230:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
 9231:             $request->print(&process_clicker($request,$symb));
 9232:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
 9233:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
 9234:                                        {href=>'', text=>'Process clicker file'}]);
 9235:             $request->print(&process_clicker_file($request,$symb));
 9236:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
 9237:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
 9238:                                        {href=>'', text=>'Process clicker file'},
 9239:                                        {href=>'', text=>'Store grades'}]);
 9240:             $request->print(&assign_clicker_grades($request,$symb));
 9241: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
 9242:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9243: 	    $request->print(&upcsvScores_form($request,$symb));
 9244: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
 9245:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9246: 	    $request->print(&csvupload($request,$symb));
 9247: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
 9248:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9249: 	    $request->print(&csvuploadmap($request,$symb));
 9250: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
 9251: 	    if ($env{'form.associate'} ne 'Reverse Association') {
 9252:                 &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9253: 		$request->print(&csvuploadoptions($request,$symb));
 9254: 	    } else {
 9255: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
 9256: 		    $env{'form.upfile_associate'} = 'reverse';
 9257: 		} else {
 9258: 		    $env{'form.upfile_associate'} = 'forward';
 9259: 		}
 9260:                 &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9261: 		$request->print(&csvuploadmap($request,$symb));
 9262: 	    }
 9263: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
 9264:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9265: 	    $request->print(&csvuploadassign($request,$symb));
 9266: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
 9267:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9268: 	    $request->print(&scantron_selectphase($request,undef,$symb));
 9269:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
 9270:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9271:  	    $request->print(&scantron_do_warning($request,$symb));
 9272: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
 9273:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9274: 	    $request->print(&scantron_validate_file($request,$symb));
 9275: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
 9276:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9277: 	    $request->print(&scantron_process_students($request,$symb));
 9278:  	} elsif ($command eq 'scantronupload' && 
 9279:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9280: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9281:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9282:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
 9283:  	} elsif ($command eq 'scantronupload_save' &&
 9284:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9285: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9286:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9287:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
 9288:  	} elsif ($command eq 'scantron_download' &&
 9289: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 9290:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9291:  	    $request->print(&scantron_download_scantron_data($request,$symb));
 9292:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
 9293:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9294:             $request->print(&checkscantron_results($request,$symb));     
 9295: 	} elsif ($command) {
 9296:             &startpage($request,$symb);
 9297: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
 9298: 	}
 9299:     }
 9300:     if ($ssi_error) {
 9301: 	&ssi_print_error($request);
 9302:     }
 9303:     $request->print(&Apache::loncommon::end_page());
 9304:     &reset_caches();
 9305:     return '';
 9306: }
 9307: 
 9308: 1;
 9309: 
 9310: __END__;
 9311: 
 9312: 
 9313: =head1 NAME
 9314: 
 9315: Apache::grades
 9316: 
 9317: =head1 SYNOPSIS
 9318: 
 9319: Handles the viewing of grades.
 9320: 
 9321: This is part of the LearningOnline Network with CAPA project
 9322: described at http://www.lon-capa.org.
 9323: 
 9324: =head1 OVERVIEW
 9325: 
 9326: Do an ssi with retries:
 9327: While I'd love to factor out this with the vesrion in lonprintout,
 9328: 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
 9329: I'm not quite ready to invent (e.g. an ssi_with_retry object).
 9330: 
 9331: At least the logic that drives this has been pulled out into loncommon.
 9332: 
 9333: 
 9334: 
 9335: ssi_with_retries - Does the server side include of a resource.
 9336:                      if the ssi call returns an error we'll retry it up to
 9337:                      the number of times requested by the caller.
 9338:                      If we still have a proble, no text is appended to the
 9339:                      output and we set some global variables.
 9340:                      to indicate to the caller an SSI error occurred.  
 9341:                      All of this is supposed to deal with the issues described
 9342:                      in LonCAPA BZ 5631 see:
 9343:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
 9344:                      by informing the user that this happened.
 9345: 
 9346: Parameters:
 9347:   resource   - The resource to include.  This is passed directly, without
 9348:                interpretation to lonnet::ssi.
 9349:   form       - The form hash parameters that guide the interpretation of the resource
 9350:                
 9351:   retries    - Number of retries allowed before giving up completely.
 9352: Returns:
 9353:   On success, returns the rendered resource identified by the resource parameter.
 9354: Side Effects:
 9355:   The following global variables can be set:
 9356:    ssi_error                - If an unrecoverable error occurred this becomes true.
 9357:                               It is up to the caller to initialize this to false
 9358:                               if desired.
 9359:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
 9360:                               of the resource that could not be rendered by the ssi
 9361:                               call.
 9362:    ssi_error_message   - The error string fetched from the ssi response
 9363:                               in the event of an error.
 9364: 
 9365: 
 9366: =head1 HANDLER SUBROUTINE
 9367: 
 9368: ssi_with_retries()
 9369: 
 9370: =head1 SUBROUTINES
 9371: 
 9372: =over
 9373: 
 9374: =item scantron_get_correction() : 
 9375: 
 9376:    Builds the interface screen to interact with the operator to fix a
 9377:    specific error condition in a specific scanline
 9378: 
 9379:  Arguments:
 9380:     $r           - Apache request object
 9381:     $i           - number of the current scanline
 9382:     $scan_record - hash ref as returned from &scantron_parse_scanline()
 9383:     $scan_config - hash ref as returned from &get_scantron_config()
 9384:     $line        - full contents of the current scanline
 9385:     $error       - error condition, valid values are
 9386:                    'incorrectCODE', 'duplicateCODE',
 9387:                    'doublebubble', 'missingbubble',
 9388:                    'duplicateID', 'incorrectID'
 9389:     $arg         - extra information needed
 9390:        For errors:
 9391:          - duplicateID   - paper number that this studentID was seen before on
 9392:          - duplicateCODE - array ref of the paper numbers this CODE was
 9393:                            seen on before
 9394:          - incorrectCODE - current incorrect CODE 
 9395:          - doublebubble  - array ref of the bubble lines that have double
 9396:                            bubble errors
 9397:          - missingbubble - array ref of the bubble lines that have missing
 9398:                            bubble errors
 9399: 
 9400: =item  scantron_get_maxbubble() : 
 9401: 
 9402:    Arguments:
 9403:        $nav_error  - Reference to scalar which is a flag to indicate a
 9404:                       failure to retrieve a navmap object.
 9405:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
 9406:        calling routine should trap the error condition and display the warning
 9407:        found in &navmap_errormsg().
 9408: 
 9409:    Returns the maximum number of bubble lines that are expected to
 9410:    occur. Does this by walking the selected sequence rendering the
 9411:    resource and then checking &Apache::lonxml::get_problem_counter()
 9412:    for what the current value of the problem counter is.
 9413: 
 9414:    Caches the results to $env{'form.scantron_maxbubble'},
 9415:    $env{'form.scantron.bubble_lines.n'}, 
 9416:    $env{'form.scantron.first_bubble_line.n'} and
 9417:    $env{"form.scantron.sub_bubblelines.n"}
 9418:    which are the total number of bubble, lines, the number of bubble
 9419:    lines for response n and number of the first bubble line for response n,
 9420:    and a comma separated list of numbers of bubble lines for sub-questions
 9421:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
 9422: 
 9423: 
 9424: =item  scantron_validate_missingbubbles() : 
 9425: 
 9426:    Validates all scanlines in the selected file to not have any
 9427:     answers that don't have bubbles that have not been verified
 9428:     to be bubble free.
 9429: 
 9430: =item  scantron_process_students() : 
 9431: 
 9432:    Routine that does the actual grading of the bubble sheet information.
 9433: 
 9434:    The parsed scanline hash is added to %env 
 9435: 
 9436:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
 9437:    foreach resource , with the form data of
 9438: 
 9439: 	'submitted'     =>'scantron' 
 9440: 	'grade_target'  =>'grade',
 9441: 	'grade_username'=> username of student
 9442: 	'grade_domain'  => domain of student
 9443: 	'grade_courseid'=> of course
 9444: 	'grade_symb'    => symb of resource to grade
 9445: 
 9446:     This triggers a grading pass. The problem grading code takes care
 9447:     of converting the bubbled letter information (now in %env) into a
 9448:     valid submission.
 9449: 
 9450: =item  scantron_upload_scantron_data() :
 9451: 
 9452:     Creates the screen for adding a new bubble sheet data file to a course.
 9453: 
 9454: =item  scantron_upload_scantron_data_save() : 
 9455: 
 9456:    Adds a provided bubble information data file to the course if user
 9457:    has the correct privileges to do so. 
 9458: 
 9459: =item  valid_file() :
 9460: 
 9461:    Validates that the requested bubble data file exists in the course.
 9462: 
 9463: =item  scantron_download_scantron_data() : 
 9464: 
 9465:    Shows a list of the three internal files (original, corrected,
 9466:    skipped) for a specific bubble sheet data file that exists in the
 9467:    course.
 9468: 
 9469: =item  scantron_validate_ID() : 
 9470: 
 9471:    Validates all scanlines in the selected file to not have any
 9472:    invalid or underspecified student/employee IDs
 9473: 
 9474: =item navmap_errormsg() :
 9475: 
 9476:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
 9477:    Should be called whenever the request to instantiate a navmap object fails.  
 9478: 
 9479: =back
 9480: 
 9481: =cut

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