File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.612: download - view: text, annotated - select for diffs
Mon Apr 12 13:11:42 2010 UTC (14 years ago) by www
Branches: MAIN
CVS tags: HEAD
Fix call to scantron_selectphase

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.612 2010/04/12 13:11:42 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="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
  621: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
  622: 	'<input type="hidden" name="command" value="submission" />'."\n".
  623: 	'<input type="hidden" name="student" value="" />'."\n".
  624: 	'<input type="hidden" name="userdom" value="" />'."\n".
  625: 	'</form>'."\n";
  626:     return $jscript;
  627: }
  628: 
  629: 
  630: 
  631: # Given the score (as a number [0-1] and the weight) what is the final
  632: # point value? This function will round to the nearest tenth, third,
  633: # or quarter if one of those is within the tolerance of .00001.
  634: sub compute_points {
  635:     my ($score, $weight) = @_;
  636:     
  637:     my $tolerance = .00001;
  638:     my $points = $score * $weight;
  639: 
  640:     # Check for nearness to 1/x.
  641:     my $check_for_nearness = sub {
  642:         my ($factor) = @_;
  643:         my $num = ($points * $factor) + $tolerance;
  644:         my $floored_num = floor($num);
  645:         if ($num - $floored_num < 2 * $tolerance * $factor) {
  646:             return $floored_num / $factor;
  647:         }
  648:         return $points;
  649:     };
  650: 
  651:     $points = $check_for_nearness->(10);
  652:     $points = $check_for_nearness->(3);
  653:     $points = $check_for_nearness->(4);
  654:     
  655:     return $points;
  656: }
  657: 
  658: #------------------ End of general use routines --------------------
  659: 
  660: #
  661: # Find most similar essay
  662: #
  663: 
  664: sub most_similar {
  665:     my ($uname,$udom,$uessay,$old_essays)=@_;
  666: 
  667: # ignore spaces and punctuation
  668: 
  669:     $uessay=~s/\W+/ /gs;
  670: 
  671: # ignore empty submissions (occuring when only files are sent)
  672: 
  673:     unless ($uessay=~/\w+/s) { return ''; }
  674: 
  675: # these will be returned. Do not care if not at least 50 percent similar
  676:     my $limit=0.6;
  677:     my $sname='';
  678:     my $sdom='';
  679:     my $scrsid='';
  680:     my $sessay='';
  681: # go through all essays ...
  682:     foreach my $tkey (keys(%$old_essays)) {
  683: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
  684: # ... except the same student
  685:         next if (($tname eq $uname) && ($tdom eq $udom));
  686: 	my $tessay=$old_essays->{$tkey};
  687: 	$tessay=~s/\W+/ /gs;
  688: # String similarity gives up if not even limit
  689: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
  690: # Found one
  691: 	if ($tsimilar>$limit) {
  692: 	    $limit=$tsimilar;
  693: 	    $sname=$tname;
  694: 	    $sdom=$tdom;
  695: 	    $scrsid=$tcrsid;
  696: 	    $sessay=$old_essays->{$tkey};
  697: 	}
  698:     }
  699:     if ($limit>0.6) {
  700:        return ($sname,$sdom,$scrsid,$sessay,$limit);
  701:     } else {
  702:        return ('','','','',0);
  703:     }
  704: }
  705: 
  706: #-------------------------------------------------------------------
  707: 
  708: #------------------------------------ Receipt Verification Routines
  709: #
  710: 
  711: sub initialverifyreceipt {
  712:    my ($request,$symb) = @_;
  713:    &commonJSfunctions($request);
  714:    return '<form name="gradingMenu"><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
  715:         &Apache::lonnet::recprefix($env{'request.course.id'}).
  716:         '-<input type="text" name="receipt" size="4" />'.
  717:         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  718:         '<input type="hidden" name="command" value="verify" />'.
  719:         "</form>\n";
  720: }
  721: 
  722: #--- Check whether a receipt number is valid.---
  723: sub verifyreceipt {
  724:     my ($request,$symb)  = @_;
  725: 
  726:     my $courseid = $env{'request.course.id'};
  727:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
  728: 	$env{'form.receipt'};
  729:     $receipt     =~ s/[^\-\d]//g;
  730: 
  731:     my $title.=
  732: 	'<h3><span class="LC_info">'.
  733: 	&mt('Verifying Receipt Number [_1]',$receipt).
  734: 	'</span></h3>'."\n";
  735: 
  736:     my ($string,$contents,$matches) = ('','',0);
  737:     my (undef,undef,$fullname) = &getclasslist('all','0');
  738:     
  739:     my $receiptparts=0;
  740:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
  741: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
  742:     my $parts=['0'];
  743:     if ($receiptparts) {
  744:         my $res_error; 
  745:         ($parts)=&response_type($symb,\$res_error);
  746:         if ($res_error) {
  747:             return &navmap_errormsg();
  748:         } 
  749:     }
  750:     
  751:     my $header = 
  752: 	&Apache::loncommon::start_data_table().
  753: 	&Apache::loncommon::start_data_table_header_row().
  754: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
  755: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
  756: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
  757:     if ($receiptparts) {
  758: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
  759:     }
  760:     $header.=
  761: 	&Apache::loncommon::end_data_table_header_row();
  762: 
  763:     foreach (sort 
  764: 	     {
  765: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  766: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  767: 		 }
  768: 		 return $a cmp $b;
  769: 	     } (keys(%$fullname))) {
  770: 	my ($uname,$udom)=split(/\:/);
  771: 	foreach my $part (@$parts) {
  772: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
  773: 		$contents.=
  774: 		    &Apache::loncommon::start_data_table_row().
  775: 		    '<td>&nbsp;'."\n".
  776: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
  777: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
  778: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
  779: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
  780: 		if ($receiptparts) {
  781: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
  782: 		}
  783: 		$contents.= 
  784: 		    &Apache::loncommon::end_data_table_row()."\n";
  785: 		
  786: 		$matches++;
  787: 	    }
  788: 	}
  789:     }
  790:     if ($matches == 0) {
  791:         $string = $title
  792:                  .'<p class="LC_warning">'
  793:                  .&mt('No match found for the above receipt number.')
  794:                  .'</p>';
  795:     } else {
  796: 	$string = &jscriptNform($symb).$title.
  797: 	    '<p>'.
  798: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
  799: 	    '</p>'.
  800: 	    $header.
  801: 	    $contents.
  802: 	    &Apache::loncommon::end_data_table()."\n";
  803:     }
  804:     return $string.&show_grading_menu_form($symb);
  805: }
  806: 
  807: #--- This is called by a number of programs.
  808: #--- Called from the Grading Menu - View/Grade an individual student
  809: #--- Also called directly when one clicks on the subm button 
  810: #    on the problem page.
  811: sub listStudents {
  812:     my ($request,$symb) = @_;
  813: 
  814:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
  815:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
  816:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
  817:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
  818:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
  819:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
  820: 
  821:     my $result='<h3><span class="LC_info">&nbsp;'
  822: 	.&mt("$viewgrade 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="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
  923: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
  924: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  925: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
  926: 
  927:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
  928: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
  929:     } else {
  930:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
  931:                       .&Apache::lonhtmlcommon::StatusOptions(
  932:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
  933:                       .&Apache::lonhtmlcommon::row_closure();
  934:     }
  935: 
  936:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
  937:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
  938:                   .&Apache::lonhtmlcommon::row_closure(1)
  939:                   .&Apache::lonhtmlcommon::end_pick_box();
  940: 
  941:     $gradeTable .= '<p>'
  942:                   .&mt('To '.lc($viewgrade)." 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"
  943:                   .'<input type="hidden" name="command" value="processGroup" />'
  944:                   .'</p>';
  945: 
  946: # checkall buttons
  947:     $gradeTable.=&check_script('gradesub', 'stuinfo');
  948:     $gradeTable.='<input type="button" '."\n".
  949:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
  950:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
  951:     $gradeTable.=&check_buttons();
  952:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
  953:     $gradeTable.= &Apache::loncommon::start_data_table().
  954: 	&Apache::loncommon::start_data_table_header_row();
  955:     my $loop = 0;
  956:     while ($loop < 2) {
  957: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
  958: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
  959: 	if ($env{'form.showgrading'} eq 'yes' 
  960: 	    && $submitonly ne 'queued'
  961: 	    && $submitonly ne 'all') {
  962: 	    foreach my $part (sort(@$partlist)) {
  963: 		my $display_part=
  964: 		    &get_display_part((split(/_/,$part))[0],$symb);
  965: 		$gradeTable.=
  966: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
  967: 	    }
  968: 	} elsif ($submitonly eq 'queued') {
  969: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
  970: 	}
  971: 	$loop++;
  972: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
  973:     }
  974:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
  975: 
  976:     my $ctr = 0;
  977:     foreach my $student (sort 
  978: 			 {
  979: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  980: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  981: 			     }
  982: 			     return $a cmp $b;
  983: 			 }
  984: 			 (keys(%$fullname))) {
  985: 	my ($uname,$udom) = split(/:/,$student);
  986: 
  987: 	my %status = ();
  988: 
  989: 	if ($submitonly eq 'queued') {
  990: 	    my %queue_status = 
  991: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
  992: 							$udom,$uname);
  993: 	    next if (!defined($queue_status{'gradingqueue'}));
  994: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
  995: 	}
  996: 
  997: 	if ($env{'form.showgrading'} eq 'yes' 
  998: 	    && $submitonly ne 'queued'
  999: 	    && $submitonly ne 'all') {
 1000: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
 1001: 	    my $submitted = 0;
 1002: 	    my $graded = 0;
 1003: 	    my $incorrect = 0;
 1004: 	    foreach (keys(%status)) {
 1005: 		$submitted = 1 if ($status{$_} ne 'nothing');
 1006: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
 1007: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
 1008: 		
 1009: 		my ($foo,$partid,$foo1) = split(/\./,$_);
 1010: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 1011: 		    $submitted = 0;
 1012: 		    my ($part)=split(/\./,$partid);
 1013: 		    $gradeTable.='<input type="hidden" name="'.
 1014: 			$student.':'.$part.':submitted_by" value="'.
 1015: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
 1016: 		}
 1017: 	    }
 1018: 	    
 1019: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 1020: 				     $submitonly eq 'incorrect' ||
 1021: 				     $submitonly eq 'graded'));
 1022: 	    next if (!$graded && ($submitonly eq 'graded'));
 1023: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 1024: 	}
 1025: 
 1026: 	$ctr++;
 1027: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
 1028:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
 1029: 	if ( $perm{'vgr'} eq 'F' ) {
 1030: 	    if ($ctr%2 ==1) {
 1031: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
 1032: 	    }
 1033: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
 1034:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
 1035:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
 1036: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
 1037: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
 1038: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
 1039: 
 1040: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
 1041: 		foreach (sort(keys(%status))) {
 1042: 		    next if ($_ =~ /^resource.*?submitted_by$/);
 1043: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
 1044: 		}
 1045: 	    }
 1046: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
 1047: 	    if ($ctr%2 ==0) {
 1048: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
 1049: 	    }
 1050: 	}
 1051:     }
 1052:     if ($ctr%2 ==1) {
 1053: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
 1054: 	    if ($env{'form.showgrading'} eq 'yes' 
 1055: 		&& $submitonly ne 'queued'
 1056: 		&& $submitonly ne 'all') {
 1057: 		foreach (@$partlist) {
 1058: 		    $gradeTable.='<td>&nbsp;</td>';
 1059: 		}
 1060: 	    } elsif ($submitonly eq 'queued') {
 1061: 		$gradeTable.='<td>&nbsp;</td>';
 1062: 	    }
 1063: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
 1064:     }
 1065: 
 1066:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
 1067:         '<input type="button" '.
 1068:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
 1069:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
 1070:     if ($ctr == 0) {
 1071: 	my $num_students=(scalar(keys(%$fullname)));
 1072: 	if ($num_students eq 0) {
 1073: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
 1074: 	} else {
 1075: 	    my $submissions='submissions';
 1076: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
 1077: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
 1078: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
 1079: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
 1080: 		&mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
 1081: 		    $num_students).
 1082: 		'</span><br />';
 1083: 	}
 1084:     } elsif ($ctr == 1) {
 1085: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
 1086:     }
 1087:     $gradeTable.=&show_grading_menu_form($symb);
 1088:     $request->print($gradeTable);
 1089:     return '';
 1090: }
 1091: 
 1092: #---- Called from the listStudents routine
 1093: 
 1094: sub check_script {
 1095:     my ($form, $type)=@_;
 1096:     my $chkallscript= &Apache::lonhtmlcommon::scripttag('
 1097:     function checkall() {
 1098:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1099:             ele = document.forms.'.$form.'.elements[i];
 1100:             if (ele.name == "'.$type.'") {
 1101:             document.forms.'.$form.'.elements[i].checked=true;
 1102:                                        }
 1103:         }
 1104:     }
 1105: 
 1106:     function checksec() {
 1107:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1108:             ele = document.forms.'.$form.'.elements[i];
 1109:            string = document.forms.'.$form.'.chksec.value;
 1110:            if
 1111:           (ele.value.indexOf(":::SECTION"+string)>0) {
 1112:               document.forms.'.$form.'.elements[i].checked=true;
 1113:             }
 1114:         }
 1115:     }
 1116: 
 1117: 
 1118:     function uncheckall() {
 1119:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1120:             ele = document.forms.'.$form.'.elements[i];
 1121:             if (ele.name == "'.$type.'") {
 1122:             document.forms.'.$form.'.elements[i].checked=false;
 1123:                                        }
 1124:         }
 1125:     }
 1126: 
 1127: '."\n");
 1128:     return $chkallscript;
 1129: }
 1130: 
 1131: sub check_buttons {
 1132:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
 1133:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
 1134:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
 1135:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
 1136:     return $buttons;
 1137: }
 1138: 
 1139: #     Displays the submissions for one student or a group of students
 1140: sub processGroup {
 1141:     my ($request)  = shift;
 1142:     my $ctr        = 0;
 1143:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1144:     my $total      = scalar(@stuchecked)-1;
 1145: 
 1146:     foreach my $student (@stuchecked) {
 1147: 	my ($uname,$udom,$fullname) = split(/:/,$student);
 1148: 	$env{'form.student'}        = $uname;
 1149: 	$env{'form.userdom'}        = $udom;
 1150: 	$env{'form.fullname'}       = $fullname;
 1151: 	&submission($request,$ctr,$total);
 1152: 	$ctr++;
 1153:     }
 1154:     return '';
 1155: }
 1156: 
 1157: #------------------------------------------------------------------------------------
 1158: #
 1159: #-------------------------- Next few routines handles grading by student, essentially
 1160: #                           handles essay response type problem/part
 1161: #
 1162: #--- Javascript to handle the submission page functionality ---
 1163: sub sub_page_js {
 1164:     my $request = shift;
 1165: 	    my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 1166:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1167:     function updateRadio(formname,id,weight) {
 1168: 	var gradeBox = formname["GD_BOX"+id];
 1169: 	var radioButton = formname["RADVAL"+id];
 1170: 	var oldpts = formname["oldpts"+id].value;
 1171: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
 1172: 	gradeBox.value = pts;
 1173: 	var resetbox = false;
 1174: 	if (isNaN(pts) || pts < 0) {
 1175: 	    alert("$alertmsg"+pts);
 1176: 	    for (var i=0; i<radioButton.length; i++) {
 1177: 		if (radioButton[i].checked) {
 1178: 		    gradeBox.value = i;
 1179: 		    resetbox = true;
 1180: 		}
 1181: 	    }
 1182: 	    if (!resetbox) {
 1183: 		formtextbox.value = "";
 1184: 	    }
 1185: 	    return;
 1186: 	}
 1187: 
 1188: 	if (pts > weight) {
 1189: 	    var resp = confirm("You entered a value ("+pts+
 1190: 			       ") greater than the weight for the part. Accept?");
 1191: 	    if (resp == false) {
 1192: 		gradeBox.value = oldpts;
 1193: 		return;
 1194: 	    }
 1195: 	}
 1196: 
 1197: 	for (var i=0; i<radioButton.length; i++) {
 1198: 	    radioButton[i].checked=false;
 1199: 	    if (pts == i && pts != "") {
 1200: 		radioButton[i].checked=true;
 1201: 	    }
 1202: 	}
 1203: 	updateSelect(formname,id);
 1204: 	formname["stores"+id].value = "0";
 1205:     }
 1206: 
 1207:     function writeBox(formname,id,pts) {
 1208: 	var gradeBox = formname["GD_BOX"+id];
 1209: 	if (checkSolved(formname,id) == 'update') {
 1210: 	    gradeBox.value = pts;
 1211: 	} else {
 1212: 	    var oldpts = formname["oldpts"+id].value;
 1213: 	    gradeBox.value = oldpts;
 1214: 	    var radioButton = formname["RADVAL"+id];
 1215: 	    for (var i=0; i<radioButton.length; i++) {
 1216: 		radioButton[i].checked=false;
 1217: 		if (i == oldpts) {
 1218: 		    radioButton[i].checked=true;
 1219: 		}
 1220: 	    }
 1221: 	}
 1222: 	formname["stores"+id].value = "0";
 1223: 	updateSelect(formname,id);
 1224: 	return;
 1225:     }
 1226: 
 1227:     function clearRadBox(formname,id) {
 1228: 	if (checkSolved(formname,id) == 'noupdate') {
 1229: 	    updateSelect(formname,id);
 1230: 	    return;
 1231: 	}
 1232: 	gradeSelect = formname["GD_SEL"+id];
 1233: 	for (var i=0; i<gradeSelect.length; i++) {
 1234: 	    if (gradeSelect[i].selected) {
 1235: 		var selectx=i;
 1236: 	    }
 1237: 	}
 1238: 	var stores = formname["stores"+id];
 1239: 	if (selectx == stores.value) { return };
 1240: 	var gradeBox = formname["GD_BOX"+id];
 1241: 	gradeBox.value = "";
 1242: 	var radioButton = formname["RADVAL"+id];
 1243: 	for (var i=0; i<radioButton.length; i++) {
 1244: 	    radioButton[i].checked=false;
 1245: 	}
 1246: 	stores.value = selectx;
 1247:     }
 1248: 
 1249:     function checkSolved(formname,id) {
 1250: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
 1251: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
 1252: 	    if (!reply) {return "noupdate";}
 1253: 	    formname.overRideScore.value = 'yes';
 1254: 	}
 1255: 	return "update";
 1256:     }
 1257: 
 1258:     function updateSelect(formname,id) {
 1259: 	formname["GD_SEL"+id][0].selected = true;
 1260: 	return;
 1261:     }
 1262: 
 1263: //=========== Check that a point is assigned for all the parts  ============
 1264:     function checksubmit(formname,val,total,parttot) {
 1265: 	formname.gradeOpt.value = val;
 1266: 	if (val == "Save & Next") {
 1267: 	    for (i=0;i<=total;i++) {
 1268: 		for (j=0;j<parttot;j++) {
 1269: 		    var partid = formname["partid"+i+"_"+j].value;
 1270: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1271: 			var points = formname["GD_BOX"+i+"_"+partid].value;
 1272: 			if (points == "") {
 1273: 			    var name = formname["name"+i].value;
 1274: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
 1275: 			    var resp = confirm("You did not assign a score for "+studentID+
 1276: 					       ", part "+partid+". Continue?");
 1277: 			    if (resp == false) {
 1278: 				formname["GD_BOX"+i+"_"+partid].focus();
 1279: 				return false;
 1280: 			    }
 1281: 			}
 1282: 		    }
 1283: 		    
 1284: 		}
 1285: 	    }
 1286: 	    
 1287: 	}
 1288: 	if (val == "Grade Student") {
 1289: 	    formname.showgrading.value = "yes";
 1290: 	    if (formname.Status.value == "") {
 1291: 		formname.Status.value = "Active";
 1292: 	    }
 1293: 	    formname.studentNo.value = total;
 1294: 	}
 1295: 	formname.submit();
 1296:     }
 1297: 
 1298: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1299:     function checkSubmitPage(formname,total) {
 1300: 	noscore = new Array(100);
 1301: 	var ptr = 0;
 1302: 	for (i=1;i<total;i++) {
 1303: 	    var partid = formname["q_"+i].value;
 1304: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1305: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1306: 		var status = formname["solved"+i+"_"+partid].value;
 1307: 		if (points == "" && status != "correct_by_student") {
 1308: 		    noscore[ptr] = i;
 1309: 		    ptr++;
 1310: 		}
 1311: 	    }
 1312: 	}
 1313: 	if (ptr != 0) {
 1314: 	    var sense = ptr == 1 ? ": " : "s: ";
 1315: 	    var prolist = "";
 1316: 	    if (ptr == 1) {
 1317: 		prolist = noscore[0];
 1318: 	    } else {
 1319: 		var i = 0;
 1320: 		while (i < ptr-1) {
 1321: 		    prolist += noscore[i]+", ";
 1322: 		    i++;
 1323: 		}
 1324: 		prolist += "and "+noscore[i];
 1325: 	    }
 1326: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1327: 	    if (resp == false) {
 1328: 		return false;
 1329: 	    }
 1330: 	}
 1331: 
 1332: 	formname.submit();
 1333:     }
 1334: SUBJAVASCRIPT
 1335: }
 1336: 
 1337: #--- javascript for essay type problem --
 1338: sub sub_page_kw_js {
 1339:     my $request = shift;
 1340:     my $iconpath = $request->dir_config('lonIconsURL');
 1341:     &commonJSfunctions($request);
 1342: 
 1343:     my $inner_js_msg_central= &Apache::lonhtmlcommon::scripttag(<<INNERJS);
 1344:     function checkInput() {
 1345:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1346:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1347:       var usrctr = document.msgcenter.usrctr.value;
 1348:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1349:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1350: 
 1351:       var msgchk = "";
 1352:       if (document.msgcenter.subchk.checked) {
 1353:          msgchk = "msgsub,";
 1354:       }
 1355:       var includemsg = 0;
 1356:       for (var i=1; i<=nmsg; i++) {
 1357:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1358:           var frmmsg = document.msgcenter["msg"+i];
 1359:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1360:           var showflg = opener.document.SCORE["shownOnce"+i];
 1361:           showflg.value = "1";
 1362:           var chkbox = document.msgcenter["msgn"+i];
 1363:           if (chkbox.checked) {
 1364:              msgchk += "savemsg"+i+",";
 1365:              includemsg = 1;
 1366:           }
 1367:       }
 1368:       if (document.msgcenter.newmsgchk.checked) {
 1369:          msgchk += "newmsg"+usrctr;
 1370:          includemsg = 1;
 1371:       }
 1372:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1373:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1374:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1375:       includemsg.value = msgchk;
 1376: 
 1377:       self.close()
 1378: 
 1379:     }
 1380: INNERJS
 1381: 
 1382:     my $inner_js_highlight_central= &Apache::lonhtmlcommon::scripttag(<<INNERJS);
 1383:     function updateChoice(flag) {
 1384:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1385:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1386:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1387:       opener.document.SCORE.refresh.value = "on";
 1388:       if (opener.document.SCORE.keywords.value!=""){
 1389:          opener.document.SCORE.submit();
 1390:       }
 1391:       self.close()
 1392:     }
 1393: INNERJS
 1394: 
 1395:     my $start_page_msg_central = 
 1396:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1397: 				       {'js_ready'  => 1,
 1398: 					'only_body' => 1,
 1399: 					'bgcolor'   =>'#FFFFFF',});
 1400:     my $end_page_msg_central = 
 1401: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1402: 
 1403: 
 1404:     my $start_page_highlight_central = 
 1405:         &Apache::loncommon::start_page('Highlight Central',
 1406: 				       $inner_js_highlight_central,
 1407: 				       {'js_ready'  => 1,
 1408: 					'only_body' => 1,
 1409: 					'bgcolor'   =>'#FFFFFF',});
 1410:     my $end_page_highlight_central = 
 1411: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1412: 
 1413:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1414:     $docopen=~s/^document\.//;
 1415:     my $alertmsg = &mt('Please select a word or group of words from document and then click this link.');
 1416:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1417: 
 1418: //===================== Show list of keywords ====================
 1419:   function keywords(formname) {
 1420:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
 1421:     if (nret==null) return;
 1422:     formname.keywords.value = nret;
 1423: 
 1424:     if (formname.keywords.value != "") {
 1425: 	formname.refresh.value = "on";
 1426: 	formname.submit();
 1427:     }
 1428:     return;
 1429:   }
 1430: 
 1431: //===================== Script to view submitted by ==================
 1432:   function viewSubmitter(submitter) {
 1433:     document.SCORE.refresh.value = "on";
 1434:     document.SCORE.NCT.value = "1";
 1435:     document.SCORE.unamedom0.value = submitter;
 1436:     document.SCORE.submit();
 1437:     return;
 1438:   }
 1439: 
 1440: //===================== Script to add keyword(s) ==================
 1441:   function getSel() {
 1442:     if (document.getSelection) txt = document.getSelection();
 1443:     else if (document.selection) txt = document.selection.createRange().text;
 1444:     else return;
 1445:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1446:     if (cleantxt=="") {
 1447: 	alert("$alertmsg");
 1448: 	return;
 1449:     }
 1450:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
 1451:     if (nret==null) return;
 1452:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1453:     if (document.SCORE.keywords.value != "") {
 1454: 	document.SCORE.refresh.value = "on";
 1455: 	document.SCORE.submit();
 1456:     }
 1457:     return;
 1458:   }
 1459: 
 1460: //====================== Script for composing message ==============
 1461:    // preload images
 1462:    img1 = new Image();
 1463:    img1.src = "$iconpath/mailbkgrd.gif";
 1464:    img2 = new Image();
 1465:    img2.src = "$iconpath/mailto.gif";
 1466: 
 1467:   function msgCenter(msgform,usrctr,fullname) {
 1468:     var Nmsg  = msgform.savemsgN.value;
 1469:     savedMsgHeader(Nmsg,usrctr,fullname);
 1470:     var subject = msgform.msgsub.value;
 1471:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1472:     re = /msgsub/;
 1473:     var shwsel = "";
 1474:     if (re.test(msgchk)) { shwsel = "checked" }
 1475:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1476:     displaySubject(checkEntities(subject),shwsel);
 1477:     for (var i=1; i<=Nmsg; i++) {
 1478: 	var testmsg = "savemsg"+i+",";
 1479: 	re = new RegExp(testmsg,"g");
 1480: 	shwsel = "";
 1481: 	if (re.test(msgchk)) { shwsel = "checked" }
 1482: 	var message = document.SCORE["savemsg"+i].value;
 1483: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1484: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1485: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1486:     }
 1487:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1488:     shwsel = "";
 1489:     re = /newmsg/;
 1490:     if (re.test(msgchk)) { shwsel = "checked" }
 1491:     newMsg(newmsg,shwsel);
 1492:     msgTail(); 
 1493:     return;
 1494:   }
 1495: 
 1496:   function checkEntities(strx) {
 1497:     if (strx.length == 0) return strx;
 1498:     var orgStr = ["&", "<", ">", '"']; 
 1499:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1500:     var counter = 0;
 1501:     while (counter < 4) {
 1502: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1503: 	counter++;
 1504:     }
 1505:     return strx;
 1506:   }
 1507: 
 1508:   function strReplace(strx, orgStr, newStr) {
 1509:     return strx.split(orgStr).join(newStr);
 1510:   }
 1511: 
 1512:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1513:     var height = 70*Nmsg+250;
 1514:     var scrollbar = "no";
 1515:     if (height > 600) {
 1516: 	height = 600;
 1517: 	scrollbar = "yes";
 1518:     }
 1519:     var xpos = (screen.width-600)/2;
 1520:     xpos = (xpos < 0) ? '0' : xpos;
 1521:     var ypos = (screen.height-height)/2-30;
 1522:     ypos = (ypos < 0) ? '0' : ypos;
 1523: 
 1524:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
 1525:     pWin.focus();
 1526:     pDoc = pWin.document;
 1527:     pDoc.$docopen;
 1528:     pDoc.write('$start_page_msg_central');
 1529: 
 1530:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1531:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1532:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
 1533: 
 1534:     pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
 1535:     pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
 1536:     pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
 1537: }
 1538:     function displaySubject(msg,shwsel) {
 1539:     pDoc = pWin.document;
 1540:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1541:     pDoc.write("<td>Subject<\\/td>");
 1542:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1543:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
 1544: }
 1545: 
 1546:   function displaySavedMsg(ctr,msg,shwsel) {
 1547:     pDoc = pWin.document;
 1548:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1549:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
 1550:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1551:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
 1552: }
 1553: 
 1554:   function newMsg(newmsg,shwsel) {
 1555:     pDoc = pWin.document;
 1556:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1557:     pDoc.write("<td align=\\"center\\">New<\\/td>");
 1558:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1559:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
 1560: }
 1561: 
 1562:   function msgTail() {
 1563:     pDoc = pWin.document;
 1564:     pDoc.write("<\\/table>");
 1565:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1566:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1567:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onclick=\\"self.close()\\"><br /><br />");
 1568:     pDoc.write("<\\/form>");
 1569:     pDoc.write('$end_page_msg_central');
 1570:     pDoc.close();
 1571: }
 1572: 
 1573: //====================== Script for keyword highlight options ==============
 1574:   function kwhighlight() {
 1575:     var kwclr    = document.SCORE.kwclr.value;
 1576:     var kwsize   = document.SCORE.kwsize.value;
 1577:     var kwstyle  = document.SCORE.kwstyle.value;
 1578:     var redsel = "";
 1579:     var grnsel = "";
 1580:     var blusel = "";
 1581:     if (kwclr=="red")   {var redsel="checked"};
 1582:     if (kwclr=="green") {var grnsel="checked"};
 1583:     if (kwclr=="blue")  {var blusel="checked"};
 1584:     var sznsel = "";
 1585:     var sz1sel = "";
 1586:     var sz2sel = "";
 1587:     if (kwsize=="0")  {var sznsel="checked"};
 1588:     if (kwsize=="+1") {var sz1sel="checked"};
 1589:     if (kwsize=="+2") {var sz2sel="checked"};
 1590:     var synsel = "";
 1591:     var syisel = "";
 1592:     var sybsel = "";
 1593:     if (kwstyle=="")    {var synsel="checked"};
 1594:     if (kwstyle=="<i>") {var syisel="checked"};
 1595:     if (kwstyle=="<b>") {var sybsel="checked"};
 1596:     highlightCentral();
 1597:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
 1598:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
 1599:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
 1600:     highlightend();
 1601:     return;
 1602:   }
 1603: 
 1604:   function highlightCentral() {
 1605: //    if (window.hwdWin) window.hwdWin.close();
 1606:     var xpos = (screen.width-400)/2;
 1607:     xpos = (xpos < 0) ? '0' : xpos;
 1608:     var ypos = (screen.height-330)/2-30;
 1609:     ypos = (ypos < 0) ? '0' : ypos;
 1610: 
 1611:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1612:     hwdWin.focus();
 1613:     var hDoc = hwdWin.document;
 1614:     hDoc.$docopen;
 1615:     hDoc.write('$start_page_highlight_central');
 1616:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1617:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options<\\/span><\\/h3><br /><br />");
 1618: 
 1619:     hDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
 1620:     hDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
 1621:     hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
 1622:   }
 1623: 
 1624:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1625:     var hDoc = hwdWin.document;
 1626:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1627:     hDoc.write("<td align=\\"left\\">");
 1628:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
 1629:     hDoc.write("<td align=\\"left\\">");
 1630:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
 1631:     hDoc.write("<td align=\\"left\\">");
 1632:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
 1633:     hDoc.write("<\\/tr>");
 1634:   }
 1635: 
 1636:   function highlightend() { 
 1637:     var hDoc = hwdWin.document;
 1638:     hDoc.write("<\\/table>");
 1639:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1640:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onclick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
 1641:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onclick=\\"self.close()\\"><br /><br />");
 1642:     hDoc.write("<\\/form>");
 1643:     hDoc.write('$end_page_highlight_central');
 1644:     hDoc.close();
 1645:   }
 1646: 
 1647: SUBJAVASCRIPT
 1648: }
 1649: 
 1650: sub get_increment {
 1651:     my $increment = $env{'form.increment'};
 1652:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1653:         $increment != .1) {
 1654:         $increment = 1;
 1655:     }
 1656:     return $increment;
 1657: }
 1658: 
 1659: sub gradeBox_start {
 1660:     return (
 1661:         &Apache::loncommon::start_data_table()
 1662:        .&Apache::loncommon::start_data_table_header_row()
 1663:        .'<th>'.&mt('Part').'</th>'
 1664:        .'<th>'.&mt('Points').'</th>'
 1665:        .'<th>&nbsp;</th>'
 1666:        .'<th>'.&mt('Assign Grade').'</th>'
 1667:        .'<th>'.&mt('Weight').'</th>'
 1668:        .'<th>'.&mt('Grade Status').'</th>'
 1669:        .&Apache::loncommon::end_data_table_header_row()
 1670:     );
 1671: }
 1672: 
 1673: sub gradeBox_end {
 1674:     return (
 1675:         &Apache::loncommon::end_data_table()
 1676:     );
 1677: }
 1678: #--- displays the grading box, used in essay type problem and grading by page/sequence
 1679: sub gradeBox {
 1680:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 1681:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1682: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 1683:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 1684:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
 1685:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
 1686:     $wgt       = ($wgt > 0 ? $wgt : '1');
 1687:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 1688: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 1689:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 1690:     my $display_part= &get_display_part($partid,$symb);
 1691:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 1692: 				       [$partid]);
 1693:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 1694:     if ($last_resets{$partid}) {
 1695:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 1696:     }
 1697:     $result.=&Apache::loncommon::start_data_table_row();
 1698:     my $ctr = 0;
 1699:     my $thisweight = 0;
 1700:     my $increment = &get_increment();
 1701: 
 1702:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 1703:     while ($thisweight<=$wgt) {
 1704: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 1705:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 1706: 	    $thisweight.')" value="'.$thisweight.'" '.
 1707: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 1708: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 1709:         $thisweight += $increment;
 1710: 	$ctr++;
 1711:     }
 1712:     $radio.='</tr></table>';
 1713: 
 1714:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 1715: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 1716: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 1717: 	$wgt.')" /></td>'."\n";
 1718:     $line.='<td>/'.$wgt.' '.$wgtmsg.
 1719: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 1720: 	' </td>'."\n";
 1721:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
 1722: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 1723:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 1724: 	$line.='<option></option>'.
 1725: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
 1726:     } else {
 1727: 	$line.='<option selected="selected"></option>'.
 1728: 	    '<option value="excused" >'.&mt('excused').'</option>';
 1729:     }
 1730:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
 1731: 
 1732: 
 1733:     $result .= 
 1734: 	    '<td>'.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
 1735:     $result.=&Apache::loncommon::end_data_table_row();
 1736:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 1737: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 1738: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 1739: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 1740:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 1741:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 1742:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 1743:         $aggtries.'" />'."\n";
 1744:     my $res_error;
 1745:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
 1746:     if ($res_error) {
 1747:         return &navmap_errormsg();
 1748:     }
 1749:     return $result;
 1750: }
 1751: 
 1752: sub handback_box {
 1753:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error) = @_;
 1754:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
 1755:     my (@respids);
 1756:      my @part_response_id = &flatten_responseType($responseType);
 1757:     foreach my $part_response_id (@part_response_id) {
 1758:     	my ($part,$resp) = @{ $part_response_id };
 1759:         if ($part eq $partid) {
 1760:             push(@respids,$resp);
 1761:         }
 1762:     }
 1763:     my $result;
 1764:     foreach my $respid (@respids) {
 1765: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 1766: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 1767: 	next if (!@$files);
 1768: 	my $file_counter = 1;
 1769: 	foreach my $file (@$files) {
 1770: 	    if ($file =~ /\/portfolio\//) {
 1771:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 1772:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
 1773:     	        $file_disp = "$name.$ext";
 1774:     	        $file = $file_path.$file_disp;
 1775:     	        $result.=&mt('Return commented version of [_1] to student.',
 1776:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 1777:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 1778:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
 1779:     	        $result.='('.&mt('File will be uploaded when you click on Save &amp; Next below.').')<br />';
 1780:     	        $file_counter++;
 1781: 	    }
 1782: 	}
 1783:     }
 1784:     return $result;    
 1785: }
 1786: 
 1787: sub show_problem {
 1788:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 1789:     my $rendered;
 1790:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 1791:     &Apache::lonxml::remember_problem_counter();
 1792:     if ($mode eq 'both' or $mode eq 'text') {
 1793: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 1794: 						       $env{'request.course.id'},
 1795: 						       undef,\%form);
 1796:     }
 1797:     if ($removeform) {
 1798: 	$rendered=~s|<form(.*?)>||g;
 1799: 	$rendered=~s|</form>||g;
 1800: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 1801:     }
 1802:     my $companswer;
 1803:     if ($mode eq 'both' or $mode eq 'answer') {
 1804: 	&Apache::lonxml::restore_problem_counter();
 1805: 	$companswer=
 1806: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 1807: 						    $env{'request.course.id'},
 1808: 						    %form);
 1809:     }
 1810:     if ($removeform) {
 1811: 	$companswer=~s|<form(.*?)>||g;
 1812: 	$companswer=~s|</form>||g;
 1813: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 1814:     }
 1815:     $rendered=
 1816:         '<div class="LC_Box">'
 1817:        .'<h3 class="LC_hcell">'.&mt('View of the problem').'</h3>'
 1818:        .$rendered
 1819:        .'</div>';
 1820:     $companswer=
 1821:         '<div class="LC_Box">'
 1822:        .'<h3 class="LC_hcell">'.&mt('Correct answer').'</h3>'
 1823:        .$companswer
 1824:        .'</div>';
 1825:     my $result;
 1826:     if ($mode eq 'both') {
 1827:         $result=$rendered.$companswer;
 1828:     } elsif ($mode eq 'text') {
 1829:         $result=$rendered;
 1830:     } elsif ($mode eq 'answer') {
 1831:         $result=$companswer;
 1832:     }
 1833:     return $result;
 1834: }
 1835: 
 1836: sub files_exist {
 1837:     my ($r, $symb) = @_;
 1838:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1839: 
 1840:     foreach my $student (@students) {
 1841:         my ($uname,$udom,$fullname) = split(/:/,$student);
 1842:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 1843: 					      $udom,$uname);
 1844:         my ($string,$timestamp)= &get_last_submission(\%record);
 1845:         foreach my $submission (@$string) {
 1846:             my ($partid,$respid) =
 1847: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 1848:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 1849: 					   \%record);
 1850:             return 1 if (@$files);
 1851:         }
 1852:     }
 1853:     return 0;
 1854: }
 1855: 
 1856: sub download_all_link {
 1857:     my ($r,$symb) = @_;
 1858:     my $all_students = 
 1859: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 1860: 
 1861:     my $parts =
 1862: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 1863: 
 1864:     my $identifier = &Apache::loncommon::get_cgi_id();
 1865:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 1866:                              'cgi.'.$identifier.'.symb' => $symb,
 1867:                              'cgi.'.$identifier.'.parts' => $parts,});
 1868:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 1869: 	      &mt('Download All Submitted Documents').'</a>');
 1870:     return
 1871: }
 1872: 
 1873: sub build_section_inputs {
 1874:     my $section_inputs;
 1875:     if ($env{'form.section'} eq '') {
 1876:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 1877:     } else {
 1878:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 1879:         foreach my $section (@sections) {
 1880:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 1881:         }
 1882:     }
 1883:     return $section_inputs;
 1884: }
 1885: 
 1886: # --------------------------- show submissions of a student, option to grade 
 1887: sub submission {
 1888:     my ($request,$counter,$total,$symb) = @_;
 1889:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 1890:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 1891:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 1892:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 1893: 
 1894:     my $probtitle=&Apache::lonnet::gettitle($symb); 
 1895:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 1896: 
 1897:     if (!&canview($usec)) {
 1898: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
 1899: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
 1900: 			$env{'request.course.id'}.')</span>');
 1901: 	$request->print(&show_grading_menu_form($symb));
 1902: 	return;
 1903:     }
 1904: 
 1905:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 1906:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 1907:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 1908:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 1909:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1910: 	'" src="'.$request->dir_config('lonIconsURL').
 1911: 	'/check.gif" height="16" border="0" />';
 1912: 
 1913:     my %old_essays;
 1914:     # header info
 1915:     if ($counter == 0) {
 1916: 	&sub_page_js($request);
 1917: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
 1918: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
 1919: 	    &download_all_link($request, $symb);
 1920: 	}
 1921: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>');
 1922: 
 1923: 	# option to display problem, only once else it cause problems 
 1924:         # with the form later since the problem has a form.
 1925: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 1926: 	    my $mode;
 1927: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 1928: 		$mode='both';
 1929: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 1930: 		$mode='text';
 1931: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 1932: 		$mode='answer';
 1933: 	    }
 1934: 	    &Apache::lonxml::clear_problem_counter();
 1935: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 1936: 	}
 1937: 
 1938: 	# kwclr is the only variable that is guaranteed to be non blank 
 1939:         # if this subroutine has been called once.
 1940: 	my %keyhash = ();
 1941: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
 1942: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 1943: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 1944: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 1945: 
 1946: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 1947: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 1948: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 1949: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 1950: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 1951: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
 1952: 		$keyhash{$symb.'_subject'} : $probtitle;
 1953: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 1954: 	}
 1955: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 1956: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 1957: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 1958: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 1959: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 1960: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 1961: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 1962: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 1963: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 1964: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 1965: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 1966: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
 1967: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 1968: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 1969: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 1970: 			&build_section_inputs().
 1971: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 1972: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
 1973: 			'<input type="hidden" name="NCT"'.
 1974: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 1975: 	if ($env{'form.handgrade'} eq 'yes') {
 1976: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 1977: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 1978: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 1979: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
 1980: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 1981: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 1982: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 1983: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
 1984: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
 1985: 	    }
 1986: 	}
 1987: 	
 1988: 	my ($cts,$prnmsg) = (1,'');
 1989: 	while ($cts <= $env{'form.savemsgN'}) {
 1990: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 1991: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 1992: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 1993: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 1994: 		'" />'."\n".
 1995: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 1996: 	    $cts++;
 1997: 	}
 1998: 	$request->print($prnmsg);
 1999: 
 2000: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
 2001: #
 2002: # Print out the keyword options line
 2003: #
 2004: 	    $request->print(<<KEYWORDS);
 2005: &nbsp;<b>Keyword Options:</b>&nbsp;
 2006: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
 2007: <a href="#" onmousedown="javascript:getSel(); return false"
 2008:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
 2009: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
 2010: KEYWORDS
 2011: #
 2012: # Load the other essays for similarity check
 2013: #
 2014:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 2015: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 2016: 	    $apath=&escape($apath);
 2017: 	    $apath=~s/\W/\_/gs;
 2018: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
 2019:         }
 2020:     }
 2021: 
 2022: # This is where output for one specific student would start
 2023:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
 2024:     $request->print(
 2025:         "\n\n"
 2026:        .'<div class="LC_grade_show_user'.$add_class.'">'
 2027:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
 2028:        ."\n"
 2029:     );
 2030: 
 2031:     # Show additional functions if allowed
 2032:     if ($perm{'vgr'}) {
 2033:         $request->print(
 2034:             &Apache::loncommon::track_student_link(
 2035:                 &mt('View recent activity'),
 2036:                 $uname,$udom,'check')
 2037:            .' '
 2038:         );
 2039:     }
 2040:     if ($perm{'opa'}) {
 2041:         $request->print(
 2042:             &Apache::loncommon::pprmlink(
 2043:                 &mt('Set/Change parameters'),
 2044:                 $uname,$udom,$symb,'check'));
 2045:     }
 2046: 
 2047:     # Show Problem
 2048:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2049: 	my $mode;
 2050: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2051: 	    $mode='both';
 2052: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2053: 	    $mode='text';
 2054: 	} elsif ($env{'form.vAns'} eq 'all') {
 2055: 	    $mode='answer';
 2056: 	}
 2057: 	&Apache::lonxml::clear_problem_counter();
 2058: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2059:     }
 2060: 
 2061:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2062:     my $res_error;
 2063:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2064:     if ($res_error) {
 2065:         $request->print(&navmap_errormsg());
 2066:         return;
 2067:     }
 2068: 
 2069:     # Display student info
 2070:     $request->print(($counter == 0 ? '' : '<br />'));
 2071: 
 2072:     my $result='<div class="LC_Box">'
 2073:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
 2074:     $result.='<input type="hidden" name="name'.$counter.
 2075:              '" value="'.$env{'form.fullname'}.'" />'."\n";
 2076:     if ($env{'form.handgrade'} eq 'no') {
 2077:         $result.='<p class="LC_info">'
 2078:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
 2079:                 ."</p>\n";
 2080:     }
 2081: 
 2082:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
 2083:     my $fullname;
 2084:     my $col_fullnames = [];
 2085:     if ($env{'form.handgrade'} eq 'yes') {
 2086: 	(my $sub_result,$fullname,$col_fullnames)=
 2087: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2088: 				 $counter);
 2089: 	$result.=$sub_result;
 2090:     }
 2091:     $request->print($result."\n");
 2092: 
 2093:     # print student answer/submission
 2094:     # Options are (1) Handgraded submission only
 2095:     #             (2) Last submission, includes submission that is not handgraded 
 2096:     #                  (for multi-response type part)
 2097:     #             (3) Last submission plus the parts info
 2098:     #             (4) The whole record for this student
 2099:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
 2100: 	my ($string,$timestamp)= &get_last_submission(\%record);
 2101: 	
 2102: 	my $lastsubonly;
 2103: 
 2104:         if ($$timestamp eq '') {
 2105:             $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
 2106:         } else {
 2107:             $lastsubonly =
 2108:                 '<div class="LC_grade_submissions_body">'
 2109:                .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
 2110: 
 2111: 	    my %seenparts;
 2112: 	    my @part_response_id = &flatten_responseType($responseType);
 2113: 	    foreach my $part (@part_response_id) {
 2114: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
 2115: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
 2116: 
 2117: 		my ($partid,$respid) = @{ $part };
 2118: 		my $display_part=&get_display_part($partid,$symb);
 2119: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2120: 		    if (exists($seenparts{$partid})) { next; }
 2121: 		    $seenparts{$partid}=1;
 2122: 		    my $submitby='<b>Part:</b> '.$display_part.
 2123: 			' <b>Collaborative submission by:</b> '.
 2124: 			'<a href="javascript:viewSubmitter(\''.
 2125: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
 2126: 			'\');" target="_self">'.
 2127: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
 2128: 		    $request->print($submitby);
 2129: 		    next;
 2130: 		}
 2131: 		my $responsetype = $responseType->{$partid}->{$respid};
 2132: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
 2133:                     $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
 2134:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2135:                         ' <span class="LC_internal_info">'.
 2136:                         '('.&mt('Part ID: [_1]',$respid).')'.
 2137:                         '</span>&nbsp; &nbsp;'.
 2138: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
 2139: 		    next;
 2140: 		}
 2141: 		foreach my $submission (@$string) {
 2142: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2143: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2144: 		    my ($ressub,$hide,$subval) = split(/:/,$submission,3);
 2145: 		    # Similarity check
 2146: 		    my $similar='';
 2147: 		    if($env{'form.checkPlag'}){
 2148: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2149: 			    &most_similar($uname,$udom,$subval,\%old_essays);
 2150: 			if ($osim) {
 2151: 			    $osim=int($osim*100.0);
 2152: 			    my %old_course_desc = 
 2153: 				&Apache::lonnet::coursedescription($ocrsid,
 2154: 								   {'one_time' => 1});
 2155: 
 2156:                             if ($hide) {
 2157:                                 $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
 2158:                                          &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
 2159:                             } else {
 2160: 			        $similar="<hr /><h3><span class=\"LC_warning\">".
 2161: 				    &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
 2162: 				        $osim,
 2163: 				        &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
 2164: 				        $old_course_desc{'description'},
 2165: 				        $old_course_desc{'num'},
 2166: 				        $old_course_desc{'domain'}).
 2167: 				    '</span></h3><blockquote><i>'.
 2168: 				    &keywords_highlight($oessay).
 2169: 				    '</i></blockquote><hr />';
 2170:                             }
 2171: 			}
 2172: 		    }
 2173: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
 2174: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
 2175: 			($env{'form.lastSub'} eq 'hdgrade' && 
 2176: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
 2177: 			my $display_part=&get_display_part($partid,$symb);
 2178:                         $lastsubonly.='<div class="LC_grade_submission_part">'.
 2179:                             '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2180:                             ' <span class="LC_internal_info">'.
 2181:                             '('.&mt('Part ID: [_1]',$respid).')'.
 2182:                             '</span>&nbsp; &nbsp;';
 2183: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2184: 			if (@$files) {
 2185:                             if ($hide) {
 2186:                                 $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
 2187:                             } else {
 2188:                                 $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
 2189:                                 foreach my $file (@$files) {
 2190:                                     &Apache::lonnet::allowuploaded('/adm/grades',$file);
 2191:                                     $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" /> '.$file.'</a>';
 2192:                                 }
 2193:                             }
 2194: 			    $lastsubonly.='<br />';
 2195: 			}
 2196:                         if ($hide) {
 2197:                             $lastsubonly.='<b>'.&mt('Anonymous Survey').'</b>'; 
 2198:                         } else {
 2199: 			    $lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
 2200: 			        &cleanRecord($subval,$responsetype,$symb,$partid,
 2201: 					     $respid,\%record,$order,undef,$uname,$udom);
 2202:                         }
 2203: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2204: 			$lastsubonly.='</div>';
 2205: 		    }
 2206: 		}
 2207: 	    }
 2208: 	    $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
 2209: 	}
 2210: 	$request->print($lastsubonly);
 2211:    } elsif ($env{'form.lastSub'} eq 'datesub') {
 2212: #	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
 2213:     my ($parts,$handgrade,$responseType) = &response_type($symb);
 2214: 
 2215: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2216:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2217: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2218: 								 $env{'request.course.id'},
 2219: 								 $last,'.submission',
 2220: 								 'Apache::grades::keywords_highlight'));
 2221:     }
 2222: 
 2223:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2224: 	.$udom.'" />'."\n");
 2225:     # return if view submission with no grading option
 2226:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
 2227: 	my $toGrade.='<input type="button" value="Grade Student" '.
 2228: 	    'onclick="javascript:checksubmit(this.form,\'Grade Student\',\''
 2229: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
 2230: 	$toGrade.='</div>'."\n";
 2231: 	if (($env{'form.command'} eq 'submission') || 
 2232: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
 2233: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
 2234: 	}
 2235: 	$request->print($toGrade);
 2236: 	return;
 2237:     } else {
 2238: 	$request->print('</div>'."\n");
 2239:     }
 2240: 
 2241:     # essay grading message center
 2242:     if ($env{'form.handgrade'} eq 'yes') {
 2243: 	my $result='<div class="LC_grade_message_center">';
 2244:     
 2245: 	$result.='<div class="LC_grade_message_center_header">'.
 2246: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
 2247: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2248: 	my $msgfor = $givenn.' '.$lastname;
 2249: 	if (scalar(@$col_fullnames) > 0) {
 2250: 	    my $lastone = pop(@$col_fullnames);
 2251: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2252: 	}
 2253: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2254: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2255: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
 2256: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2257: 	    ',\''.$msgfor.'\');" target="_self">'.
 2258: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
 2259: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2260: 	    '<img src="'.$request->dir_config('lonIconsURL').
 2261: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
 2262: 	    '<br />&nbsp;('.
 2263: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
 2264: 	$result.='</div></div>';
 2265: 	$request->print($result);
 2266:     }
 2267: 
 2268:     my %seen = ();
 2269:     my @partlist;
 2270:     my @gradePartRespid;
 2271:     my @part_response_id = &flatten_responseType($responseType);
 2272:     $request->print(
 2273:         '<div class="LC_Box">'
 2274:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
 2275:     );
 2276:     $request->print(&gradeBox_start());
 2277:     foreach my $part_response_id (@part_response_id) {
 2278:     	my ($partid,$respid) = @{ $part_response_id };
 2279: 	my $part_resp = join('_',@{ $part_response_id });
 2280: 	next if ($seen{$partid} > 0);
 2281: 	$seen{$partid}++;
 2282: 	next if ($$handgrade{$part_resp} ne 'yes' 
 2283: 		 && $env{'form.lastSub'} eq 'hdgrade');
 2284: 	push(@partlist,$partid);
 2285: 	push(@gradePartRespid,$partid.'.'.$respid);
 2286: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2287:     }
 2288:     $request->print(&gradeBox_end()); # </div>
 2289:     $request->print('</div>');
 2290: 
 2291:     $request->print('<div class="LC_grade_info_links">');
 2292:     $request->print('</div>');
 2293: 
 2294:     $result='<input type="hidden" name="partlist'.$counter.
 2295: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2296:     $result.='<input type="hidden" name="gradePartRespid'.
 2297: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2298:     my $ctr = 0;
 2299:     while ($ctr < scalar(@partlist)) {
 2300: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2301: 	    $partlist[$ctr].'" />'."\n";
 2302: 	$ctr++;
 2303:     }
 2304:     $request->print($result.''."\n");
 2305: 
 2306: # Done with printing info for one student
 2307: 
 2308:     $request->print('</div>');#LC_grade_show_user
 2309: 
 2310: 
 2311:     # print end of form
 2312:     if ($counter == $total) {
 2313:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
 2314: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2315: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
 2316: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2317: 	my $ntstu ='<select name="NTSTU">'.
 2318: 	    '<option>1</option><option>2</option>'.
 2319: 	    '<option>3</option><option>5</option>'.
 2320: 	    '<option>7</option><option>10</option></select>'."\n";
 2321: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2322: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2323:         $endform.=&mt('[_1]student(s)',$ntstu);
 2324: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2325: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2326: 	    '<input type="button" value="'.&mt('Next').'" '.
 2327: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2328:         $endform.='<span class="LC_warning">'.
 2329:                   &mt('(Next and Previous (student) do not save the scores.)').
 2330:                   '</span>'."\n" ;
 2331:         $endform.="<input type='hidden' value='".&get_increment().
 2332:             "' name='increment' />";
 2333: 	$endform.='</td></tr></table></form>';
 2334: 	$endform.=&show_grading_menu_form($symb);
 2335: 	$request->print($endform);
 2336:     }
 2337:     return '';
 2338: }
 2339: 
 2340: sub check_collaborators {
 2341:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2342:     my ($result,@col_fullnames);
 2343:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2344:     foreach my $part (keys(%$handgrade)) {
 2345: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2346: 					'.maxcollaborators',
 2347: 					$symb,$udom,$uname);
 2348: 	next if ($ncol <= 0);
 2349: 	$part =~ s/\_/\./g;
 2350: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2351: 	my (@good_collaborators, @bad_collaborators);
 2352: 	foreach my $possible_collaborator
 2353: 	    (split(/,?\s+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2354: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2355: 	    next if ($possible_collaborator eq '');
 2356: 	    my ($co_name,$co_dom) = split(/\@|:/,$possible_collaborator);
 2357: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2358: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2359: 	    # Doing this grep allows 'fuzzy' specification
 2360: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2361: 			       keys(%$classlist));
 2362: 	    if (! scalar(@matches)) {
 2363: 		push(@bad_collaborators, $possible_collaborator);
 2364: 	    } else {
 2365: 		push(@good_collaborators, @matches);
 2366: 	    }
 2367: 	}
 2368: 	if (scalar(@good_collaborators) != 0) {
 2369: 	    $result.='<br />'.&mt('Collaborators: ');
 2370: 	    foreach my $name (@good_collaborators) {
 2371: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2372: 		push(@col_fullnames, $givenn.' '.$lastname);
 2373: 		$result.=$fullname->{$name}.'&nbsp; &nbsp; &nbsp;';
 2374: 	    }
 2375: 	    $result.='<br />'."\n";
 2376: 	    my ($part)=split(/\./,$part);
 2377: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2378: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2379: 		"\n";
 2380: 	}
 2381: 	if (scalar(@bad_collaborators) > 0) {
 2382: 	    $result.='<div class="LC_warning">';
 2383: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2384: 	    $result .= '</div>';
 2385: 	}         
 2386: 	if (scalar(@bad_collaborators > $ncol)) {
 2387: 	    $result .= '<div class="LC_warning">';
 2388: 	    $result .= &mt('This student has submitted too many '.
 2389: 		'collaborators.  Maximum is [_1].',$ncol);
 2390: 	    $result .= '</div>';
 2391: 	}
 2392:     }
 2393:     return ($result,$fullname,\@col_fullnames);
 2394: }
 2395: 
 2396: #--- Retrieve the last submission for all the parts
 2397: sub get_last_submission {
 2398:     my ($returnhash)=@_;
 2399:     my (@string,$timestamp,%lasthidden);
 2400:     if ($$returnhash{'version'}) {
 2401: 	my %lasthash=();
 2402: 	my ($version);
 2403: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2404: 	    foreach my $key (sort(split(/\:/,
 2405: 					$$returnhash{$version.':keys'}))) {
 2406: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2407: 		$timestamp = 
 2408: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2409: 	    }
 2410: 	}
 2411:         my %typeparts;
 2412:         my $showsurv = 
 2413:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
 2414:         foreach my $key (sort(keys(%lasthash))) {
 2415:             if ($key =~ /\.type$/) {
 2416:                 if (($lasthash{$key} eq 'anonsurvey') || 
 2417:                     ($lasthash{$key} eq 'anonsurveycred')) {
 2418:                     my ($ign,@parts) = split(/\./,$key);
 2419:                     pop(@parts);
 2420:                     unless ($showsurv) {
 2421:                         my $id = join(',',@parts);
 2422:                         $typeparts{$ign.'.'.$id} = $lasthash{$key};
 2423:                     }
 2424:                     delete($lasthash{$key});
 2425:                 }
 2426:             }
 2427:         }
 2428:         my @hidden = keys(%typeparts);
 2429: 	foreach my $key (keys(%lasthash)) {
 2430: 	    next if ($key !~ /\.submission$/);
 2431:             my $hide;
 2432:             if (@hidden) {
 2433:                 foreach my $id (@hidden) {
 2434:                     if ($key =~ /^\Q$id\E/) {
 2435:                         $hide = 1;
 2436:                         last;
 2437:                     }
 2438:                 }
 2439:             }
 2440: 	    my ($partid,$foo) = split(/submission$/,$key);
 2441: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
 2442: 		'<span class="LC_warning">Draft Copy</span> ' : '';
 2443: 	    push(@string, join(':', $key, $hide, $draft.$lasthash{$key}));
 2444: 	}
 2445:     }
 2446:     if (!@string) {
 2447: 	$string[0] =
 2448: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
 2449:     }
 2450:     return (\@string,\$timestamp);
 2451: }
 2452: 
 2453: #--- High light keywords, with style choosen by user.
 2454: sub keywords_highlight {
 2455:     my $string    = shift;
 2456:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2457:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2458:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2459:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2460:     foreach my $keyword (@keylist) {
 2461: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2462:     }
 2463:     return $string;
 2464: }
 2465: 
 2466: #--- Called from submission routine
 2467: sub processHandGrade {
 2468:     my ($request,$symb) = @_;
 2469:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2470:     my $button = $env{'form.gradeOpt'};
 2471:     my $ngrade = $env{'form.NCT'};
 2472:     my $ntstu  = $env{'form.NTSTU'};
 2473:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2474:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 2475: 
 2476:     if ($button eq 'Save & Next') {
 2477: 	my $ctr = 0;
 2478: 	while ($ctr < $ngrade) {
 2479: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 2480: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 2481: 	    if ($errorflag eq 'no_score') {
 2482: 		$ctr++;
 2483: 		next;
 2484: 	    }
 2485: 	    if ($errorflag eq 'not_allowed') {
 2486: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
 2487: 		$ctr++;
 2488: 		next;
 2489: 	    }
 2490: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 2491: 	    my ($subject,$message,$msgstatus) = ('','','');
 2492: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 2493:             my ($feedurl,$showsymb) =
 2494: 		&get_feedurl_and_symb($symb,$uname,$udom);
 2495: 	    my $messagetail;
 2496: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 2497: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 2498: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 2499: 		$subject.=' ['.$restitle.']';
 2500: 		my (@msgnum) = split(/,/,$includemsg);
 2501: 		foreach (@msgnum) {
 2502: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 2503: 		}
 2504: 		$message =&Apache::lonfeedback::clear_out_html($message);
 2505: 		if ($env{'form.withgrades'.$ctr}) {
 2506: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 2507: 		    $messagetail = " for <a href=\"".
 2508: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
 2509: 		}
 2510: 		$msgstatus = 
 2511:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 2512: 						     $message.$messagetail,
 2513:                                                      undef,$feedurl,undef,
 2514:                                                      undef,undef,$showsymb,
 2515:                                                      $restitle);
 2516: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
 2517: 				$msgstatus);
 2518: 	    }
 2519: 	    if ($env{'form.collaborator'.$ctr}) {
 2520: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 2521: 		foreach my $collabstr (@collabstrs) {
 2522: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 2523: 		    foreach my $collaborator (@collaborators) {
 2524: 			my ($errorflag,$pts,$wgt) = 
 2525: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 2526: 					   $env{'form.unamedom'.$ctr},$part);
 2527: 			if ($errorflag eq 'not_allowed') {
 2528: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 2529: 			    next;
 2530: 			} elsif ($message ne '') {
 2531: 			    my ($baseurl,$showsymb) = 
 2532: 				&get_feedurl_and_symb($symb,$collaborator,
 2533: 						      $udom);
 2534: 			    if ($env{'form.withgrades'.$ctr}) {
 2535: 				$messagetail = " for <a href=\"".
 2536:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
 2537: 			    }
 2538: 			    $msgstatus = 
 2539: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 2540: 			}
 2541: 		    }
 2542: 		}
 2543: 	    }
 2544: 	    $ctr++;
 2545: 	}
 2546:     }
 2547: 
 2548:     if ($env{'form.handgrade'} eq 'yes') {
 2549: 	# Keywords sorted in alphabatical order
 2550: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2551: 	my %keyhash = ();
 2552: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 2553: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 2554: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 2555: 	$env{'form.keywords'} = join(' ',@keywords);
 2556: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 2557: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 2558: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 2559: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 2560: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 2561: 
 2562: 	# message center - Order of message gets changed. Blank line is eliminated.
 2563: 	# New messages are saved in env for the next student.
 2564: 	# All messages are saved in nohist_handgrade.db
 2565: 	my ($ctr,$idx) = (1,1);
 2566: 	while ($ctr <= $env{'form.savemsgN'}) {
 2567: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 2568: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 2569: 		$idx++;
 2570: 	    }
 2571: 	    $ctr++;
 2572: 	}
 2573: 	$ctr = 0;
 2574: 	while ($ctr < $ngrade) {
 2575: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 2576: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2577: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2578: 		$idx++;
 2579: 	    }
 2580: 	    $ctr++;
 2581: 	}
 2582: 	$env{'form.savemsgN'} = --$idx;
 2583: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 2584: 	my $putresult = &Apache::lonnet::put
 2585: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 2586:     }
 2587:     # Called by Save & Refresh from Highlight Attribute Window
 2588:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 2589:     if ($env{'form.refresh'} eq 'on') {
 2590: 	my ($ctr,$total) = (0,0);
 2591: 	while ($ctr < $ngrade) {
 2592: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 2593: 	    $ctr++;
 2594: 	}
 2595: 	$env{'form.NTSTU'}=$ngrade;
 2596: 	$ctr = 0;
 2597: 	while ($ctr < $total) {
 2598: 	    my $processUser = $env{'form.unamedom'.$ctr};
 2599: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2600: 	    $env{'form.fullname'} = $$fullname{$processUser};
 2601: 	    &submission($request,$ctr,$total-1);
 2602: 	    $ctr++;
 2603: 	}
 2604: 	return '';
 2605:     }
 2606: 
 2607: # Go directly to grade student - from submission or link from chart page
 2608:     if ($button eq 'Grade Student') {
 2609: #	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
 2610: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
 2611: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2612: 	$env{'form.fullname'} = $$fullname{$processUser};
 2613: 	&submission($request,0,0);
 2614: 	return '';
 2615:     }
 2616: 
 2617:     # Get the next/previous one or group of students
 2618:     my $firststu = $env{'form.unamedom0'};
 2619:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 2620:     my $ctr = 2;
 2621:     while ($laststu eq '') {
 2622: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 2623: 	$ctr++;
 2624: 	$laststu = $firststu if ($ctr > $ngrade);
 2625:     }
 2626: 
 2627:     my (@parsedlist,@nextlist);
 2628:     my ($nextflg) = 0;
 2629:     foreach my $item (sort 
 2630: 	     {
 2631: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 2632: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 2633: 		 }
 2634: 		 return $a cmp $b;
 2635: 	     } (keys(%$fullname))) {
 2636: # FIXME: this is fishy, looks like the button label
 2637: 	if ($nextflg == 1 && $button =~ /Next$/) {
 2638: 	    push(@parsedlist,$item);
 2639: 	}
 2640: 	$nextflg = 1 if ($item eq $laststu);
 2641: 	if ($button eq 'Previous') {
 2642: 	    last if ($item eq $firststu);
 2643: 	    push(@parsedlist,$item);
 2644: 	}
 2645:     }
 2646:     $ctr = 0;
 2647: # FIXME: this is fishy, looks like the button label
 2648:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 2649:     my $res_error;
 2650:     my ($partlist) = &response_type($symb,\$res_error);
 2651:     if ($res_error) {
 2652:         $request->print(&navmap_errormsg());
 2653:         return;
 2654:     }
 2655:     foreach my $student (@parsedlist) {
 2656: 	my $submitonly=$env{'form.submitonly'};
 2657: 	my ($uname,$udom) = split(/:/,$student);
 2658: 	
 2659: 	if ($submitonly eq 'queued') {
 2660: 	    my %queue_status = 
 2661: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 2662: 							$udom,$uname);
 2663: 	    next if (!defined($queue_status{'gradingqueue'}));
 2664: 	}
 2665: 
 2666: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 2667: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2668: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 2669: 	    my $submitted = 0;
 2670: 	    my $ungraded = 0;
 2671: 	    my $incorrect = 0;
 2672: 	    foreach my $item (keys(%status)) {
 2673: 		$submitted = 1 if ($status{$item} ne 'nothing');
 2674: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 2675: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 2676: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 2677: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 2678: 		    $submitted = 0;
 2679: 		}
 2680: 	    }
 2681: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 2682: 				     $submitonly eq 'incorrect' ||
 2683: 				     $submitonly eq 'graded'));
 2684: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 2685: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 2686: 	}
 2687: 	push(@nextlist,$student) if ($ctr < $ntstu);
 2688: 	last if ($ctr == $ntstu);
 2689: 	$ctr++;
 2690:     }
 2691: 
 2692:     $ctr = 0;
 2693:     my $total = scalar(@nextlist)-1;
 2694: 
 2695:     foreach (sort(@nextlist)) {
 2696: 	my ($uname,$udom,$submitter) = split(/:/);
 2697: 	$env{'form.student'}  = $uname;
 2698: 	$env{'form.userdom'}  = $udom;
 2699: 	$env{'form.fullname'} = $$fullname{$_};
 2700: 	&submission($request,$ctr,$total);
 2701: 	$ctr++;
 2702:     }
 2703:     if ($total < 0) {
 2704: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
 2705: 	$the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
 2706: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
 2707: 	$the_end.=&show_grading_menu_form($symb);
 2708: 	$request->print($the_end);
 2709:     }
 2710:     return '';
 2711: }
 2712: 
 2713: #---- Save the score and award for each student, if changed
 2714: sub saveHandGrade {
 2715:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 2716:     my @version_parts;
 2717:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 2718: 					   $env{'request.course.id'});
 2719:     if (!&canmodify($usec)) { return('not_allowed'); }
 2720:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 2721:     my @parts_graded;
 2722:     my %newrecord  = ();
 2723:     my ($pts,$wgt) = ('','');
 2724:     my %aggregate = ();
 2725:     my $aggregateflag = 0;
 2726:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 2727:     foreach my $new_part (@parts) {
 2728: 	#collaborator ($submi may vary for different parts
 2729: 	if ($submitter && $new_part ne $part) { next; }
 2730: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 2731: 	if ($dropMenu eq 'excused') {
 2732: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 2733: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 2734: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 2735: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 2736: 		}
 2737: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 2738: 	    }
 2739: 	} elsif ($dropMenu eq 'reset status'
 2740: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 2741: 	    foreach my $key (keys(%record)) {
 2742: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 2743: 	    }
 2744: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2745: 		"$env{'user.name'}:$env{'user.domain'}";
 2746:             my $totaltries = $record{'resource.'.$part.'.tries'};
 2747: 
 2748:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 2749: 					       [$new_part]);
 2750:             my $aggtries =$totaltries;
 2751:             if ($last_resets{$new_part}) {
 2752:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 2753: 					   $new_part);
 2754:             }
 2755: 
 2756:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 2757:             if ($aggtries > 0) {
 2758:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 2759:                 $aggregateflag = 1;
 2760:             }
 2761: 	} elsif ($dropMenu eq '') {
 2762: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 2763: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 2764: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 2765: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 2766: 		next;
 2767: 	    }
 2768: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 2769: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 2770: 	    my $partial= $pts/$wgt;
 2771: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 2772: 		#do not update score for part if not changed.
 2773:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 2774: 		next;
 2775: 	    } else {
 2776: 	        push(@parts_graded,$new_part);
 2777: 	    }
 2778: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 2779: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 2780: 	    }
 2781: 	    my $reckey = 'resource.'.$new_part.'.solved';
 2782: 	    if ($partial == 0) {
 2783: 		if ($record{$reckey} ne 'incorrect_by_override') {
 2784: 		    $newrecord{$reckey} = 'incorrect_by_override';
 2785: 		}
 2786: 	    } else {
 2787: 		if ($record{$reckey} ne 'correct_by_override') {
 2788: 		    $newrecord{$reckey} = 'correct_by_override';
 2789: 		}
 2790: 	    }	    
 2791: 	    if ($submitter && 
 2792: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 2793: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 2794: 	    }
 2795: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2796: 		"$env{'user.name'}:$env{'user.domain'}";
 2797: 	}
 2798: 	# unless problem has been graded, set flag to version the submitted files
 2799: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 2800: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 2801: 	        $dropMenu eq 'reset status')
 2802: 	   {
 2803: 	    push(@version_parts,$new_part);
 2804: 	}
 2805:     }
 2806:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2807:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2808: 
 2809:     if (%newrecord) {
 2810:         if (@version_parts) {
 2811:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 2812:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 2813: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 2814: 	    foreach my $new_part (@version_parts) {
 2815: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 2816: 				$new_part,\%newrecord);
 2817: 	    }
 2818:         }
 2819: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 2820: 				$env{'request.course.id'},$domain,$stuname);
 2821: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 2822: 				     $cdom,$cnum,$domain,$stuname);
 2823:     }
 2824:     if ($aggregateflag) {
 2825:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 2826: 			      $cdom,$cnum);
 2827:     }
 2828:     return ('',$pts,$wgt);
 2829: }
 2830: 
 2831: sub check_and_remove_from_queue {
 2832:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 2833:     my @ungraded_parts;
 2834:     foreach my $part (@{$parts}) {
 2835: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 2836: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 2837: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 2838: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 2839: 		) {
 2840: 	    push(@ungraded_parts, $part);
 2841: 	}
 2842:     }
 2843:     if ( !@ungraded_parts ) {
 2844: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 2845: 					       $cnum,$domain,$stuname);
 2846:     }
 2847: }
 2848: 
 2849: sub handback_files {
 2850:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 2851:     my $portfolio_root = '/userfiles/portfolio';
 2852:     my $res_error;
 2853:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2854:     if ($res_error) {
 2855:         $request->print('<br />'.&navmap_errormsg().'<br />');
 2856:         return;
 2857:     }
 2858:     my @part_response_id = &flatten_responseType($responseType);
 2859:     foreach my $part_response_id (@part_response_id) {
 2860:     	my ($part_id,$resp_id) = @{ $part_response_id };
 2861: 	my $part_resp = join('_',@{ $part_response_id });
 2862:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
 2863:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
 2864:                 my $file_counter = 1;
 2865: 		my $file_msg;
 2866:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
 2867:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
 2868:                     my ($directory,$answer_file) = 
 2869:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
 2870:                     my ($answer_name,$answer_ver,$answer_ext) =
 2871: 		        &file_name_version_ext($answer_file);
 2872: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 2873:                     my $getpropath = 1;
 2874: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
 2875: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 2876:                     # fix file name
 2877:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 2878:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 2879:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
 2880:             	                                $save_file_name);
 2881:                     if ($result !~ m|^/uploaded/|) {
 2882:                         $request->print('<br /><span class="LC_error">'.
 2883:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 2884:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$file_counter).
 2885:                                         '</span>');
 2886:                     } else {
 2887:                         # mark the file as read only
 2888:                         my @files = ($save_file_name);
 2889:                         my @what = ($symb,$env{'request.course.id'},'handback');
 2890:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
 2891: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 2892: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 2893: 			}
 2894:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 2895: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
 2896: 
 2897:                     }
 2898:                     $request->print("<br />".$fname." will be the uploaded file name");
 2899:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
 2900:                     $file_counter++;
 2901:                 }
 2902: 		my $subject = "File Handed Back by Instructor ";
 2903: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
 2904: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
 2905: 		$message .= ' The returned file(s) are named: '. $file_msg;
 2906: 		$message .= " and can be found in your portfolio space.";
 2907: 		my ($feedurl,$showsymb) = 
 2908: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
 2909:                 my $restitle = &Apache::lonnet::gettitle($symb);
 2910: 		my $msgstatus = 
 2911:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
 2912: 			 ' (File Returned) ['.$restitle.']',$message,undef,
 2913:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
 2914:             }
 2915:         }
 2916:     return;
 2917: }
 2918: 
 2919: sub get_feedurl_and_symb {
 2920:     my ($symb,$uname,$udom) = @_;
 2921:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2922:     $url = &Apache::lonnet::clutter($url);
 2923:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 2924: 					$symb,$udom,$uname);
 2925:     if ($encrypturl =~ /^yes$/i) {
 2926: 	&Apache::lonenc::encrypted(\$url,1);
 2927: 	&Apache::lonenc::encrypted(\$symb,1);
 2928:     }
 2929:     return ($url,$symb);
 2930: }
 2931: 
 2932: sub get_submitted_files {
 2933:     my ($udom,$uname,$partid,$respid,$record) = @_;
 2934:     my @files;
 2935:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 2936:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 2937:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 2938:     	    push(@files,$file_url.$file);
 2939:         }
 2940:     }
 2941:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 2942:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 2943:     }
 2944:     return (\@files);
 2945: }
 2946: 
 2947: # ----------- Provides number of tries since last reset.
 2948: sub get_num_tries {
 2949:     my ($record,$last_reset,$part) = @_;
 2950:     my $timestamp = '';
 2951:     my $num_tries = 0;
 2952:     if ($$record{'version'}) {
 2953:         for (my $version=$$record{'version'};$version>=1;$version--) {
 2954:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 2955:                 $timestamp = $$record{$version.':timestamp'};
 2956:                 if ($timestamp > $last_reset) {
 2957:                     $num_tries ++;
 2958:                 } else {
 2959:                     last;
 2960:                 }
 2961:             }
 2962:         }
 2963:     }
 2964:     return $num_tries;
 2965: }
 2966: 
 2967: # ----------- Determine decrements required in aggregate totals 
 2968: sub decrement_aggs {
 2969:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 2970:     my %decrement = (
 2971:                         attempts => 0,
 2972:                         users => 0,
 2973:                         correct => 0
 2974:                     );
 2975:     $decrement{'attempts'} = $aggtries;
 2976:     if ($solvedstatus =~ /^correct/) {
 2977:         $decrement{'correct'} = 1;
 2978:     }
 2979:     if ($aggtries == $totaltries) {
 2980:         $decrement{'users'} = 1;
 2981:     }
 2982:     foreach my $type (keys(%decrement)) {
 2983:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 2984:     }
 2985:     return;
 2986: }
 2987: 
 2988: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 2989: sub get_last_resets {
 2990:     my ($symb,$courseid,$partids) =@_;
 2991:     my %last_resets;
 2992:     my $cdom = $env{'course.'.$courseid.'.domain'};
 2993:     my $cname = $env{'course.'.$courseid.'.num'};
 2994:     my @keys;
 2995:     foreach my $part (@{$partids}) {
 2996: 	push(@keys,"$symb\0$part\0resettime");
 2997:     }
 2998:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 2999: 				     $cdom,$cname);
 3000:     foreach my $part (@{$partids}) {
 3001: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 3002:     }
 3003:     return %last_resets;
 3004: }
 3005: 
 3006: # ----------- Handles creating versions for portfolio files as answers
 3007: sub version_portfiles {
 3008:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 3009:     my $version_parts = join('|',@$v_flag);
 3010:     my @returned_keys;
 3011:     my $parts = join('|', @$parts_graded);
 3012:     my $portfolio_root = '/userfiles/portfolio';
 3013:     foreach my $key (keys(%$record)) {
 3014:         my $new_portfiles;
 3015:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 3016:             my @versioned_portfiles;
 3017:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 3018:             foreach my $file (@portfiles) {
 3019:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 3020:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 3021: 		my ($answer_name,$answer_ver,$answer_ext) =
 3022: 		    &file_name_version_ext($answer_file);
 3023:                 my $getpropath = 1;    
 3024:                 my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
 3025:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 3026:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
 3027:                 if ($new_answer ne 'problem getting file') {
 3028:                     push(@versioned_portfiles, $directory.$new_answer);
 3029:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
 3030:                         [$directory.$new_answer],
 3031:                         [$symb,$env{'request.course.id'},'graded']);
 3032:                 }
 3033:             }
 3034:             $$record{$key} = join(',',@versioned_portfiles);
 3035:             push(@returned_keys,$key);
 3036:         }
 3037:     } 
 3038:     return (@returned_keys);   
 3039: }
 3040: 
 3041: sub get_next_version {
 3042:     my ($answer_name, $answer_ext, $dir_list) = @_;
 3043:     my $version;
 3044:     foreach my $row (@$dir_list) {
 3045:         my ($file) = split(/\&/,$row,2);
 3046:         my ($file_name,$file_version,$file_ext) =
 3047: 	    &file_name_version_ext($file);
 3048:         if (($file_name eq $answer_name) && 
 3049: 	    ($file_ext eq $answer_ext)) {
 3050:                 # gets here if filename and extension match, regardless of version
 3051:                 if ($file_version ne '') {
 3052:                 # a versioned file is found  so save it for later
 3053:                 if ($file_version > $version) {
 3054: 		    $version = $file_version;
 3055: 	        }
 3056:             }
 3057:         }
 3058:     } 
 3059:     $version ++;
 3060:     return($version);
 3061: }
 3062: 
 3063: sub version_selected_portfile {
 3064:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 3065:     my ($answer_name,$answer_ver,$answer_ext) =
 3066:         &file_name_version_ext($file_name);
 3067:     my $new_answer;
 3068:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 3069:     if($env{'form.copy'} eq '-1') {
 3070:         $new_answer = 'problem getting file';
 3071:     } else {
 3072:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 3073:         my $copy_result = &Apache::lonnet::finishuserfileupload(
 3074:                             $stu_name,$domain,'copy',
 3075: 		        '/portfolio'.$directory.$new_answer);
 3076:     }    
 3077:     return ($new_answer);
 3078: }
 3079: 
 3080: sub file_name_version_ext {
 3081:     my ($file)=@_;
 3082:     my @file_parts = split(/\./, $file);
 3083:     my ($name,$version,$ext);
 3084:     if (@file_parts > 1) {
 3085: 	$ext=pop(@file_parts);
 3086: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 3087: 	    $version=pop(@file_parts);
 3088: 	}
 3089: 	$name=join('.',@file_parts);
 3090:     } else {
 3091: 	$name=join('.',@file_parts);
 3092:     }
 3093:     return($name,$version,$ext);
 3094: }
 3095: 
 3096: #--------------------------------------------------------------------------------------
 3097: #
 3098: #-------------------------- Next few routines handles grading by section or whole class
 3099: #
 3100: #--- Javascript to handle grading by section or whole class
 3101: sub viewgrades_js {
 3102:     my ($request) = shift;
 3103: 
 3104:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3105:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
 3106:    function writePoint(partid,weight,point) {
 3107: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3108: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3109: 	if (point == "textval") {
 3110: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3111: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3112: 		alert("$alertmsg"+parseFloat(point));
 3113: 		var resetbox = false;
 3114: 		for (var i=0; i<radioButton.length; i++) {
 3115: 		    if (radioButton[i].checked) {
 3116: 			textbox.value = i;
 3117: 			resetbox = true;
 3118: 		    }
 3119: 		}
 3120: 		if (!resetbox) {
 3121: 		    textbox.value = "";
 3122: 		}
 3123: 		return;
 3124: 	    }
 3125: 	    if (parseFloat(point) > parseFloat(weight)) {
 3126: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3127: 				   ") greater than the weight for the part. Accept?");
 3128: 		if (resp == false) {
 3129: 		    textbox.value = "";
 3130: 		    return;
 3131: 		}
 3132: 	    }
 3133: 	    for (var i=0; i<radioButton.length; i++) {
 3134: 		radioButton[i].checked=false;
 3135: 		if (parseFloat(point) == i) {
 3136: 		    radioButton[i].checked=true;
 3137: 		}
 3138: 	    }
 3139: 
 3140: 	} else {
 3141: 	    textbox.value = parseFloat(point);
 3142: 	}
 3143: 	for (i=0;i<document.classgrade.total.value;i++) {
 3144: 	    var user = document.classgrade["ctr"+i].value;
 3145: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3146: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3147: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3148: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3149: 	    if (saveval != "correct") {
 3150: 		scorename.value = point;
 3151: 		if (selname[0].selected != true) {
 3152: 		    selname[0].selected = true;
 3153: 		}
 3154: 	    }
 3155: 	}
 3156: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3157:     }
 3158: 
 3159:     function writeRadText(partid,weight) {
 3160: 	var selval   = document.classgrade["SELVAL_"+partid];
 3161: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3162:         var override = document.classgrade["FORCE_"+partid].checked;
 3163: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3164: 	if (selval[1].selected || selval[2].selected) {
 3165: 	    for (var i=0; i<radioButton.length; i++) {
 3166: 		radioButton[i].checked=false;
 3167: 
 3168: 	    }
 3169: 	    textbox.value = "";
 3170: 
 3171: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3172: 		var user = document.classgrade["ctr"+i].value;
 3173: 		user = user.replace(new RegExp(':', 'g'),"_");
 3174: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3175: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3176: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3177: 		if ((saveval != "correct") || override) {
 3178: 		    scorename.value = "";
 3179: 		    if (selval[1].selected) {
 3180: 			selname[1].selected = true;
 3181: 		    } else {
 3182: 			selname[2].selected = true;
 3183: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3184: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3185: 		    }
 3186: 		}
 3187: 	    }
 3188: 	} else {
 3189: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3190: 		var user = document.classgrade["ctr"+i].value;
 3191: 		user = user.replace(new RegExp(':', 'g'),"_");
 3192: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3193: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3194: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3195: 		if ((saveval != "correct") || override) {
 3196: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3197: 		    selname[0].selected = true;
 3198: 		}
 3199: 	    }
 3200: 	}	    
 3201:     }
 3202: 
 3203:     function changeSelect(partid,user) {
 3204: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3205: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3206: 	var point  = textbox.value;
 3207: 	var weight = document.classgrade["weight_"+partid].value;
 3208: 
 3209: 	if (isNaN(point) || parseFloat(point) < 0) {
 3210: 	    alert("$alertmsg"+parseFloat(point));
 3211: 	    textbox.value = "";
 3212: 	    return;
 3213: 	}
 3214: 	if (parseFloat(point) > parseFloat(weight)) {
 3215: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3216: 			       ") greater than the weight of the part. Accept?");
 3217: 	    if (resp == false) {
 3218: 		textbox.value = "";
 3219: 		return;
 3220: 	    }
 3221: 	}
 3222: 	selval[0].selected = true;
 3223:     }
 3224: 
 3225:     function changeOneScore(partid,user) {
 3226: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3227: 	if (selval[1].selected || selval[2].selected) {
 3228: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3229: 	    if (selval[2].selected) {
 3230: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3231: 	    }
 3232:         }
 3233:     }
 3234: 
 3235:     function resetEntry(numpart) {
 3236: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3237: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3238: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3239: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3240: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3241: 	    for (var i=0; i<radioButton.length; i++) {
 3242: 		radioButton[i].checked=false;
 3243: 
 3244: 	    }
 3245: 	    textbox.value = "";
 3246: 	    selval[0].selected = true;
 3247: 
 3248: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3249: 		var user = document.classgrade["ctr"+i].value;
 3250: 		user = user.replace(new RegExp(':', 'g'),"_");
 3251: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3252: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3253: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3254: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3255: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3256: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3257: 		if (saveselval == "excused") {
 3258: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3259: 		} else {
 3260: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3261: 		}
 3262: 	    }
 3263: 	}
 3264:     }
 3265: 
 3266: VIEWJAVASCRIPT
 3267: }
 3268: 
 3269: #--- show scores for a section or whole class w/ option to change/update a score
 3270: sub viewgrades {
 3271:     my ($request,$symb) = @_;
 3272:     &viewgrades_js($request);
 3273: 
 3274:     #need to make sure we have the correct data for later EXT calls, 
 3275:     #thus invalidate the cache
 3276:     &Apache::lonnet::devalidatecourseresdata(
 3277:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3278:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3279:     &Apache::lonnet::clear_EXT_cache_status();
 3280: 
 3281:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3282: 
 3283:     #view individual student submission form - called using Javascript viewOneStudent
 3284:     $result.=&jscriptNform($symb);
 3285: 
 3286:     #beginning of class grading form
 3287:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3288:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3289: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3290: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3291: 	&build_section_inputs().
 3292: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 3293: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3294: 
 3295:     my ($common_header,$specific_header);
 3296:     if ($env{'form.section'} eq 'all') {
 3297: 	$common_header = &mt('Assign Common Grade to Class');
 3298:         $specific_header = &mt('Assign Grade to Specific Students in Class');
 3299:     } elsif ($env{'form.section'} eq 'none') {
 3300:         $common_header = &mt('Assign Common Grade to Students in no Section');
 3301: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
 3302:     } else {
 3303:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3304:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
 3305: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
 3306:     }
 3307:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
 3308:     #radio buttons/text box for assigning points for a section or class.
 3309:     #handles different parts of a problem
 3310:     my $res_error;
 3311:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3312:     if ($res_error) {
 3313:         return &navmap_errormsg();
 3314:     }
 3315:     my %weight = ();
 3316:     my $ctsparts = 0;
 3317:     my %seen = ();
 3318:     my @part_response_id = &flatten_responseType($responseType);
 3319:     foreach my $part_response_id (@part_response_id) {
 3320:     	my ($partid,$respid) = @{ $part_response_id };
 3321: 	my $part_resp = join('_',@{ $part_response_id });
 3322: 	next if $seen{$partid};
 3323: 	$seen{$partid}++;
 3324: 	my $handgrade=$$handgrade{$part_resp};
 3325: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 3326: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 3327: 
 3328: 	my $display_part=&get_display_part($partid,$symb);
 3329: 	my $radio.='<table border="0"><tr>';  
 3330: 	my $ctr = 0;
 3331: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 3332: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 3333: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 3334: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 3335: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 3336: 	    $ctr++;
 3337: 	}
 3338: 	$radio.='</tr></table>';
 3339: 	my $line = '<input type="text" name="TEXTVAL_'.
 3340: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
 3341: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 3342: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 3343: 	$line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
 3344: 	    'onchange="javascript:writeRadText(\''.$partid.'\','.
 3345: 		$weight{$partid}.')"> '.
 3346: 	    '<option selected="selected"> </option>'.
 3347: 	    '<option value="excused">'.&mt('excused').'</option>'.
 3348: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 3349: 	    '</select></td>'.
 3350:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 3351: 	$line.='<input type="hidden" name="partid_'.
 3352: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 3353: 	$line.='<input type="hidden" name="weight_'.
 3354: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 3355: 
 3356: 	$result.=
 3357: 	    &Apache::loncommon::start_data_table_row()."\n".
 3358: 	    '<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>'.
 3359: 	    &Apache::loncommon::end_data_table_row()."\n";
 3360: 	$ctsparts++;
 3361:     }
 3362:     $result.=&Apache::loncommon::end_data_table()."\n".
 3363: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 3364:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 3365: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
 3366: 
 3367:     #table listing all the students in a section/class
 3368:     #header of table
 3369:     $result.= '<h3>'.$specific_header.'</h3>'.
 3370:               &Apache::loncommon::start_data_table().
 3371: 	      &Apache::loncommon::start_data_table_header_row().
 3372: 	      '<th>'.&mt('No.').'</th>'.
 3373: 	      '<th>'.&nameUserString('header')."</th>\n";
 3374:     my $partserror;
 3375:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3376:     if ($partserror) {
 3377:         return &navmap_errormsg();
 3378:     }
 3379:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 3380:     my @partids = ();
 3381:     foreach my $part (@parts) {
 3382: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3383:         my $narrowtext = &mt('Tries');
 3384: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 3385: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 3386: 	my ($partid) = &split_part_type($part);
 3387:         push(@partids,$partid);
 3388: 	my $display_part=&get_display_part($partid,$symb);
 3389: 	if ($display =~ /^Partial Credit Factor/) {
 3390: 	    $result.='<th>'.
 3391: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
 3392: 		    $display_part,$weight{$partid}).'</th>'."\n";
 3393: 	    next;
 3394: 	    
 3395: 	} else {
 3396: 	    if ($display =~ /Problem Status/) {
 3397: 		my $grade_status_mt = &mt('Grade Status');
 3398: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 3399: 	    }
 3400: 	    my $part_mt = &mt('Part:');
 3401: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 3402: 	}
 3403: 
 3404: 	$result.='<th>'.$display.'</th>'."\n";
 3405:     }
 3406:     $result.=&Apache::loncommon::end_data_table_header_row();
 3407: 
 3408:     my %last_resets = 
 3409: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 3410: 
 3411:     #get info for each student
 3412:     #list all the students - with points and grade status
 3413:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3414:     my $ctr = 0;
 3415:     foreach (sort 
 3416: 	     {
 3417: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3418: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3419: 		 }
 3420: 		 return $a cmp $b;
 3421: 	     } (keys(%$fullname))) {
 3422: 	$ctr++;
 3423: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 3424: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
 3425:     }
 3426:     $result.=&Apache::loncommon::end_data_table();
 3427:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 3428:     $result.='<input type="button" value="'.&mt('Save').'" '.
 3429: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
 3430:     if (scalar(%$fullname) eq 0) {
 3431: 	my $colspan=3+scalar(@parts);
 3432: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3433:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 3434: 	$result='<span class="LC_warning">'.
 3435: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 3436: 	        $section_display, $stu_status).
 3437: 	    '</span>';
 3438:     }
 3439:     $result.=&show_grading_menu_form($symb);
 3440:     return $result;
 3441: }
 3442: 
 3443: #--- call by previous routine to display each student
 3444: sub viewstudentgrade {
 3445:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 3446:     my ($uname,$udom) = split(/:/,$student);
 3447:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 3448:     my %aggregates = (); 
 3449:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 3450: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
 3451: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
 3452: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 3453: 	'\');" target="_self">'.$fullname.'</a> '.
 3454: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 3455:     $student=~s/:/_/; # colon doen't work in javascript for names
 3456:     foreach my $apart (@$parts) {
 3457: 	my ($part,$type) = &split_part_type($apart);
 3458: 	my $score=$record{"resource.$part.$type"};
 3459:         $result.='<td align="center">';
 3460:         my ($aggtries,$totaltries);
 3461:         unless (exists($aggregates{$part})) {
 3462: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 3463: 
 3464: 	    $aggtries = $totaltries;
 3465:             if ($$last_resets{$part}) {  
 3466:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 3467: 					   $part);
 3468:             }
 3469:             $result.='<input type="hidden" name="'.
 3470:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 3471:             $result.='<input type="hidden" name="'.
 3472:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 3473:             $aggregates{$part} = 1;
 3474:         }
 3475: 	if ($type eq 'awarded') {
 3476: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 3477: 	    $result.='<input type="hidden" name="'.
 3478: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 3479: 	    $result.='<input type="text" name="'.
 3480: 		'GD_'.$student.'_'.$part.'_awarded" '.
 3481:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
 3482: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 3483: 	} elsif ($type eq 'solved') {
 3484: 	    my ($status,$foo)=split(/_/,$score,2);
 3485: 	    $status = 'nothing' if ($status eq '');
 3486: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 3487: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 3488: 	    $result.='&nbsp;<select name="'.
 3489: 		'GD_'.$student.'_'.$part.'_solved" '.
 3490:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 3491: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 3492: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 3493: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 3494: 	    $result.="</select>&nbsp;</td>\n";
 3495: 	} else {
 3496: 	    $result.='<input type="hidden" name="'.
 3497: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 3498: 		    "\n";
 3499: 	    $result.='<input type="text" name="'.
 3500: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 3501: 		'value="'.$score.'" size="4" /></td>'."\n";
 3502: 	}
 3503:     }
 3504:     $result.=&Apache::loncommon::end_data_table_row();
 3505:     return $result;
 3506: }
 3507: 
 3508: #--- change scores for all the students in a section/class
 3509: #    record does not get update if unchanged
 3510: sub editgrades {
 3511:     my ($request,$symb) = @_;
 3512: 
 3513:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3514:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 3515:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
 3516: 
 3517:     my $result= &Apache::loncommon::start_data_table().
 3518: 	&Apache::loncommon::start_data_table_header_row().
 3519: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 3520: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 3521:     my %scoreptr = (
 3522: 		    'correct'  =>'correct_by_override',
 3523: 		    'incorrect'=>'incorrect_by_override',
 3524: 		    'excused'  =>'excused',
 3525: 		    'ungraded' =>'ungraded_attempted',
 3526:                     'credited' =>'credit_attempted',
 3527: 		    'nothing'  => '',
 3528: 		    );
 3529:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 3530: 
 3531:     my (@partid);
 3532:     my %weight = ();
 3533:     my %columns = ();
 3534:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 3535: 
 3536:     my $partserror;
 3537:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3538:     if ($partserror) {
 3539:         return &navmap_errormsg();
 3540:     }
 3541:     my $header;
 3542:     while ($ctr < $env{'form.totalparts'}) {
 3543: 	my $partid = $env{'form.partid_'.$ctr};
 3544: 	push(@partid,$partid);
 3545: 	$weight{$partid} = $env{'form.weight_'.$partid};
 3546: 	$ctr++;
 3547:     }
 3548:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3549:     foreach my $partid (@partid) {
 3550: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 3551: 	    '<th align="center">'.&mt('New Score').'</th>';
 3552: 	$columns{$partid}=2;
 3553: 	foreach my $stores (@parts) {
 3554: 	    my ($part,$type) = &split_part_type($stores);
 3555: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 3556: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 3557: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 3558: 	    $display =~ s/\[Part: \Q$part\E\]//;
 3559:             my $narrowtext = &mt('Tries');
 3560: 	    $display =~ s/Number of Attempts/$narrowtext/;
 3561: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 3562: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 3563: 	    $columns{$partid}+=2;
 3564: 	}
 3565:     }
 3566:     foreach my $partid (@partid) {
 3567: 	my $display_part=&get_display_part($partid,$symb);
 3568: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 3569: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 3570: 	    '</th>';
 3571: 
 3572:     }
 3573:     $result .= &Apache::loncommon::end_data_table_header_row().
 3574: 	&Apache::loncommon::start_data_table_header_row().
 3575: 	$header.
 3576: 	&Apache::loncommon::end_data_table_header_row();
 3577:     my @noupdate;
 3578:     my ($updateCtr,$noupdateCtr) = (1,1);
 3579:     for ($i=0; $i<$env{'form.total'}; $i++) {
 3580: 	my $line;
 3581: 	my $user = $env{'form.ctr'.$i};
 3582: 	my ($uname,$udom)=split(/:/,$user);
 3583: 	my %newrecord;
 3584: 	my $updateflag = 0;
 3585: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 3586: 	my $usec=$classlist->{"$uname:$udom"}[5];
 3587: 	if (!&canmodify($usec)) {
 3588: 	    my $numcols=scalar(@partid)*4+2;
 3589: 	    push(@noupdate,
 3590: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
 3591: 		 &mt('Not allowed to modify student')."</span></td></tr>");
 3592: 	    next;
 3593: 	}
 3594:         my %aggregate = ();
 3595:         my $aggregateflag = 0;
 3596: 	$user=~s/:/_/; # colon doen't work in javascript for names
 3597: 	foreach (@partid) {
 3598: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 3599: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 3600: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 3601: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3602: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 3603: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 3604: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 3605: 	    my $score;
 3606: 	    if ($partial eq '') {
 3607: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3608: 	    } elsif ($partial > 0) {
 3609: 		$score = 'correct_by_override';
 3610: 	    } elsif ($partial == 0) {
 3611: 		$score = 'incorrect_by_override';
 3612: 	    }
 3613: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 3614: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 3615: 
 3616: 	    $newrecord{'resource.'.$_.'.regrader'}=
 3617: 		"$env{'user.name'}:$env{'user.domain'}";
 3618: 	    if ($dropMenu eq 'reset status' &&
 3619: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 3620: 		$newrecord{'resource.'.$_.'.tries'} = '';
 3621: 		$newrecord{'resource.'.$_.'.solved'} = '';
 3622: 		$newrecord{'resource.'.$_.'.award'} = '';
 3623: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 3624: 		$updateflag = 1;
 3625:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 3626:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 3627:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 3628:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 3629:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3630:                     $aggregateflag = 1;
 3631:                 }
 3632: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 3633: 		$updateflag = 1;
 3634: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 3635: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 3636: 		$rec_update++;
 3637: 	    }
 3638: 
 3639: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3640: 		'<td align="center">'.$awarded.
 3641: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 3642: 
 3643: 
 3644: 	    my $partid=$_;
 3645: 	    foreach my $stores (@parts) {
 3646: 		my ($part,$type) = &split_part_type($stores);
 3647: 		if ($part !~ m/^\Q$partid\E/) { next;}
 3648: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 3649: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 3650: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 3651: 		if ($awarded ne '' && $awarded ne $old_aw) {
 3652: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 3653: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3654: 		    $updateflag=1;
 3655: 		}
 3656: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3657: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 3658: 	    }
 3659: 	}
 3660: 	$line.="\n";
 3661: 
 3662: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3663: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3664: 
 3665: 	if ($updateflag) {
 3666: 	    $count++;
 3667: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 3668: 				    $udom,$uname);
 3669: 
 3670: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 3671: 					      $cnum,$udom,$uname)) {
 3672: 		# need to figure out if should be in queue.
 3673: 		my %record =  
 3674: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 3675: 					     $udom,$uname);
 3676: 		my $all_graded = 1;
 3677: 		my $none_graded = 1;
 3678: 		foreach my $part (@parts) {
 3679: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 3680: 			$all_graded = 0;
 3681: 		    } else {
 3682: 			$none_graded = 0;
 3683: 		    }
 3684: 		}
 3685: 
 3686: 		if ($all_graded || $none_graded) {
 3687: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 3688: 							   $symb,$cdom,$cnum,
 3689: 							   $udom,$uname);
 3690: 		}
 3691: 	    }
 3692: 
 3693: 	    $result.=&Apache::loncommon::start_data_table_row().
 3694: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 3695: 		&Apache::loncommon::end_data_table_row();
 3696: 	    $updateCtr++;
 3697: 	} else {
 3698: 	    push(@noupdate,
 3699: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 3700: 	    $noupdateCtr++;
 3701: 	}
 3702:         if ($aggregateflag) {
 3703:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3704: 				  $cdom,$cnum);
 3705:         }
 3706:     }
 3707:     if (@noupdate) {
 3708: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
 3709: 	my $numcols=scalar(@partid)*4+2;
 3710: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 3711: 	    '<td align="center" colspan="'.$numcols.'">'.
 3712: 	    &mt('No Changes Occurred For the Students Below').
 3713: 	    '</td>'.
 3714: 	    &Apache::loncommon::end_data_table_row();
 3715: 	foreach my $line (@noupdate) {
 3716: 	    $result.=
 3717: 		&Apache::loncommon::start_data_table_row().
 3718: 		$line.
 3719: 		&Apache::loncommon::end_data_table_row();
 3720: 	}
 3721:     }
 3722:     $result .= &Apache::loncommon::end_data_table().
 3723: 	&show_grading_menu_form($symb);
 3724:     my $msg = '<p><b>'.
 3725: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 3726: 	    $rec_update,$count).'</b><br />'.
 3727: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 3728: 	'</b></p>';
 3729:     return $title.$msg.$result;
 3730: }
 3731: 
 3732: sub split_part_type {
 3733:     my ($partstr) = @_;
 3734:     my ($temp,@allparts)=split(/_/,$partstr);
 3735:     my $type=pop(@allparts);
 3736:     my $part=join('_',@allparts);
 3737:     return ($part,$type);
 3738: }
 3739: 
 3740: #------------- end of section for handling grading by section/class ---------
 3741: #
 3742: #----------------------------------------------------------------------------
 3743: 
 3744: 
 3745: #----------------------------------------------------------------------------
 3746: #
 3747: #-------------------------- Next few routines handles grading by csv upload
 3748: #
 3749: #--- Javascript to handle csv upload
 3750: sub csvupload_javascript_reverse_associate {
 3751:     my $error1=&mt('You need to specify the username or the student/employee ID');
 3752:     my $error2=&mt('You need to specify at least one grading field');
 3753:   return(<<ENDPICK);
 3754:   function verify(vf) {
 3755:     var foundsomething=0;
 3756:     var founduname=0;
 3757:     var foundID=0;
 3758:     for (i=0;i<=vf.nfields.value;i++) {
 3759:       tw=eval('vf.f'+i+'.selectedIndex');
 3760:       if (i==0 && tw!=0) { foundID=1; }
 3761:       if (i==1 && tw!=0) { founduname=1; }
 3762:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 3763:     }
 3764:     if (founduname==0 && foundID==0) {
 3765: 	alert('$error1');
 3766: 	return;
 3767:     }
 3768:     if (foundsomething==0) {
 3769: 	alert('$error2');
 3770: 	return;
 3771:     }
 3772:     vf.submit();
 3773:   }
 3774:   function flip(vf,tf) {
 3775:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3776:     var i;
 3777:     for (i=0;i<=vf.nfields.value;i++) {
 3778:       //can not pick the same destination field for both name and domain
 3779:       if (((i ==0)||(i ==1)) && 
 3780:           ((tf==0)||(tf==1)) && 
 3781:           (i!=tf) &&
 3782:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3783:         eval('vf.f'+i+'.selectedIndex=0;')
 3784:       }
 3785:     }
 3786:   }
 3787: ENDPICK
 3788: }
 3789: 
 3790: sub csvupload_javascript_forward_associate {
 3791:     my $error1=&mt('You need to specify the username or the student/employee ID');
 3792:     my $error2=&mt('You need to specify at least one grading field');
 3793:   return(<<ENDPICK);
 3794:   function verify(vf) {
 3795:     var foundsomething=0;
 3796:     var founduname=0;
 3797:     var foundID=0;
 3798:     for (i=0;i<=vf.nfields.value;i++) {
 3799:       tw=eval('vf.f'+i+'.selectedIndex');
 3800:       if (tw==1) { foundID=1; }
 3801:       if (tw==2) { founduname=1; }
 3802:       if (tw>3) { foundsomething=1; }
 3803:     }
 3804:     if (founduname==0 && foundID==0) {
 3805: 	alert('$error1');
 3806: 	return;
 3807:     }
 3808:     if (foundsomething==0) {
 3809: 	alert('$error2');
 3810: 	return;
 3811:     }
 3812:     vf.submit();
 3813:   }
 3814:   function flip(vf,tf) {
 3815:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3816:     var i;
 3817:     //can not pick the same destination field twice
 3818:     for (i=0;i<=vf.nfields.value;i++) {
 3819:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3820:         eval('vf.f'+i+'.selectedIndex=0;')
 3821:       }
 3822:     }
 3823:   }
 3824: ENDPICK
 3825: }
 3826: 
 3827: sub csvuploadmap_header {
 3828:     my ($request,$symb,$datatoken,$distotal)= @_;
 3829:     my $javascript;
 3830:     if ($env{'form.upfile_associate'} eq 'reverse') {
 3831: 	$javascript=&csvupload_javascript_reverse_associate();
 3832:     } else {
 3833: 	$javascript=&csvupload_javascript_forward_associate();
 3834:     }
 3835: 
 3836:     my $result='';
 3837:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
 3838:     my $ignore=&mt('Ignore First Line');
 3839:     $symb = &Apache::lonenc::check_encrypt($symb);
 3840:     $request->print(<<ENDPICK);
 3841: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3842: <h3><span class="LC_info">Uploading Class Grades</span></h3>
 3843: $result
 3844: <hr />
 3845: <h3>Identify fields</h3>
 3846: Total number of records found in file: $distotal <hr />
 3847: Enter as many fields as you can. The system will inform you and bring you back
 3848: to this page if the data selected is insufficient to run your class.<hr />
 3849: <input type="button" value="Reverse Association" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 3850: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
 3851: <input type="hidden" name="associate"  value="" />
 3852: <input type="hidden" name="phase"      value="three" />
 3853: <input type="hidden" name="datatoken"  value="$datatoken" />
 3854: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 3855: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 3856: <input type="hidden" name="upfile_associate" 
 3857:                                        value="$env{'form.upfile_associate'}" />
 3858: <input type="hidden" name="symb"       value="$symb" />
 3859: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 3860: <input type="hidden" name="command"    value="csvuploadoptions" />
 3861: <hr />
 3862: ENDPICK
 3863:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
 3864:     return '';
 3865: 
 3866: }
 3867: 
 3868: sub csvupload_fields {
 3869:     my ($symb,$errorref) = @_;
 3870:     my (@parts) = &getpartlist($symb,$errorref);
 3871:     if (ref($errorref)) {
 3872:         if ($$errorref) {
 3873:             return;
 3874:         }
 3875:     }
 3876: 
 3877:     my @fields=(['ID','Student/Employee ID'],
 3878: 		['username','Student Username'],
 3879: 		['domain','Student Domain']);
 3880:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3881:     foreach my $part (sort(@parts)) {
 3882: 	my @datum;
 3883: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3884: 	my $name=$part;
 3885: 	if  (!$display) { $display = $name; }
 3886: 	@datum=($name,$display);
 3887: 	if ($name=~/^stores_(.*)_awarded/) {
 3888: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 3889: 	}
 3890: 	push(@fields,\@datum);
 3891:     }
 3892:     return (@fields);
 3893: }
 3894: 
 3895: sub csvuploadmap_footer {
 3896:     my ($request,$i,$keyfields) =@_;
 3897:     $request->print(<<ENDPICK);
 3898: </table>
 3899: <input type="hidden" name="nfields" value="$i" />
 3900: <input type="hidden" name="keyfields" value="$keyfields" />
 3901: <input type="button" onclick="javascript:verify(this.form)" value="Assign Grades" /><br />
 3902: </form>
 3903: ENDPICK
 3904: }
 3905: 
 3906: sub checkforfile_js {
 3907:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 3908:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
 3909:     function checkUpload(formname) {
 3910: 	if (formname.upfile.value == "") {
 3911: 	    alert("$alertmsg");
 3912: 	    return false;
 3913: 	}
 3914: 	formname.submit();
 3915:     }
 3916: CSVFORMJS
 3917:     return $result;
 3918: }
 3919: 
 3920: sub upcsvScores_form {
 3921:     my ($request,$symb) = @_;
 3922:     if (!$symb) {return '';}
 3923:     my $result=&checkforfile_js();
 3924:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 3925:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 3926:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource.').
 3927: 	'</b></td></tr>'."\n";
 3928:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
 3929:     my $upload=&mt("Upload Scores");
 3930:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 3931:     my $ignore=&mt('Ignore First Line');
 3932:     $symb = &Apache::lonenc::check_encrypt($symb);
 3933:     $result.=<<ENDUPFORM;
 3934: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3935: <input type="hidden" name="symb" value="$symb" />
 3936: <input type="hidden" name="command" value="csvuploadmap" />
 3937: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 3938: $upfile_select
 3939: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 3940: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
 3941: </form>
 3942: ENDUPFORM
 3943:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 3944:                            &mt("How do I create a CSV file from a spreadsheet"))
 3945:     .'</td></tr></table>'."\n";
 3946:     $result.='</td></tr></table><br /><br />'."\n";
 3947:     $result.=&show_grading_menu_form($symb);
 3948:     return $result;
 3949: }
 3950: 
 3951: 
 3952: sub csvuploadmap {
 3953:     my ($request,$symb)= @_;
 3954:     if (!$symb) {return '';}
 3955: 
 3956:     my $datatoken;
 3957:     if (!$env{'form.datatoken'}) {
 3958: 	$datatoken=&Apache::loncommon::upfile_store($request);
 3959:     } else {
 3960: 	$datatoken=$env{'form.datatoken'};
 3961: 	&Apache::loncommon::load_tmp_file($request);
 3962:     }
 3963:     my @records=&Apache::loncommon::upfile_record_sep();
 3964:     if ($env{'form.noFirstLine'}) { shift(@records); }
 3965:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 3966:     my ($i,$keyfields);
 3967:     if (@records) {
 3968:         my $fieldserror;
 3969: 	my @fields=&csvupload_fields($symb,\$fieldserror);
 3970:         if ($fieldserror) {
 3971:             $request->print(&navmap_errormsg());
 3972:             return;
 3973:         }
 3974: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 3975: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 3976: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 3977: 							  \@fields);
 3978: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 3979: 	    chop($keyfields);
 3980: 	} else {
 3981: 	    unshift(@fields,['none','']);
 3982: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 3983: 							    \@fields);
 3984:             foreach my $rec (@records) {
 3985:                 my %temp = &Apache::loncommon::record_sep($rec);
 3986:                 if (%temp) {
 3987:                     $keyfields=join(',',sort(keys(%temp)));
 3988:                     last;
 3989:                 }
 3990:             }
 3991: 	}
 3992:     }
 3993:     &csvuploadmap_footer($request,$i,$keyfields);
 3994:     $request->print(&show_grading_menu_form($symb));
 3995: 
 3996:     return '';
 3997: }
 3998: 
 3999: sub csvuploadoptions {
 4000:     my ($request,$symb)= @_;
 4001:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
 4002:     my $ignore=&mt('Ignore First Line');
 4003:     $request->print(<<ENDPICK);
 4004: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4005: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
 4006: <input type="hidden" name="command"    value="csvuploadassign" />
 4007: <!--
 4008: <p>
 4009: <label>
 4010:    <input type="checkbox" name="show_full_results" />
 4011:    Show a table of all changes
 4012: </label>
 4013: </p>
 4014: -->
 4015: <p>
 4016: <label>
 4017:    <input type="checkbox" name="overwite_scores" checked="checked" />
 4018:    Overwrite any existing score
 4019: </label>
 4020: </p>
 4021: ENDPICK
 4022:     my %fields=&get_fields();
 4023:     if (!defined($fields{'domain'})) {
 4024: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 4025: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
 4026:     }
 4027:     foreach my $key (sort(keys(%env))) {
 4028: 	if ($key !~ /^form\.(.*)$/) { next; }
 4029: 	my $cleankey=$1;
 4030: 	if ($cleankey eq 'command') { next; }
 4031: 	$request->print('<input type="hidden" name="'.$cleankey.
 4032: 			'"  value="'.$env{$key}.'" />'."\n");
 4033:     }
 4034:     # FIXME do a check for any duplicated user ids...
 4035:     # FIXME do a check for any invalid user ids?...
 4036:     $request->print('<input type="submit" value="Assign Grades" /><br />
 4037: <hr /></form>'."\n");
 4038:     $request->print(&show_grading_menu_form($symb));
 4039:     return '';
 4040: }
 4041: 
 4042: sub get_fields {
 4043:     my %fields;
 4044:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 4045:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 4046: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 4047: 	    if ($env{'form.f'.$i} ne 'none') {
 4048: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 4049: 	    }
 4050: 	} else {
 4051: 	    if ($env{'form.f'.$i} ne 'none') {
 4052: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 4053: 	    }
 4054: 	}
 4055:     }
 4056:     return %fields;
 4057: }
 4058: 
 4059: sub csvuploadassign {
 4060:     my ($request,$symb)= @_;
 4061:     if (!$symb) {return '';}
 4062:     my $error_msg = '';
 4063:     &Apache::loncommon::load_tmp_file($request);
 4064:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 4065:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
 4066:     my %fields=&get_fields();
 4067:     $request->print('<h3>Assigning Grades</h3>');
 4068:     my $courseid=$env{'request.course.id'};
 4069:     my ($classlist) = &getclasslist('all',0);
 4070:     my @notallowed;
 4071:     my @skipped;
 4072:     my $countdone=0;
 4073:     foreach my $grade (@gradedata) {
 4074: 	my %entries=&Apache::loncommon::record_sep($grade);
 4075: 	my $domain;
 4076: 	if ($entries{$fields{'domain'}}) {
 4077: 	    $domain=$entries{$fields{'domain'}};
 4078: 	} else {
 4079: 	    $domain=$env{'form.default_domain'};
 4080: 	}
 4081: 	$domain=~s/\s//g;
 4082: 	my $username=$entries{$fields{'username'}};
 4083: 	$username=~s/\s//g;
 4084: 	if (!$username) {
 4085: 	    my $id=$entries{$fields{'ID'}};
 4086: 	    $id=~s/\s//g;
 4087: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 4088: 	    $username=$ids{$id};
 4089: 	}
 4090: 	if (!exists($$classlist{"$username:$domain"})) {
 4091: 	    my $id=$entries{$fields{'ID'}};
 4092: 	    $id=~s/\s//g;
 4093: 	    if ($id) {
 4094: 		push(@skipped,"$id:$domain");
 4095: 	    } else {
 4096: 		push(@skipped,"$username:$domain");
 4097: 	    }
 4098: 	    next;
 4099: 	}
 4100: 	my $usec=$classlist->{"$username:$domain"}[5];
 4101: 	if (!&canmodify($usec)) {
 4102: 	    push(@notallowed,"$username:$domain");
 4103: 	    next;
 4104: 	}
 4105: 	my %points;
 4106: 	my %grades;
 4107: 	foreach my $dest (keys(%fields)) {
 4108: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 4109: 		$dest eq 'domain') { next; }
 4110: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 4111: 	    if ($dest=~/stores_(.*)_points/) {
 4112: 		my $part=$1;
 4113: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 4114: 					      $symb,$domain,$username);
 4115:                 if ($wgt) {
 4116:                     $entries{$fields{$dest}}=~s/\s//g;
 4117:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 4118:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 4119:                                           : 'correct_by_override';
 4120:                     $grades{"resource.$part.awarded"}=$pcr;
 4121:                     $grades{"resource.$part.solved"}=$award;
 4122:                     $points{$part}=1;
 4123:                 } else {
 4124:                     $error_msg = "<br />" .
 4125:                         &mt("Some point values were assigned"
 4126:                             ." for problems with a weight "
 4127:                             ."of zero. These values were "
 4128:                             ."ignored.");
 4129:                 }
 4130: 	    } else {
 4131: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 4132: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 4133: 		my $store_key=$dest;
 4134: 		$store_key=~s/^stores/resource/;
 4135: 		$store_key=~s/_/\./g;
 4136: 		$grades{$store_key}=$entries{$fields{$dest}};
 4137: 	    }
 4138: 	}
 4139: 	if (! %grades) { 
 4140:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 4141:         } else {
 4142: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 4143: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 4144: 					   $env{'request.course.id'},
 4145: 					   $domain,$username);
 4146: 	   if ($result eq 'ok') {
 4147: 	      $request->print('.');
 4148: 	   } else {
 4149: 	      $request->print("<p><span class=\"LC_error\">".
 4150:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 4151:                                   "$username:$domain",$result)."</span></p>");
 4152: 	   }
 4153: 	   $request->rflush();
 4154: 	   $countdone++;
 4155:         }
 4156:     }
 4157:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
 4158:     if (@skipped) {
 4159: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
 4160:         $request->print(join(', ',@skipped));
 4161:     }
 4162:     if (@notallowed) {
 4163: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
 4164: 	$request->print(join(', ',@notallowed));
 4165:     }
 4166:     $request->print("<br />\n");
 4167:     $request->print(&show_grading_menu_form($symb));
 4168:     return $error_msg;
 4169: }
 4170: #------------- end of section for handling csv file upload ---------
 4171: #
 4172: #-------------------------------------------------------------------
 4173: #
 4174: #-------------- Next few routines handle grading by page/sequence
 4175: #
 4176: #--- Select a page/sequence and a student to grade
 4177: sub pickStudentPage {
 4178:     my ($request,$symb) = @_;
 4179: 
 4180:     my $alertmsg = &mt('Please select the student you wish to grade.');
 4181:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
 4182: 
 4183: function checkPickOne(formname) {
 4184:     if (radioSelection(formname.student) == null) {
 4185: 	alert("$alertmsg");
 4186: 	return;
 4187:     }
 4188:     ptr = pullDownSelection(formname.selectpage);
 4189:     formname.page.value = formname["page"+ptr].value;
 4190:     formname.title.value = formname["title"+ptr].value;
 4191:     formname.submit();
 4192: }
 4193: 
 4194: LISTJAVASCRIPT
 4195:     &commonJSfunctions($request);
 4196: 
 4197:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4198:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4199:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4200: 
 4201:     my $result='<h3><span class="LC_info">&nbsp;'.
 4202: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 4203: 
 4204:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 4205:     my $map_error;
 4206:     my ($titles,$symbx) = &getSymbMap($map_error);
 4207:     if ($map_error) {
 4208:         $request->print(&navmap_errormsg());
 4209:         return; 
 4210:     }
 4211:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 4212: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 4213: #    my $type=($curpage =~ /\.(page|sequence)/);
 4214:     my $select = '<select name="selectpage">'."\n";
 4215:     my $ctr=0;
 4216:     foreach (@$titles) {
 4217: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4218: 	$select.='<option value="'.$ctr.'" '.
 4219: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4220: 	    '>'.$showtitle.'</option>'."\n";
 4221: 	$ctr++;
 4222:     }
 4223:     $select.= '</select>';
 4224:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
 4225: 
 4226:     $ctr=0;
 4227:     foreach (@$titles) {
 4228: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4229: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 4230: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 4231: 	$ctr++;
 4232:     }
 4233:     $result.='<input type="hidden" name="page" />'."\n".
 4234: 	'<input type="hidden" name="title" />'."\n";
 4235: 
 4236:     my $options =
 4237: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
 4238: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
 4239:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
 4240: 
 4241:     $options =
 4242: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
 4243: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
 4244: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
 4245:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
 4246:     
 4247:     $result.=&build_section_inputs();
 4248:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4249:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 4250: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 4251: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4252: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
 4253: 
 4254:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
 4255: 
 4256:     $result.='&nbsp;<input type="button" '.
 4257:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 4258: 
 4259:     $request->print($result);
 4260: 
 4261:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 4262: 	&Apache::loncommon::start_data_table().
 4263: 	&Apache::loncommon::start_data_table_header_row().
 4264: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4265: 	'<th>'.&nameUserString('header').'</th>'.
 4266: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4267: 	'<th>'.&nameUserString('header').'</th>'.
 4268: 	&Apache::loncommon::end_data_table_header_row();
 4269:  
 4270:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 4271:     my $ptr = 1;
 4272:     foreach my $student (sort 
 4273: 			 {
 4274: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4275: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4276: 			     }
 4277: 			     return $a cmp $b;
 4278: 			 } (keys(%$fullname))) {
 4279: 	my ($uname,$udom) = split(/:/,$student);
 4280: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 4281:                                   : '</td>');
 4282: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 4283: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 4284: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 4285: 	$studentTable.=
 4286: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 4287:                          : '');
 4288: 	$ptr++;
 4289:     }
 4290:     if ($ptr%2 == 0) {
 4291: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 4292: 	    &Apache::loncommon::end_data_table_row();
 4293:     }
 4294:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 4295:     $studentTable.='<input type="button" '.
 4296:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 4297: 
 4298:     $studentTable.=&show_grading_menu_form($symb);
 4299:     $request->print($studentTable);
 4300: 
 4301:     return '';
 4302: }
 4303: 
 4304: sub getSymbMap {
 4305:     my ($map_error) = @_;
 4306:     my $navmap = Apache::lonnavmaps::navmap->new();
 4307:     unless (ref($navmap)) {
 4308:         if (ref($map_error)) {
 4309:             $$map_error = 'navmap';
 4310:         }
 4311:         return;
 4312:     }
 4313:     my %symbx = ();
 4314:     my @titles = ();
 4315:     my $minder = 0;
 4316: 
 4317:     # Gather every sequence that has problems.
 4318:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 4319: 					       1,0,1);
 4320:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 4321: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 4322: 	    my $title = $minder.'.'.
 4323: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 4324: 	    push(@titles, $title); # minder in case two titles are identical
 4325: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 4326: 	    $minder++;
 4327: 	}
 4328:     }
 4329:     return \@titles,\%symbx;
 4330: }
 4331: 
 4332: #
 4333: #--- Displays a page/sequence w/wo problems, w/wo submissions
 4334: sub displayPage {
 4335:     my ($request,$symb) = @_;
 4336:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4337:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4338:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4339:     my $pageTitle = $env{'form.page'};
 4340:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4341:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4342:     my $usec=$classlist->{$env{'form.student'}}[5];
 4343: 
 4344:     #need to make sure we have the correct data for later EXT calls, 
 4345:     #thus invalidate the cache
 4346:     &Apache::lonnet::devalidatecourseresdata(
 4347:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 4348:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 4349:     &Apache::lonnet::clear_EXT_cache_status();
 4350: 
 4351:     if (!&canview($usec)) {
 4352: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
 4353: 	$request->print(&show_grading_menu_form($symb));
 4354: 	return;
 4355:     }
 4356:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4357:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 4358: 	'</h3>'."\n";
 4359:     $env{'form.CODE'} = uc($env{'form.CODE'});
 4360:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 4361: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 4362:     } else {
 4363: 	delete($env{'form.CODE'});
 4364:     }
 4365:     &sub_page_js($request);
 4366:     $request->print($result);
 4367: 
 4368:     my $navmap = Apache::lonnavmaps::navmap->new();
 4369:     unless (ref($navmap)) {
 4370:         $request->print(&navmap_errormsg());
 4371:         $request->print(&show_grading_menu_form($symb));
 4372:         return;
 4373:     }
 4374:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 4375:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4376:     if (!$map) {
 4377: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 4378: 	$request->print(&show_grading_menu_form($symb));
 4379: 	return; 
 4380:     }
 4381:     my $iterator = $navmap->getIterator($map->map_start(),
 4382: 					$map->map_finish());
 4383: 
 4384:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 4385: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 4386: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 4387: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 4388: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 4389: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 4390: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4391: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
 4392: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
 4393: 
 4394:     if (defined($env{'form.CODE'})) {
 4395: 	$studentTable.=
 4396: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 4397:     }
 4398:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 4399: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 4400: 
 4401:     $studentTable.='&nbsp;<span class="LC_info">'.
 4402:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
 4403:         '</span>'."\n".
 4404: 	&Apache::loncommon::start_data_table().
 4405: 	&Apache::loncommon::start_data_table_header_row().
 4406: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
 4407: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 4408: 	&Apache::loncommon::end_data_table_header_row();
 4409: 
 4410:     &Apache::lonxml::clear_problem_counter();
 4411:     my ($depth,$question,$prob) = (1,1,1);
 4412:     $iterator->next(); # skip the first BEGIN_MAP
 4413:     my $curRes = $iterator->next(); # for "current resource"
 4414:     while ($depth > 0) {
 4415:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4416:         if($curRes == $iterator->END_MAP) { $depth--; }
 4417: 
 4418:         if (ref($curRes) && $curRes->is_problem()) {
 4419: 	    my $parts = $curRes->parts();
 4420:             my $title = $curRes->compTitle();
 4421: 	    my $symbx = $curRes->symb();
 4422: 	    $studentTable.=
 4423: 		&Apache::loncommon::start_data_table_row().
 4424: 		'<td align="center" valign="top" >'.$prob.
 4425: 		(scalar(@{$parts}) == 1 ? '' 
 4426: 		                        : '<br />('.&mt('[_1]&nbsp;parts)',
 4427: 							scalar(@{$parts}))
 4428: 		 ).
 4429: 		 '</td>';
 4430: 	    $studentTable.='<td valign="top">';
 4431: 	    my %form = ('CODE' => $env{'form.CODE'},);
 4432: 	    if ($env{'form.vProb'} eq 'yes' ) {
 4433: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 4434: 					     undef,'both',\%form);
 4435: 	    } else {
 4436: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 4437: 		$companswer =~ s|<form(.*?)>||g;
 4438: 		$companswer =~ s|</form>||g;
 4439: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 4440: #		    $companswer =~ s/$1/ /ms;
 4441: #		    $request->print('match='.$1."<br />\n");
 4442: #		}
 4443: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 4444: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 4445: 	    }
 4446: 
 4447: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 4448: 
 4449: 	    if ($env{'form.lastSub'} eq 'datesub') {
 4450: 		if ($record{'version'} eq '') {
 4451: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
 4452: 		} else {
 4453: 		    my %responseType = ();
 4454: 		    foreach my $partid (@{$parts}) {
 4455: 			my @responseIds =$curRes->responseIds($partid);
 4456: 			my @responseType =$curRes->responseType($partid);
 4457: 			my %responseIds;
 4458: 			for (my $i=0;$i<=$#responseIds;$i++) {
 4459: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 4460: 			}
 4461: 			$responseType{$partid} = \%responseIds;
 4462: 		    }
 4463: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 4464: 
 4465: 		}
 4466: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 4467: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 4468: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 4469: 									$env{'request.course.id'},
 4470: 									'','.submission');
 4471:  
 4472: 	    }
 4473: 	    if (&canmodify($usec)) {
 4474:             $studentTable.=&gradeBox_start();
 4475: 		foreach my $partid (@{$parts}) {
 4476: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 4477: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 4478: 		    $question++;
 4479: 		}
 4480:             $studentTable.=&gradeBox_end();
 4481: 		$prob++;
 4482: 	    }
 4483: 	    $studentTable.='</td></tr>';
 4484: 
 4485: 	}
 4486:         $curRes = $iterator->next();
 4487:     }
 4488: 
 4489:     $studentTable.=
 4490:         '</table>'."\n".
 4491:         '<input type="button" value="'.&mt('Save').'" '.
 4492:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 4493:         '</form>'."\n";
 4494:     $studentTable.=&show_grading_menu_form($symb);
 4495:     $request->print($studentTable);
 4496: 
 4497:     return '';
 4498: }
 4499: 
 4500: sub displaySubByDates {
 4501:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 4502:     my $isCODE=0;
 4503:     my $isTask = ($symb =~/\.task$/);
 4504:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 4505:     my $studentTable=&Apache::loncommon::start_data_table().
 4506: 	&Apache::loncommon::start_data_table_header_row().
 4507: 	'<th>'.&mt('Date/Time').'</th>'.
 4508: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 4509: 	'<th>'.&mt('Submission').'</th>'.
 4510: 	'<th>'.&mt('Status').'</th>'.
 4511: 	&Apache::loncommon::end_data_table_header_row();
 4512:     my ($version);
 4513:     my %mark;
 4514:     my %orders;
 4515:     $mark{'correct_by_student'} = $checkIcon;
 4516:     if (!exists($$record{'1:timestamp'})) {
 4517: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 4518:     }
 4519: 
 4520:     my $interaction;
 4521:     my $no_increment = 1;
 4522:     for ($version=1;$version<=$$record{'version'};$version++) {
 4523: 	my $timestamp = 
 4524: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 4525: 	if (exists($$record{$version.':resource.0.version'})) {
 4526: 	    $interaction = $$record{$version.':resource.0.version'};
 4527: 	}
 4528: 
 4529: 	my $where = ($isTask ? "$version:resource.$interaction"
 4530: 		             : "$version:resource");
 4531: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 4532: 	    '<td>'.$timestamp.'</td>';
 4533: 	if ($isCODE) {
 4534: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 4535: 	}
 4536: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 4537: 	my @displaySub = ();
 4538: 	foreach my $partid (@{$parts}) {
 4539:             my $hidden;
 4540:             if (($$record{$version.':resource.'.$partid.'.type'} eq 'anonsurvey') ||
 4541:                 ($$record{$version.':resource.'.$partid.'.type'} eq 'anonsurveycred')) {
 4542:                 $hidden = 1;
 4543:             }
 4544: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
 4545: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 4546: 	    
 4547: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 4548: 	    my $display_part=&get_display_part($partid,$symb);
 4549: 	    foreach my $matchKey (@matchKey) {
 4550: 		if (exists($$record{$version.':'.$matchKey}) &&
 4551: 		    $$record{$version.':'.$matchKey} ne '') {
 4552:                     
 4553: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 4554: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 4555:                     $displaySub[0].='<span class="LC_nobreak"';
 4556:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
 4557:                                    .' <span class="LC_internal_info">'
 4558:                                    .'('.&mt('Part ID: [_1]',$responseId).')'
 4559:                                    .'</span>'
 4560:                                    .' <b>';
 4561:                     if ($hidden) {
 4562:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
 4563:                     } else {
 4564: 		        if ($$record{"$where.$partid.tries"} eq '') {
 4565: 			    $displaySub[0].=&mt('Trial not counted');
 4566: 		        } else {
 4567: 			    $displaySub[0].=&mt('Trial: [_1]',
 4568: 					    $$record{"$where.$partid.tries"});
 4569: 		        }
 4570: 		        my $responseType=($isTask ? 'Task'
 4571:                                               : $responseType->{$partid}->{$responseId});
 4572: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
 4573: 		        if (!exists($orders{$partid}->{$responseId})) {
 4574: 			    $orders{$partid}->{$responseId}=
 4575: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
 4576:                                            $no_increment);
 4577: 		        }
 4578: 		        $displaySub[0].='</b></span>'; # /nobreak
 4579: 		        $displaySub[0].='&nbsp; '.
 4580: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
 4581:                     }
 4582: 		}
 4583: 	    }
 4584: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 4585: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 4586: 				    $$record{"$where.$partid.checkedin"},
 4587: 				    $$record{"$where.$partid.checkedin.slot"}).
 4588: 					'<br />';
 4589: 	    }
 4590: 	    if (exists $$record{"$where.$partid.award"}) {
 4591: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 4592: 		    lc($$record{"$where.$partid.award"}).' '.
 4593: 		    $mark{$$record{"$where.$partid.solved"}}.
 4594: 		    '<br />';
 4595: 	    }
 4596: 	    if (exists $$record{"$where.$partid.regrader"}) {
 4597: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 4598: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4599: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 4600: 		$displaySub[2].=
 4601: 		    $$record{"$version:resource.$partid.regrader"}.
 4602: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4603: 	    }
 4604: 	}
 4605: 	# needed because old essay regrader has not parts info
 4606: 	if (exists $$record{"$version:resource.regrader"}) {
 4607: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 4608: 	}
 4609: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 4610: 	if ($displaySub[2]) {
 4611: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 4612: 	}
 4613: 	$studentTable.='&nbsp;</td>'.
 4614: 	    &Apache::loncommon::end_data_table_row();
 4615:     }
 4616:     $studentTable.=&Apache::loncommon::end_data_table();
 4617:     return $studentTable;
 4618: }
 4619: 
 4620: sub updateGradeByPage {
 4621:     my ($request,$symb) = @_;
 4622: 
 4623:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4624:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4625:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4626:     my $pageTitle = $env{'form.page'};
 4627:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4628:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4629:     my $usec=$classlist->{$env{'form.student'}}[5];
 4630:     if (!&canmodify($usec)) {
 4631: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 4632: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
 4633: 	return;
 4634:     }
 4635:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4636:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 4637: 	'</h3>'."\n";
 4638: 
 4639:     $request->print($result);
 4640: 
 4641: 
 4642:     my $navmap = Apache::lonnavmaps::navmap->new();
 4643:     unless (ref($navmap)) {
 4644:         $request->print(&navmap_errormsg());
 4645:         return;
 4646:     }
 4647:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 4648:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4649:     if (!$map) {
 4650: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 4651: 	$request->print(&show_grading_menu_form($symb));
 4652: 	return; 
 4653:     }
 4654:     my $iterator = $navmap->getIterator($map->map_start(),
 4655: 					$map->map_finish());
 4656: 
 4657:     my $studentTable=
 4658: 	&Apache::loncommon::start_data_table().
 4659: 	&Apache::loncommon::start_data_table_header_row().
 4660: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 4661: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 4662: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 4663: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 4664: 	&Apache::loncommon::end_data_table_header_row();
 4665: 
 4666:     $iterator->next(); # skip the first BEGIN_MAP
 4667:     my $curRes = $iterator->next(); # for "current resource"
 4668:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
 4669:     while ($depth > 0) {
 4670:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4671:         if($curRes == $iterator->END_MAP) { $depth--; }
 4672: 
 4673:         if (ref($curRes) && $curRes->is_problem()) {
 4674: 	    my $parts = $curRes->parts();
 4675:             my $title = $curRes->compTitle();
 4676: 	    my $symbx = $curRes->symb();
 4677: 	    $studentTable.=
 4678: 		&Apache::loncommon::start_data_table_row().
 4679: 		'<td align="center" valign="top" >'.$prob.
 4680: 		(scalar(@{$parts}) == 1 ? '' 
 4681:                                         : '<br />('.&mt('[quant,_1,&nbsp;part]',scalar(@{$parts}))
 4682: 		.')').'</td>';
 4683: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 4684: 
 4685: 	    my %newrecord=();
 4686: 	    my @displayPts=();
 4687:             my %aggregate = ();
 4688:             my $aggregateflag = 0;
 4689: 	    foreach my $partid (@{$parts}) {
 4690: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 4691: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 4692: 
 4693: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 4694: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 4695: 		my $partial = $newpts/$wgt;
 4696: 		my $score;
 4697: 		if ($partial > 0) {
 4698: 		    $score = 'correct_by_override';
 4699: 		} elsif ($newpts ne '') { #empty is taken as 0
 4700: 		    $score = 'incorrect_by_override';
 4701: 		}
 4702: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 4703: 		if ($dropMenu eq 'excused') {
 4704: 		    $partial = '';
 4705: 		    $score = 'excused';
 4706: 		} elsif ($dropMenu eq 'reset status'
 4707: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 4708: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 4709: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 4710: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 4711: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 4712: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 4713: 		    $changeflag++;
 4714: 		    $newpts = '';
 4715:                     
 4716:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 4717:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 4718:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 4719:                     if ($aggtries > 0) {
 4720:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4721:                         $aggregateflag = 1;
 4722:                     }
 4723: 		}
 4724: 		my $display_part=&get_display_part($partid,$curRes->symb());
 4725: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 4726: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4727: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 4728: 		    '&nbsp;<br />';
 4729: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4730: 		     (($score eq 'excused') ? 'excused' : $newpts).
 4731: 		    '&nbsp;<br />';
 4732: 		$question++;
 4733: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 4734: 
 4735: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 4736: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 4737: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 4738: 		    if (scalar(keys(%newrecord)) > 0);
 4739: 
 4740: 		$changeflag++;
 4741: 	    }
 4742: 	    if (scalar(keys(%newrecord)) > 0) {
 4743: 		my %record = 
 4744: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 4745: 					     $udom,$uname);
 4746: 
 4747: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 4748: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 4749: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 4750: 		    $newrecord{'resource.CODE'} = '';
 4751: 		}
 4752: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 4753: 					$udom,$uname);
 4754: 		%record = &Apache::lonnet::restore($symbx,
 4755: 						   $env{'request.course.id'},
 4756: 						   $udom,$uname);
 4757: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 4758: 					     $cdom,$cnum,$udom,$uname);
 4759: 	    }
 4760: 	    
 4761:             if ($aggregateflag) {
 4762:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4763:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 4764:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 4765:             }
 4766: 
 4767: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 4768: 		'<td valign="top">'.$displayPts[1].'</td>'.
 4769: 		&Apache::loncommon::end_data_table_row();
 4770: 
 4771: 	    $prob++;
 4772: 	}
 4773:         $curRes = $iterator->next();
 4774:     }
 4775: 
 4776:     $studentTable.=&Apache::loncommon::end_data_table();
 4777:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
 4778:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 4779: 		  &mt('The scores were changed for [quant,_1,problem].',
 4780: 		  $changeflag));
 4781:     $request->print($grademsg.$studentTable);
 4782: 
 4783:     return '';
 4784: }
 4785: 
 4786: #-------- end of section for handling grading by page/sequence ---------
 4787: #
 4788: #-------------------------------------------------------------------
 4789: 
 4790: #-------------------- Bubblesheet (Scantron) Grading -------------------
 4791: #
 4792: #------ start of section for handling grading by page/sequence ---------
 4793: 
 4794: =pod
 4795: 
 4796: =head1 Bubble sheet grading routines
 4797: 
 4798:   For this documentation:
 4799: 
 4800:    'scanline' refers to the full line of characters
 4801:    from the file that we are parsing that represents one entire sheet
 4802: 
 4803:    'bubble line' refers to the data
 4804:    representing the line of bubbles that are on the physical bubble sheet
 4805: 
 4806: 
 4807: The overall process is that a scanned in bubble sheet data is uploaded
 4808: into a course. When a user wants to grade, they select a
 4809: sequence/folder of resources, a file of bubble sheet info, and pick
 4810: one of the predefined configurations for what each scanline looks
 4811: like.
 4812: 
 4813: Next each scanline is checked for any errors of either 'missing
 4814: bubbles' (it's an error because it may have been mis-scanned
 4815: because too light bubbling), 'double bubble' (each bubble line should
 4816: have no more that one letter picked), invalid or duplicated CODE,
 4817: invalid student/employee ID
 4818: 
 4819: If the CODE option is used that determines the randomization of the
 4820: homework problems, either way the student/employee ID is looked up into a
 4821: username:domain.
 4822: 
 4823: During the validation phase the instructor can choose to skip scanlines. 
 4824: 
 4825: After the validation phase, there are now 3 bubble sheet files
 4826: 
 4827:   scantron_original_filename (unmodified original file)
 4828:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 4829:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 4830: 
 4831: Also there is a separate hash nohist_scantrondata that contains extra
 4832: correction information that isn't representable in the bubble sheet
 4833: file (see &scantron_getfile() for more information)
 4834: 
 4835: After all scanlines are either valid, marked as valid or skipped, then
 4836: foreach line foreach problem in the picked sequence, an ssi request is
 4837: made that simulates a user submitting their selected letter(s) against
 4838: the homework problem.
 4839: 
 4840: =over 4
 4841: 
 4842: 
 4843: 
 4844: =item defaultFormData
 4845: 
 4846:   Returns html hidden inputs used to hold context/default values.
 4847: 
 4848:  Arguments:
 4849:   $symb - $symb of the current resource 
 4850: 
 4851: =cut
 4852: 
 4853: sub defaultFormData {
 4854:     my ($symb)=@_;
 4855:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4856:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />';
 4857: }
 4858: 
 4859: 
 4860: =pod 
 4861: 
 4862: =item getSequenceDropDown
 4863: 
 4864:    Return html dropdown of possible sequences to grade
 4865:  
 4866:  Arguments:
 4867:    $symb - $symb of the current resource
 4868:    $map_error - ref to scalar which will container error if
 4869:                 $navmap object is unavailable in &getSymbMap().
 4870: 
 4871: =cut
 4872: 
 4873: sub getSequenceDropDown {
 4874:     my ($symb,$map_error)=@_;
 4875:     my $result='<select name="selectpage">'."\n";
 4876:     my ($titles,$symbx) = &getSymbMap($map_error);
 4877:     if (ref($map_error)) {
 4878:         return if ($$map_error);
 4879:     }
 4880:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 4881:     my $ctr=0;
 4882:     foreach (@$titles) {
 4883: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4884: 	$result.='<option value="'.$$symbx{$_}.'" '.
 4885: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4886: 	    '>'.$showtitle.'</option>'."\n";
 4887: 	$ctr++;
 4888:     }
 4889:     $result.= '</select>';
 4890:     return $result;
 4891: }
 4892: 
 4893: my %bubble_lines_per_response;     # no. bubble lines for each response.
 4894:                                    # key is zero-based index - 0, 1, 2 ...
 4895: 
 4896: my %first_bubble_line;             # First bubble line no. for each bubble.
 4897: 
 4898: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 4899:                                    # matchresponse or rankresponse, where 
 4900:                                    # an individual response can have multiple 
 4901:                                    # lines
 4902: 
 4903: my %responsetype_per_response;     # responsetype for each response
 4904: 
 4905: # Save and restore the bubble lines array to the form env.
 4906: 
 4907: 
 4908: sub save_bubble_lines {
 4909:     foreach my $line (keys(%bubble_lines_per_response)) {
 4910: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 4911: 	$env{"form.scantron.first_bubble_line.$line"} =
 4912: 	    $first_bubble_line{$line};
 4913:         $env{"form.scantron.sub_bubblelines.$line"} = 
 4914:             $subdivided_bubble_lines{$line};
 4915:         $env{"form.scantron.responsetype.$line"} =
 4916:             $responsetype_per_response{$line};
 4917:     }
 4918: }
 4919: 
 4920: 
 4921: sub restore_bubble_lines {
 4922:     my $line = 0;
 4923:     %bubble_lines_per_response = ();
 4924:     while ($env{"form.scantron.bubblelines.$line"}) {
 4925: 	my $value = $env{"form.scantron.bubblelines.$line"};
 4926: 	$bubble_lines_per_response{$line} = $value;
 4927: 	$first_bubble_line{$line}  =
 4928: 	    $env{"form.scantron.first_bubble_line.$line"};
 4929:         $subdivided_bubble_lines{$line} =
 4930:             $env{"form.scantron.sub_bubblelines.$line"};
 4931:         $responsetype_per_response{$line} =
 4932:             $env{"form.scantron.responsetype.$line"};
 4933: 	$line++;
 4934:     }
 4935: }
 4936: 
 4937: #  Given the parsed scanline, get the response for 
 4938: #  'answer' number n:
 4939: 
 4940: sub get_response_bubbles {
 4941:     my ($parsed_line, $response)  = @_;
 4942: 
 4943:     my $bubble_line = $first_bubble_line{$response-1} +1;
 4944:     my $bubble_lines= $bubble_lines_per_response{$response-1};
 4945:     
 4946:     my $selected = "";
 4947: 
 4948:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
 4949: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
 4950: 	$bubble_line++;
 4951:     }
 4952:     return $selected;
 4953: }
 4954: 
 4955: =pod 
 4956: 
 4957: =item scantron_filenames
 4958: 
 4959:    Returns a list of the scantron files in the current course 
 4960: 
 4961: =cut
 4962: 
 4963: sub scantron_filenames {
 4964:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4965:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4966:     my $getpropath = 1;
 4967:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
 4968:                                        $getpropath);
 4969:     my @possiblenames;
 4970:     foreach my $filename (sort(@files)) {
 4971: 	($filename)=split(/&/,$filename);
 4972: 	if ($filename!~/^scantron_orig_/) { next ; }
 4973: 	$filename=~s/^scantron_orig_//;
 4974: 	push(@possiblenames,$filename);
 4975:     }
 4976:     return @possiblenames;
 4977: }
 4978: 
 4979: =pod 
 4980: 
 4981: =item scantron_uploads
 4982: 
 4983:    Returns  html drop-down list of scantron files in current course.
 4984: 
 4985:  Arguments:
 4986:    $file2grade - filename to set as selected in the dropdown
 4987: 
 4988: =cut
 4989: 
 4990: sub scantron_uploads {
 4991:     my ($file2grade) = @_;
 4992:     my $result=	'<select name="scantron_selectfile">';
 4993:     $result.="<option></option>";
 4994:     foreach my $filename (sort(&scantron_filenames())) {
 4995: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 4996:     }
 4997:     $result.="</select>";
 4998:     return $result;
 4999: }
 5000: 
 5001: =pod 
 5002: 
 5003: =item scantron_scantab
 5004: 
 5005:   Returns html drop down of the scantron formats in the scantronformat.tab
 5006:   file.
 5007: 
 5008: =cut
 5009: 
 5010: sub scantron_scantab {
 5011:     my $result='<select name="scantron_format">'."\n";
 5012:     $result.='<option></option>'."\n";
 5013:     my @lines = &get_scantronformat_file();
 5014:     if (@lines > 0) {
 5015:         foreach my $line (@lines) {
 5016:             next if (($line =~ /^\#/) || ($line eq ''));
 5017: 	    my ($name,$descrip)=split(/:/,$line);
 5018: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 5019:         }
 5020:     }
 5021:     $result.='</select>'."\n";
 5022:     return $result;
 5023: }
 5024: 
 5025: =pod
 5026: 
 5027: =item get_scantronformat_file
 5028: 
 5029:   Returns an array containing lines from the scantron format file for
 5030:   the domain of the course.
 5031: 
 5032:   If a url for a custom.tab file is listed in domain's configuration.db, 
 5033:   lines are from this file.
 5034: 
 5035:   Otherwise, if a default.tab has been published in RES space by the 
 5036:   domainconfig user, lines are from this file.
 5037: 
 5038:   Otherwise, fall back to getting lines from the legacy file on the
 5039:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
 5040: 
 5041: =cut
 5042: 
 5043: sub get_scantronformat_file {
 5044:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5045:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
 5046:     my $gottab = 0;
 5047:     my @lines;
 5048:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 5049:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 5050:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 5051:             if ($formatfile ne '-1') {
 5052:                 @lines = split("\n",$formatfile,-1);
 5053:                 $gottab = 1;
 5054:             }
 5055:         }
 5056:     }
 5057:     if (!$gottab) {
 5058:         my $confname = $cdom.'-domainconfig';
 5059:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 5060:         my $formatfile =  &Apache::lonnet::getfile($default);
 5061:         if ($formatfile ne '-1') {
 5062:             @lines = split("\n",$formatfile,-1);
 5063:             $gottab = 1;
 5064:         }
 5065:     }
 5066:     if (!$gottab) {
 5067:         my @domains = &Apache::lonnet::current_machine_domains();
 5068:         if (grep(/^\Q$cdom\E$/,@domains)) {
 5069:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 5070:             @lines = <$fh>;
 5071:             close($fh);
 5072:         } else {
 5073:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
 5074:             @lines = <$fh>;
 5075:             close($fh);
 5076:         }
 5077:     }
 5078:     return @lines;
 5079: }
 5080: 
 5081: =pod 
 5082: 
 5083: =item scantron_CODElist
 5084: 
 5085:   Returns html drop down of the saved CODE lists from current course,
 5086:   generated from earlier printings.
 5087: 
 5088: =cut
 5089: 
 5090: sub scantron_CODElist {
 5091:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5092:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5093:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 5094:     my $namechoice='<option></option>';
 5095:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 5096: 	if ($name =~ /^error: 2 /) { next; }
 5097: 	if ($name =~ /^type\0/) { next; }
 5098: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 5099:     }
 5100:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 5101:     return $namechoice;
 5102: }
 5103: 
 5104: =pod 
 5105: 
 5106: =item scantron_CODEunique
 5107: 
 5108:   Returns the html for "Each CODE to be used once" radio.
 5109: 
 5110: =cut
 5111: 
 5112: sub scantron_CODEunique {
 5113:     my $result='<span class="LC_nobreak">
 5114:                  <label><input type="radio" name="scantron_CODEunique"
 5115:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 5116:                 </span>
 5117:                 <span class="LC_nobreak">
 5118:                  <label><input type="radio" name="scantron_CODEunique"
 5119:                         value="no" />'.&mt('No').' </label>
 5120:                 </span>';
 5121:     return $result;
 5122: }
 5123: 
 5124: =pod 
 5125: 
 5126: =item scantron_selectphase
 5127: 
 5128:   Generates the initial screen to start the bubble sheet process.
 5129:   Allows for - starting a grading run.
 5130:              - downloading existing scan data (original, corrected
 5131:                                                 or skipped info)
 5132: 
 5133:              - uploading new scan data
 5134: 
 5135:  Arguments:
 5136:   $r          - The Apache request object
 5137:   $file2grade - name of the file that contain the scanned data to score
 5138: 
 5139: =cut
 5140: 
 5141: sub scantron_selectphase {
 5142:     my ($r,$file2grade,$symb) = @_;
 5143:     if (!$symb) {return '';}
 5144:     my $map_error;
 5145:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
 5146:     if ($map_error) {
 5147:         $r->print('<br />'.&navmap_errormsg().'<br />');
 5148:         return;
 5149:     }
 5150:     my $default_form_data=&defaultFormData($symb);
 5151:     my $grading_menu_button=&show_grading_menu_form($symb);
 5152:     my $file_selector=&scantron_uploads($file2grade);
 5153:     my $format_selector=&scantron_scantab();
 5154:     my $CODE_selector=&scantron_CODElist();
 5155:     my $CODE_unique=&scantron_CODEunique();
 5156:     my $result;
 5157: 
 5158:     $ssi_error = 0;
 5159: 
 5160:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 5161:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 5162: 
 5163: 	# Chunk of form to prompt for a scantron file upload.
 5164: 
 5165:         $r->print('
 5166:     <br />
 5167:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5168:        '.&Apache::loncommon::start_data_table_header_row().'
 5169:             <th>
 5170:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
 5171:             </th>
 5172:        '.&Apache::loncommon::end_data_table_header_row().'
 5173:        '.&Apache::loncommon::start_data_table_row().'
 5174:             <td>
 5175: ');
 5176:     my $default_form_data=&defaultFormData($symb);
 5177:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5178:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 5179:     $r->print(&Apache::lonhtmlcommon::scripttag('
 5180:     function checkUpload(formname) {
 5181: 	if (formname.upfile.value == "") {
 5182: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
 5183: 	    return false;
 5184: 	}
 5185: 	formname.submit();
 5186:     }'));
 5187:     $r->print('
 5188:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 5189:                 '.$default_form_data.'
 5190:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 5191:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 5192:                 <input name="command" value="scantronupload_save" type="hidden" />
 5193:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
 5194:                 <br />
 5195:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 5196:               </form>
 5197: ');
 5198: 
 5199:         $r->print('
 5200:             </td>
 5201:        '.&Apache::loncommon::end_data_table_row().'
 5202:        '.&Apache::loncommon::end_data_table().'
 5203: ');
 5204:     }
 5205: 
 5206:     # Chunk of form to prompt for a file to grade and how:
 5207: 
 5208:     $result.= '
 5209:     <br />
 5210:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 5211:     <input type="hidden" name="command" value="scantron_warning" />
 5212:     '.$default_form_data.'
 5213:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5214:        '.&Apache::loncommon::start_data_table_header_row().'
 5215:             <th colspan="2">
 5216:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 5217:             </th>
 5218:        '.&Apache::loncommon::end_data_table_header_row().'
 5219:        '.&Apache::loncommon::start_data_table_row().'
 5220:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 5221:        '.&Apache::loncommon::end_data_table_row().'
 5222:        '.&Apache::loncommon::start_data_table_row().'
 5223:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
 5224:        '.&Apache::loncommon::end_data_table_row().'
 5225:        '.&Apache::loncommon::start_data_table_row().'
 5226:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
 5227:        '.&Apache::loncommon::end_data_table_row().'
 5228:        '.&Apache::loncommon::start_data_table_row().'
 5229:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 5230:        '.&Apache::loncommon::end_data_table_row().'
 5231:        '.&Apache::loncommon::start_data_table_row().'
 5232:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 5233:        '.&Apache::loncommon::end_data_table_row().'
 5234:        '.&Apache::loncommon::start_data_table_row().'
 5235: 	    <td> '.&mt('Options:').' </td>
 5236:             <td>
 5237: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 5238:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 5239:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 5240: 	    </td>
 5241:        '.&Apache::loncommon::end_data_table_row().'
 5242:        '.&Apache::loncommon::start_data_table_row().'
 5243:             <td colspan="2">
 5244:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
 5245:             </td>
 5246:        '.&Apache::loncommon::end_data_table_row().'
 5247:     '.&Apache::loncommon::end_data_table().'
 5248:     </form>
 5249: ';
 5250:    
 5251:     $r->print($result);
 5252: 
 5253: 
 5254: 
 5255:     # Chunk of the form that prompts to view a scoring office file,
 5256:     # corrected file, skipped records in a file.
 5257: 
 5258:     $r->print('
 5259:    <br />
 5260:    <form action="/adm/grades" name="scantron_download">
 5261:      '.$default_form_data.'
 5262:      <input type="hidden" name="command" value="scantron_download" />
 5263:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5264:        '.&Apache::loncommon::start_data_table_header_row().'
 5265:               <th>
 5266:                 &nbsp;'.&mt('Download a scoring office file').'
 5267:               </th>
 5268:        '.&Apache::loncommon::end_data_table_header_row().'
 5269:        '.&Apache::loncommon::start_data_table_row().'
 5270:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 5271:                 <br />
 5272:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 5273:        '.&Apache::loncommon::end_data_table_row().'
 5274:      '.&Apache::loncommon::end_data_table().'
 5275:    </form>
 5276:    <br />
 5277: ');
 5278: 
 5279:     &Apache::lonpickcode::code_list($r,2);
 5280: 
 5281:     $r->print('<br /><form method="post" name="checkscantron">'.
 5282:              $default_form_data."\n".
 5283:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 5284:              &Apache::loncommon::start_data_table_header_row()."\n".
 5285:              '<th colspan="2">
 5286:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
 5287:              '</th>'."\n".
 5288:               &Apache::loncommon::end_data_table_header_row()."\n".
 5289:               &Apache::loncommon::start_data_table_row()."\n".
 5290:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 5291:               '<td> '.$sequence_selector.' </td>'.
 5292:               &Apache::loncommon::end_data_table_row()."\n".
 5293:               &Apache::loncommon::start_data_table_row()."\n".
 5294:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 5295:               '<td> '.$file_selector.' </td>'."\n".
 5296:               &Apache::loncommon::end_data_table_row()."\n".
 5297:               &Apache::loncommon::start_data_table_row()."\n".
 5298:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 5299:               '<td> '.$format_selector.' </td>'."\n".
 5300:               &Apache::loncommon::end_data_table_row()."\n".
 5301:               &Apache::loncommon::start_data_table_row()."\n".
 5302:               '<td> '.&mt('Options').' </td>'."\n".
 5303:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
 5304:               &Apache::loncommon::end_data_table_row()."\n".
 5305:               &Apache::loncommon::start_data_table_row()."\n".
 5306:               '<td colspan="2">'."\n".
 5307:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 5308:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
 5309:               '</td>'."\n".
 5310:               &Apache::loncommon::end_data_table_row()."\n".
 5311:               &Apache::loncommon::end_data_table()."\n".
 5312:               '</form><br />');
 5313:     $r->print($grading_menu_button);
 5314:     return;
 5315: }
 5316: 
 5317: =pod
 5318: 
 5319: =item get_scantron_config
 5320: 
 5321:    Parse and return the scantron configuration line selected as a
 5322:    hash of configuration file fields.
 5323: 
 5324:  Arguments:
 5325:     which - the name of the configuration to parse from the file.
 5326: 
 5327: 
 5328:  Returns:
 5329:             If the named configuration is not in the file, an empty
 5330:             hash is returned.
 5331:     a hash with the fields
 5332:       name         - internal name for the this configuration setup
 5333:       description  - text to display to operator that describes this config
 5334:       CODElocation - if 0 or the string 'none'
 5335:                           - no CODE exists for this config
 5336:                      if -1 || the string 'letter'
 5337:                           - a CODE exists for this config and is
 5338:                             a string of letters
 5339:                      Unsupported value (but planned for future support)
 5340:                           if a positive integer
 5341:                                - The CODE exists as the first n items from
 5342:                                  the question section of the form
 5343:                           if the string 'number'
 5344:                                - The CODE exists for this config and is
 5345:                                  a string of numbers
 5346:       CODEstart   - (only matter if a CODE exists) column in the line where
 5347:                      the CODE starts
 5348:       CODElength  - length of the CODE
 5349:       IDstart     - column where the student/employee ID starts
 5350:       IDlength    - length of the student/employee ID info
 5351:       Qstart      - column where the information from the bubbled
 5352:                     'questions' start
 5353:       Qlength     - number of columns comprising a single bubble line from
 5354:                     the sheet. (usually either 1 or 10)
 5355:       Qon         - either a single character representing the character used
 5356:                     to signal a bubble was chosen in the positional setup, or
 5357:                     the string 'letter' if the letter of the chosen bubble is
 5358:                     in the final, or 'number' if a number representing the
 5359:                     chosen bubble is in the file (1->A 0->J)
 5360:       Qoff        - the character used to represent that a bubble was
 5361:                     left blank
 5362:       PaperID     - if the scanning process generates a unique number for each
 5363:                     sheet scanned the column that this ID number starts in
 5364:       PaperIDlength - number of columns that comprise the unique ID number
 5365:                       for the sheet of paper
 5366:       FirstName   - column that the first name starts in
 5367:       FirstNameLength - number of columns that the first name spans
 5368:  
 5369:       LastName    - column that the last name starts in
 5370:       LastNameLength - number of columns that the last name spans
 5371: 
 5372: =cut
 5373: 
 5374: sub get_scantron_config {
 5375:     my ($which) = @_;
 5376:     my @lines = &get_scantronformat_file();
 5377:     my %config;
 5378:     #FIXME probably should move to XML it has already gotten a bit much now
 5379:     foreach my $line (@lines) {
 5380: 	my ($name,$descrip)=split(/:/,$line);
 5381: 	if ($name ne $which ) { next; }
 5382: 	chomp($line);
 5383: 	my @config=split(/:/,$line);
 5384: 	$config{'name'}=$config[0];
 5385: 	$config{'description'}=$config[1];
 5386: 	$config{'CODElocation'}=$config[2];
 5387: 	$config{'CODEstart'}=$config[3];
 5388: 	$config{'CODElength'}=$config[4];
 5389: 	$config{'IDstart'}=$config[5];
 5390: 	$config{'IDlength'}=$config[6];
 5391: 	$config{'Qstart'}=$config[7];
 5392:  	$config{'Qlength'}=$config[8];
 5393: 	$config{'Qoff'}=$config[9];
 5394: 	$config{'Qon'}=$config[10];
 5395: 	$config{'PaperID'}=$config[11];
 5396: 	$config{'PaperIDlength'}=$config[12];
 5397: 	$config{'FirstName'}=$config[13];
 5398: 	$config{'FirstNamelength'}=$config[14];
 5399: 	$config{'LastName'}=$config[15];
 5400: 	$config{'LastNamelength'}=$config[16];
 5401: 	last;
 5402:     }
 5403:     return %config;
 5404: }
 5405: 
 5406: =pod 
 5407: 
 5408: =item username_to_idmap
 5409: 
 5410:     creates a hash keyed by student/employee ID with values of the corresponding
 5411:     student username:domain.
 5412: 
 5413:   Arguments:
 5414: 
 5415:     $classlist - reference to the class list hash. This is a hash
 5416:                  keyed by student name:domain  whose elements are references
 5417:                  to arrays containing various chunks of information
 5418:                  about the student. (See loncoursedata for more info).
 5419: 
 5420:   Returns
 5421:     %idmap - the constructed hash
 5422: 
 5423: =cut
 5424: 
 5425: sub username_to_idmap {
 5426:     my ($classlist)= @_;
 5427:     my %idmap;
 5428:     foreach my $student (keys(%$classlist)) {
 5429: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
 5430: 	    $student;
 5431:     }
 5432:     return %idmap;
 5433: }
 5434: 
 5435: =pod
 5436: 
 5437: =item scantron_fixup_scanline
 5438: 
 5439:    Process a requested correction to a scanline.
 5440: 
 5441:   Arguments:
 5442:     $scantron_config   - hash from &get_scantron_config()
 5443:     $scan_data         - hash of correction information 
 5444:                           (see &scantron_getfile())
 5445:     $line              - existing scanline
 5446:     $whichline         - line number of the passed in scanline
 5447:     $field             - type of change to process 
 5448:                          (either 
 5449:                           'ID'     -> correct the student/employee ID
 5450:                           'CODE'   -> correct the CODE
 5451:                           'answer' -> fixup the submitted answers)
 5452:     
 5453:    $args               - hash of additional info,
 5454:                           - 'ID' 
 5455:                                'newid' -> studentID to use in replacement
 5456:                                           of existing one
 5457:                           - 'CODE' 
 5458:                                'CODE_ignore_dup' - set to true if duplicates
 5459:                                                    should be ignored.
 5460: 	                       'CODE' - is new code or 'use_unfound'
 5461:                                         if the existing unfound code should
 5462:                                         be used as is
 5463:                           - 'answer'
 5464:                                'response' - new answer or 'none' if blank
 5465:                                'question' - the bubble line to change
 5466:                                'questionnum' - the question identifier,
 5467:                                                may include subquestion. 
 5468: 
 5469:   Returns:
 5470:     $line - the modified scanline
 5471: 
 5472:   Side effects: 
 5473:     $scan_data - may be updated
 5474: 
 5475: =cut
 5476: 
 5477: 
 5478: sub scantron_fixup_scanline {
 5479:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 5480:     if ($field eq 'ID') {
 5481: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 5482: 	    return ($line,1,'New value too large');
 5483: 	}
 5484: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 5485: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 5486: 				     $args->{'newid'});
 5487: 	}
 5488: 	substr($line,$$scantron_config{'IDstart'}-1,
 5489: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 5490: 	if ($args->{'newid'}=~/^\s*$/) {
 5491: 	    &scan_data($scan_data,"$whichline.user",
 5492: 		       $args->{'username'}.':'.$args->{'domain'});
 5493: 	}
 5494:     } elsif ($field eq 'CODE') {
 5495: 	if ($args->{'CODE_ignore_dup'}) {
 5496: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 5497: 	}
 5498: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 5499: 	if ($args->{'CODE'} ne 'use_unfound') {
 5500: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 5501: 		return ($line,1,'New CODE value too large');
 5502: 	    }
 5503: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 5504: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 5505: 	    }
 5506: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 5507: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 5508: 	}
 5509:     } elsif ($field eq 'answer') {
 5510: 	my $length=$scantron_config->{'Qlength'};
 5511: 	my $off=$scantron_config->{'Qoff'};
 5512: 	my $on=$scantron_config->{'Qon'};
 5513: 	my $answer=${off}x$length;
 5514: 	if ($args->{'response'} eq 'none') {
 5515: 	    &scan_data($scan_data,
 5516: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 5517: 	} else {
 5518: 	    if ($on eq 'letter') {
 5519: 		my @alphabet=('A'..'Z');
 5520: 		$answer=$alphabet[$args->{'response'}];
 5521: 	    } elsif ($on eq 'number') {
 5522: 		$answer=$args->{'response'}+1;
 5523: 		if ($answer == 10) { $answer = '0'; }
 5524: 	    } else {
 5525: 		substr($answer,$args->{'response'},1)=$on;
 5526: 	    }
 5527: 	    &scan_data($scan_data,
 5528: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 5529: 	}
 5530: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 5531: 	substr($line,$where-1,$length)=$answer;
 5532:     }
 5533:     return $line;
 5534: }
 5535: 
 5536: =pod
 5537: 
 5538: =item scan_data
 5539: 
 5540:     Edit or look up  an item in the scan_data hash.
 5541: 
 5542:   Arguments:
 5543:     $scan_data  - The hash (see scantron_getfile)
 5544:     $key        - shorthand of the key to edit (actual key is
 5545:                   scantronfilename_key).
 5546:     $data        - New value of the hash entry.
 5547:     $delete      - If true, the entry is removed from the hash.
 5548: 
 5549:   Returns:
 5550:     The new value of the hash table field (undefined if deleted).
 5551: 
 5552: =cut
 5553: 
 5554: 
 5555: sub scan_data {
 5556:     my ($scan_data,$key,$value,$delete)=@_;
 5557:     my $filename=$env{'form.scantron_selectfile'};
 5558:     if (defined($value)) {
 5559: 	$scan_data->{$filename.'_'.$key} = $value;
 5560:     }
 5561:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 5562:     return $scan_data->{$filename.'_'.$key};
 5563: }
 5564: 
 5565: # ----- These first few routines are general use routines.----
 5566: 
 5567: # Return the number of occurences of a pattern in a string.
 5568: 
 5569: sub occurence_count {
 5570:     my ($string, $pattern) = @_;
 5571: 
 5572:     my @matches = ($string =~ /$pattern/g);
 5573: 
 5574:     return scalar(@matches);
 5575: }
 5576: 
 5577: 
 5578: # Take a string known to have digits and convert all the
 5579: # digits into letters in the range J,A..I.
 5580: 
 5581: sub digits_to_letters {
 5582:     my ($input) = @_;
 5583: 
 5584:     my @alphabet = ('J', 'A'..'I');
 5585: 
 5586:     my @input    = split(//, $input);
 5587:     my $output ='';
 5588:     for (my $i = 0; $i < scalar(@input); $i++) {
 5589: 	if ($input[$i] =~ /\d/) {
 5590: 	    $output .= $alphabet[$input[$i]];
 5591: 	} else {
 5592: 	    $output .= $input[$i];
 5593: 	}
 5594:     }
 5595:     return $output;
 5596: }
 5597: 
 5598: =pod 
 5599: 
 5600: =item scantron_parse_scanline
 5601: 
 5602:   Decodes a scanline from the selected scantron file
 5603: 
 5604:  Arguments:
 5605:     line             - The text of the scantron file line to process
 5606:     whichline        - Line number
 5607:     scantron_config  - Hash describing the format of the scantron lines.
 5608:     scan_data        - Hash of extra information about the scanline
 5609:                        (see scantron_getfile for more information)
 5610:     just_header      - True if should not process question answers but only
 5611:                        the stuff to the left of the answers.
 5612:  Returns:
 5613:    Hash containing the result of parsing the scanline
 5614: 
 5615:    Keys are all proceeded by the string 'scantron.'
 5616: 
 5617:        CODE    - the CODE in use for this scanline
 5618:        useCODE - 1 if the CODE is invalid but it usage has been forced
 5619:                  by the operator
 5620:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 5621:                             CODEs were selected, but the usage has been
 5622:                             forced by the operator
 5623:        ID  - student/employee ID
 5624:        PaperID - if used, the ID number printed on the sheet when the 
 5625:                  paper was scanned
 5626:        FirstName - first name from the sheet
 5627:        LastName  - last name from the sheet
 5628: 
 5629:      if just_header was not true these key may also exist
 5630: 
 5631:        missingerror - a list of bubble ranges that are considered to be answers
 5632:                       to a single question that don't have any bubbles filled in.
 5633:                       Of the form questionnumber:firstbubblenumber:count.
 5634:        doubleerror  - a list of bubble ranges that are considered to be answers
 5635:                       to a single question that have more than one bubble filled in.
 5636:                       Of the form questionnumber::firstbubblenumber:count
 5637:    
 5638:                 In the above, count is the number of bubble responses in the
 5639:                 input line needed to represent the possible answers to the question.
 5640:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 5641:                 per line would have count = 2.
 5642: 
 5643:        maxquest     - the number of the last bubble line that was parsed
 5644: 
 5645:        (<number> starts at 1)
 5646:        <number>.answer - zero or more letters representing the selected
 5647:                          letters from the scanline for the bubble line 
 5648:                          <number>.
 5649:                          if blank there was either no bubble or there where
 5650:                          multiple bubbles, (consult the keys missingerror and
 5651:                          doubleerror if this is an error condition)
 5652: 
 5653: =cut
 5654: 
 5655: sub scantron_parse_scanline {
 5656:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
 5657: 
 5658:     my %record;
 5659:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 5660:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 5661:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
 5662:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 5663: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 5664: 	if ($$scantron_config{'CODElocation'} < 0 ||
 5665: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 5666: 	    $$scantron_config{'CODElocation'} eq 'number') {
 5667: 	    $record{'scantron.CODE'}=substr($data,
 5668: 					    $$scantron_config{'CODEstart'}-1,
 5669: 					    $$scantron_config{'CODElength'});
 5670: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 5671: 		$record{'scantron.useCODE'}=1;
 5672: 	    }
 5673: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 5674: 		$record{'scantron.CODE_ignore_dup'}=1;
 5675: 	    }
 5676: 	} else {
 5677: 	    #FIXME interpret first N questions
 5678: 	}
 5679:     }
 5680:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 5681: 				  $$scantron_config{'IDlength'});
 5682:     $record{'scantron.PaperID'}=
 5683: 	substr($data,$$scantron_config{'PaperID'}-1,
 5684: 	       $$scantron_config{'PaperIDlength'});
 5685:     $record{'scantron.FirstName'}=
 5686: 	substr($data,$$scantron_config{'FirstName'}-1,
 5687: 	       $$scantron_config{'FirstNamelength'});
 5688:     $record{'scantron.LastName'}=
 5689: 	substr($data,$$scantron_config{'LastName'}-1,
 5690: 	       $$scantron_config{'LastNamelength'});
 5691:     if ($just_header) { return \%record; }
 5692: 
 5693:     my @alphabet=('A'..'Z');
 5694:     my $questnum=0;
 5695:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 5696: 
 5697:     chomp($questions);		# Get rid of any trailing \n.
 5698:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 5699:     while (length($questions)) {
 5700: 	my $answers_needed = $bubble_lines_per_response{$questnum};
 5701:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 5702:                              || 1;
 5703:         $questnum++;
 5704:         my $quest_id = $questnum;
 5705:         my $currentquest = substr($questions,0,$answer_length);
 5706:         $questions       = substr($questions,$answer_length);
 5707:         if (length($currentquest) < $answer_length) { next; }
 5708: 
 5709:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
 5710:             my $subquestnum = 1;
 5711:             my $subquestions = $currentquest;
 5712:             my @subanswers_needed = 
 5713:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
 5714:             foreach my $subans (@subanswers_needed) {
 5715:                 my $subans_length =
 5716:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 5717:                 my $currsubquest = substr($subquestions,0,$subans_length);
 5718:                 $subquestions   = substr($subquestions,$subans_length);
 5719:                 $quest_id = "$questnum.$subquestnum";
 5720:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 5721:                     ($$scantron_config{'Qon'} eq 'number')) {
 5722:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 5723:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 5724:                         \@alphabet,\%record,$scantron_config,$scan_data);
 5725:                 } else {
 5726:                     $ansnum = &scantron_validator_positional($ansnum,
 5727:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
 5728:                 }
 5729:                 $subquestnum ++;
 5730:             }
 5731:         } else {
 5732:             if (($$scantron_config{'Qon'} eq 'letter') ||
 5733:                 ($$scantron_config{'Qon'} eq 'number')) {
 5734:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 5735:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5736:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5737:             } else {
 5738:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 5739:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5740:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5741:             }
 5742:         }
 5743:     }
 5744:     $record{'scantron.maxquest'}=$questnum;
 5745:     return \%record;
 5746: }
 5747: 
 5748: sub scantron_validator_lettnum {
 5749:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 5750:         $alphabet,$record,$scantron_config,$scan_data) = @_;
 5751: 
 5752:     # Qon 'letter' implies for each slot in currquest we have:
 5753:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 5754:     #    about anything else (esp. a value of Qoff) for missing
 5755:     #    bubbles.
 5756:     #
 5757:     # Qon 'number' implies each slot gives a digit that indexes the
 5758:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 5759:     #    and * or ? for double bubbles on a single line.
 5760:     #
 5761: 
 5762:     my $matchon;
 5763:     if ($$scantron_config{'Qon'} eq 'letter') {
 5764:         $matchon = '[A-Z]';
 5765:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 5766:         $matchon = '\d';
 5767:     }
 5768:     my $occurrences = 0;
 5769:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5770:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5771:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5772:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5773:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5774:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5775:         my @singlelines = split('',$currquest);
 5776:         foreach my $entry (@singlelines) {
 5777:             $occurrences = &occurence_count($entry,$matchon);
 5778:             if ($occurrences > 1) {
 5779:                 last;
 5780:             }
 5781:         } 
 5782:     } else {
 5783:         $occurrences = &occurence_count($currquest,$matchon); 
 5784:     }
 5785:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 5786:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5787:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5788:             my $bubble = substr($currquest,$ans,1);
 5789:             if ($bubble =~ /$matchon/ ) {
 5790:                 if ($$scantron_config{'Qon'} eq 'number') {
 5791:                     if ($bubble == 0) {
 5792:                         $bubble = 10; 
 5793:                     }
 5794:                     $record->{"scantron.$ansnum.answer"} = 
 5795:                         $alphabet->[$bubble-1];
 5796:                 } else {
 5797:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 5798:                 }
 5799:             } else {
 5800:                 $record->{"scantron.$ansnum.answer"}='';
 5801:             }
 5802:             $ansnum++;
 5803:         }
 5804:     } elsif (!defined($currquest)
 5805:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 5806:             || (&occurence_count($currquest,$matchon) == 0)) {
 5807:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5808:             $record->{"scantron.$ansnum.answer"}='';
 5809:             $ansnum++;
 5810:         }
 5811:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5812:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 5813:         }
 5814:     } else {
 5815:         if ($$scantron_config{'Qon'} eq 'number') {
 5816:             $currquest = &digits_to_letters($currquest);            
 5817:         }
 5818:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5819:             my $bubble = substr($currquest,$ans,1);
 5820:             $record->{"scantron.$ansnum.answer"} = $bubble;
 5821:             $ansnum++;
 5822:         }
 5823:     }
 5824:     return $ansnum;
 5825: }
 5826: 
 5827: sub scantron_validator_positional {
 5828:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 5829:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
 5830: 
 5831:     # Otherwise there's a positional notation;
 5832:     # each bubble line requires Qlength items, and there are filled in
 5833:     # bubbles for each case where there 'Qon' characters.
 5834:     #
 5835: 
 5836:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 5837: 
 5838:     # If the split only gives us one element.. the full length of the
 5839:     # answer string, no bubbles are filled in:
 5840: 
 5841:     if ($answers_needed eq '') {
 5842:         return;
 5843:     }
 5844: 
 5845:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 5846:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5847:             $record->{"scantron.$ansnum.answer"}='';
 5848:             $ansnum++;
 5849:         }
 5850:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5851:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 5852:         }
 5853:     } elsif (scalar(@array) == 2) {
 5854:         my $location = length($array[0]);
 5855:         my $line_num = int($location / $$scantron_config{'Qlength'});
 5856:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 5857:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5858:             if ($ans eq $line_num) {
 5859:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 5860:             } else {
 5861:                 $record->{"scantron.$ansnum.answer"} = ' ';
 5862:             }
 5863:             $ansnum++;
 5864:          }
 5865:     } else {
 5866:         #  If there's more than one instance of a bubble character
 5867:         #  That's a double bubble; with positional notation we can
 5868:         #  record all the bubbles filled in as well as the
 5869:         #  fact this response consists of multiple bubbles.
 5870:         #
 5871:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5872:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5873:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5874:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5875:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5876:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5877:             my $doubleerror = 0;
 5878:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 5879:                    (!$doubleerror)) {
 5880:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 5881:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 5882:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 5883:                if (length(@currarray) > 2) {
 5884:                    $doubleerror = 1;
 5885:                } 
 5886:             }
 5887:             if ($doubleerror) {
 5888:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5889:             }
 5890:         } else {
 5891:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5892:         }
 5893:         my $item = $ansnum;
 5894:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5895:             $record->{"scantron.$item.answer"} = '';
 5896:             $item ++;
 5897:         }
 5898: 
 5899:         my @ans=@array;
 5900:         my $i=0;
 5901:         my $increment = 0;
 5902:         while ($#ans) {
 5903:             $i+=length($ans[0]) + $increment;
 5904:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 5905:             my $bubble = $i%$$scantron_config{'Qlength'};
 5906:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 5907:             shift(@ans);
 5908:             $increment = 1;
 5909:         }
 5910:         $ansnum += $answers_needed;
 5911:     }
 5912:     return $ansnum;
 5913: }
 5914: 
 5915: =pod
 5916: 
 5917: =item scantron_add_delay
 5918: 
 5919:    Adds an error message that occurred during the grading phase to a
 5920:    queue of messages to be shown after grading pass is complete
 5921: 
 5922:  Arguments:
 5923:    $delayqueue  - arrary ref of hash ref of error messages
 5924:    $scanline    - the scanline that caused the error
 5925:    $errormesage - the error message
 5926:    $errorcode   - a numeric code for the error
 5927: 
 5928:  Side Effects:
 5929:    updates the $delayqueue to have a new hash ref of the error
 5930: 
 5931: =cut
 5932: 
 5933: sub scantron_add_delay {
 5934:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 5935:     push(@$delayqueue,
 5936: 	 {'line' => $scanline, 'emsg' => $errormessage,
 5937: 	  'ecode' => $errorcode }
 5938: 	 );
 5939: }
 5940: 
 5941: =pod
 5942: 
 5943: =item scantron_find_student
 5944: 
 5945:    Finds the username for the current scanline
 5946: 
 5947:   Arguments:
 5948:    $scantron_record - hash result from scantron_parse_scanline
 5949:    $scan_data       - hash of correction information 
 5950:                       (see &scantron_getfile() form more information)
 5951:    $idmap           - hash from &username_to_idmap()
 5952:    $line            - number of current scanline
 5953:  
 5954:   Returns:
 5955:    Either 'username:domain' or undef if unknown
 5956: 
 5957: =cut
 5958: 
 5959: sub scantron_find_student {
 5960:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 5961:     my $scanID=$$scantron_record{'scantron.ID'};
 5962:     if ($scanID =~ /^\s*$/) {
 5963:  	return &scan_data($scan_data,"$line.user");
 5964:     }
 5965:     foreach my $id (keys(%$idmap)) {
 5966:  	if (lc($id) eq lc($scanID)) {
 5967:  	    return $$idmap{$id};
 5968:  	}
 5969:     }
 5970:     return undef;
 5971: }
 5972: 
 5973: =pod
 5974: 
 5975: =item scantron_filter
 5976: 
 5977:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 5978:    hidden resources was selected
 5979: 
 5980: =cut
 5981: 
 5982: sub scantron_filter {
 5983:     my ($curres)=@_;
 5984: 
 5985:     if (ref($curres) && $curres->is_problem()) {
 5986: 	# if the user has asked to not have either hidden
 5987: 	# or 'randomout' controlled resources to be graded
 5988: 	# don't include them
 5989: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 5990: 	    && $curres->randomout) {
 5991: 	    return 0;
 5992: 	}
 5993: 	return 1;
 5994:     }
 5995:     return 0;
 5996: }
 5997: 
 5998: =pod
 5999: 
 6000: =item scantron_process_corrections
 6001: 
 6002:    Gets correction information out of submitted form data and corrects
 6003:    the scanline
 6004: 
 6005: =cut
 6006: 
 6007: sub scantron_process_corrections {
 6008:     my ($r) = @_;
 6009:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6010:     my ($scanlines,$scan_data)=&scantron_getfile();
 6011:     my $classlist=&Apache::loncoursedata::get_classlist();
 6012:     my $which=$env{'form.scantron_line'};
 6013:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 6014:     my ($skip,$err,$errmsg);
 6015:     if ($env{'form.scantron_skip_record'}) {
 6016: 	$skip=1;
 6017:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 6018: 	my $newstudent=$env{'form.scantron_username'}.':'.
 6019: 	    $env{'form.scantron_domain'};
 6020: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 6021: 	($line,$err,$errmsg)=
 6022: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6023: 				     'ID',{'newid'=>$newid,
 6024: 				    'username'=>$env{'form.scantron_username'},
 6025: 				    'domain'=>$env{'form.scantron_domain'}});
 6026:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 6027: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 6028: 	my $newCODE;
 6029: 	my %args;
 6030: 	if      ($resolution eq 'use_unfound') {
 6031: 	    $newCODE='use_unfound';
 6032: 	} elsif ($resolution eq 'use_found') {
 6033: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 6034: 	} elsif ($resolution eq 'use_typed') {
 6035: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 6036: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 6037: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 6038: 	}
 6039: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 6040: 	    $args{'CODE_ignore_dup'}=1;
 6041: 	}
 6042: 	$args{'CODE'}=$newCODE;
 6043: 	($line,$err,$errmsg)=
 6044: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6045: 				     'CODE',\%args);
 6046:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 6047: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 6048: 	    ($line,$err,$errmsg)=
 6049: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 6050: 					 $which,'answer',
 6051: 					 { 'question'=>$question,
 6052: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 6053:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 6054: 	    if ($err) { last; }
 6055: 	}
 6056:     }
 6057:     if ($err) {
 6058: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
 6059:     } else {
 6060: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 6061: 	&scantron_putfile($scanlines,$scan_data);
 6062:     }
 6063: }
 6064: 
 6065: =pod
 6066: 
 6067: =item reset_skipping_status
 6068: 
 6069:    Forgets the current set of remember skipped scanlines (and thus
 6070:    reverts back to considering all lines in the
 6071:    scantron_skipped_<filename> file)
 6072: 
 6073: =cut
 6074: 
 6075: sub reset_skipping_status {
 6076:     my ($scanlines,$scan_data)=&scantron_getfile();
 6077:     &scan_data($scan_data,'remember_skipping',undef,1);
 6078:     &scantron_putfile(undef,$scan_data);
 6079: }
 6080: 
 6081: =pod
 6082: 
 6083: =item start_skipping
 6084: 
 6085:    Marks a scanline to be skipped. 
 6086: 
 6087: =cut
 6088: 
 6089: sub start_skipping {
 6090:     my ($scan_data,$i)=@_;
 6091:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6092:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 6093: 	$remembered{$i}=2;
 6094:     } else {
 6095: 	$remembered{$i}=1;
 6096:     }
 6097:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 6098: }
 6099: 
 6100: =pod
 6101: 
 6102: =item should_be_skipped
 6103: 
 6104:    Checks whether a scanline should be skipped.
 6105: 
 6106: =cut
 6107: 
 6108: sub should_be_skipped {
 6109:     my ($scanlines,$scan_data,$i)=@_;
 6110:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 6111: 	# not redoing old skips
 6112: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 6113: 	return 0;
 6114:     }
 6115:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6116: 
 6117:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 6118: 	return 0;
 6119:     }
 6120:     return 1;
 6121: }
 6122: 
 6123: =pod
 6124: 
 6125: =item remember_current_skipped
 6126: 
 6127:    Discovers what scanlines are in the scantron_skipped_<filename>
 6128:    file and remembers them into scan_data for later use.
 6129: 
 6130: =cut
 6131: 
 6132: sub remember_current_skipped {
 6133:     my ($scanlines,$scan_data)=&scantron_getfile();
 6134:     my %to_remember;
 6135:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6136: 	if ($scanlines->{'skipped'}[$i]) {
 6137: 	    $to_remember{$i}=1;
 6138: 	}
 6139:     }
 6140: 
 6141:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 6142:     &scantron_putfile(undef,$scan_data);
 6143: }
 6144: 
 6145: =pod
 6146: 
 6147: =item check_for_error
 6148: 
 6149:     Checks if there was an error when attempting to remove a specific
 6150:     scantron_.. bubble sheet data file. Prints out an error if
 6151:     something went wrong.
 6152: 
 6153: =cut
 6154: 
 6155: sub check_for_error {
 6156:     my ($r,$result)=@_;
 6157:     if ($result ne 'ok' && $result ne 'not_found' ) {
 6158: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 6159:     }
 6160: }
 6161: 
 6162: =pod
 6163: 
 6164: =item scantron_warning_screen
 6165: 
 6166:    Interstitial screen to make sure the operator has selected the
 6167:    correct options before we start the validation phase.
 6168: 
 6169: =cut
 6170: 
 6171: sub scantron_warning_screen {
 6172:     my ($button_text)=@_;
 6173:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 6174:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6175:     my $CODElist;
 6176:     if ($scantron_config{'CODElocation'} &&
 6177: 	$scantron_config{'CODEstart'} &&
 6178: 	$scantron_config{'CODElength'}) {
 6179: 	$CODElist=$env{'form.scantron_CODElist'};
 6180: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
 6181: 	$CODElist=
 6182: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 6183: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 6184:     }
 6185:     return ('
 6186: <p>
 6187: <span class="LC_warning">
 6188: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
 6189: </p>
 6190: <table>
 6191: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 6192: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 6193: '.$CODElist.'
 6194: </table>
 6195: <br />
 6196: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
 6197: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
 6198: 
 6199: <br />
 6200: ');
 6201: }
 6202: 
 6203: =pod
 6204: 
 6205: =item scantron_do_warning
 6206: 
 6207:    Check if the operator has picked something for all required
 6208:    fields. Error out if something is missing.
 6209: 
 6210: =cut
 6211: 
 6212: sub scantron_do_warning {
 6213:     my ($r,$symb)=@_;
 6214:     if (!$symb) {return '';}
 6215:     my $default_form_data=&defaultFormData($symb);
 6216:     $r->print(&scantron_form_start().$default_form_data);
 6217:     if ( $env{'form.selectpage'} eq '' ||
 6218: 	 $env{'form.scantron_selectfile'} eq '' ||
 6219: 	 $env{'form.scantron_format'} eq '' ) {
 6220: 	$r->print("<p>".&mt('You have forgetten to specify some information. Please go Back and try again.')."</p>");
 6221: 	if ( $env{'form.selectpage'} eq '') {
 6222: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 6223: 	} 
 6224: 	if ( $env{'form.scantron_selectfile'} eq '') {
 6225: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a file that contains the student\'s response data.').'</span></p>');
 6226: 	} 
 6227: 	if ( $env{'form.scantron_format'} eq '') {
 6228: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a the format of the student\'s response data.').'</span></p>');
 6229: 	} 
 6230:     } else {
 6231: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
 6232: 	$r->print('
 6233: '.$warning.'
 6234: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 6235: <input type="hidden" name="command" value="scantron_validate" />
 6236: ');
 6237:     }
 6238:     $r->print("</form><br />".&show_grading_menu_form($symb));
 6239:     return '';
 6240: }
 6241: 
 6242: =pod
 6243: 
 6244: =item scantron_form_start
 6245: 
 6246:     html hidden input for remembering all selected grading options
 6247: 
 6248: =cut
 6249: 
 6250: sub scantron_form_start {
 6251:     my ($max_bubble)=@_;
 6252:     my $result= <<SCANTRONFORM;
 6253: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 6254:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 6255:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 6256:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 6257:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 6258:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 6259:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 6260:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 6261:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 6262:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 6263: SCANTRONFORM
 6264: 
 6265:   my $line = 0;
 6266:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 6267:        my $chunk =
 6268: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 6269:        $chunk .=
 6270: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 6271:        $chunk .= 
 6272:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 6273:        $chunk .=
 6274:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 6275:        $result .= $chunk;
 6276:        $line++;
 6277:    }
 6278:     return $result;
 6279: }
 6280: 
 6281: =pod
 6282: 
 6283: =item scantron_validate_file
 6284: 
 6285:     Dispatch routine for doing validation of a bubble sheet data file.
 6286: 
 6287:     Also processes any necessary information resets that need to
 6288:     occur before validation begins (ignore previous corrections,
 6289:     restarting the skipped records processing)
 6290: 
 6291: =cut
 6292: 
 6293: sub scantron_validate_file {
 6294:     my ($r,$symb) = @_;
 6295:     if (!$symb) {return '';}
 6296:     my $default_form_data=&defaultFormData($symb);
 6297:     
 6298:     # do the detection of only doing skipped records first befroe we delete
 6299:     # them when doing the corrections reset
 6300:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 6301: 	&reset_skipping_status();
 6302:     }
 6303:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 6304: 	&remember_current_skipped();
 6305: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 6306:     }
 6307: 
 6308:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 6309: 	&check_for_error($r,&scantron_remove_file('corrected'));
 6310: 	&check_for_error($r,&scantron_remove_file('skipped'));
 6311: 	&check_for_error($r,&scantron_remove_scan_data());
 6312: 	$env{'form.scantron_options_ignore'}='done';
 6313:     }
 6314: 
 6315:     if ($env{'form.scantron_corrections'}) {
 6316: 	&scantron_process_corrections($r);
 6317:     }
 6318:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 6319:     #get the student pick code ready
 6320:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 6321:     my $nav_error;
 6322:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
 6323:     if ($nav_error) {
 6324:         $r->print(&navmap_errormsg());
 6325:         return '';
 6326:     }
 6327:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 6328:     $r->print($result);
 6329:     
 6330:     my @validate_phases=( 'sequence',
 6331: 			  'ID',
 6332: 			  'CODE',
 6333: 			  'doublebubble',
 6334: 			  'missingbubbles');
 6335:     if (!$env{'form.validatepass'}) {
 6336: 	$env{'form.validatepass'} = 0;
 6337:     }
 6338:     my $currentphase=$env{'form.validatepass'};
 6339: 
 6340: 
 6341:     my $stop=0;
 6342:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 6343: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 6344: 	$r->rflush();
 6345: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 6346: 	{
 6347: 	    no strict 'refs';
 6348: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 6349: 	}
 6350:     }
 6351:     if (!$stop) {
 6352: 	my $warning=&scantron_warning_screen('Start Grading');
 6353: 	$r->print(&mt('Validation process complete.').'<br />'.
 6354:                   $warning.
 6355:                   &mt('Perform verification for each student after storage of submissions?').
 6356:                   '&nbsp;<span class="LC_nobreak"><label>'.
 6357:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 6358:                   ('&nbsp;'x3).'<label>'.
 6359:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 6360:                   '</label></span><br />'.
 6361:                   &mt('Grading will take longer if you use verification.').'<br />'.
 6362:                   &mt("Alternatively, the 'Review bubblesheet data' utility (see grading menu) can be used for all students after grading is complete.").'<br /><br />'.
 6363:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 6364:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 6365:     } else {
 6366: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 6367: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 6368:     }
 6369:     if ($stop) {
 6370: 	if ($validate_phases[$currentphase] eq 'sequence') {
 6371: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 6372: 	    $r->print(' '.&mt('this error').' <br />');
 6373: 
 6374: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
 6375: 	} else {
 6376:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 6377: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 6378:             } else {
 6379:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 6380:             }
 6381: 	    $r->print(' '.&mt('using corrected info').' <br />');
 6382: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 6383: 	    $r->print(" ".&mt("this scanline saving it for later."));
 6384: 	}
 6385:     }
 6386:     $r->print(" </form><br />".&show_grading_menu_form($symb));
 6387:     return '';
 6388: }
 6389: 
 6390: 
 6391: =pod
 6392: 
 6393: =item scantron_remove_file
 6394: 
 6395:    Removes the requested bubble sheet data file, makes sure that
 6396:    scantron_original_<filename> is never removed
 6397: 
 6398: 
 6399: =cut
 6400: 
 6401: sub scantron_remove_file {
 6402:     my ($which)=@_;
 6403:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6404:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6405:     my $file='scantron_';
 6406:     if ($which eq 'corrected' || $which eq 'skipped') {
 6407: 	$file.=$which.'_';
 6408:     } else {
 6409: 	return 'refused';
 6410:     }
 6411:     $file.=$env{'form.scantron_selectfile'};
 6412:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 6413: }
 6414: 
 6415: 
 6416: =pod
 6417: 
 6418: =item scantron_remove_scan_data
 6419: 
 6420:    Removes all scan_data correction for the requested bubble sheet
 6421:    data file.  (In the case that both the are doing skipped records we need
 6422:    to remember the old skipped lines for the time being so that element
 6423:    persists for a while.)
 6424: 
 6425: =cut
 6426: 
 6427: sub scantron_remove_scan_data {
 6428:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6429:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6430:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 6431:     my @todelete;
 6432:     my $filename=$env{'form.scantron_selectfile'};
 6433:     foreach my $key (@keys) {
 6434: 	if ($key=~/^\Q$filename\E_/) {
 6435: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 6436: 		$key=~/remember_skipping/) {
 6437: 		next;
 6438: 	    }
 6439: 	    push(@todelete,$key);
 6440: 	}
 6441:     }
 6442:     my $result;
 6443:     if (@todelete) {
 6444: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 6445: 				       \@todelete,$cdom,$cname);
 6446:     } else {
 6447: 	$result = 'ok';
 6448:     }
 6449:     return $result;
 6450: }
 6451: 
 6452: 
 6453: =pod
 6454: 
 6455: =item scantron_getfile
 6456: 
 6457:     Fetches the requested bubble sheet data file (all 3 versions), and
 6458:     the scan_data hash
 6459:   
 6460:   Arguments:
 6461:     None
 6462: 
 6463:   Returns:
 6464:     2 hash references
 6465: 
 6466:      - first one has 
 6467:          orig      -
 6468:          corrected -
 6469:          skipped   -  each of which points to an array ref of the specified
 6470:                       file broken up into individual lines
 6471:          count     - number of scanlines
 6472:  
 6473:      - second is the scan_data hash possible keys are
 6474:        ($number refers to scanline numbered $number and thus the key affects
 6475:         only that scanline
 6476:         $bubline refers to the specific bubble line element and the aspects
 6477:         refers to that specific bubble line element)
 6478: 
 6479:        $number.user - username:domain to use
 6480:        $number.CODE_ignore_dup 
 6481:                     - ignore the duplicate CODE error 
 6482:        $number.useCODE
 6483:                     - use the CODE in the scanline as is
 6484:        $number.no_bubble.$bubline
 6485:                     - it is valid that there is no bubbled in bubble
 6486:                       at $number $bubline
 6487:        remember_skipping
 6488:                     - a frozen hash containing keys of $number and values
 6489:                       of either 
 6490:                         1 - we are on a 'do skipped records pass' and plan
 6491:                             on processing this line
 6492:                         2 - we are on a 'do skipped records pass' and this
 6493:                             scanline has been marked to skip yet again
 6494: 
 6495: =cut
 6496: 
 6497: sub scantron_getfile {
 6498:     #FIXME really would prefer a scantron directory
 6499:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6500:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6501:     my $lines;
 6502:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6503: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 6504:     my %scanlines;
 6505:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 6506:     my $temp=$scanlines{'orig'};
 6507:     $scanlines{'count'}=$#$temp;
 6508: 
 6509:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6510: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 6511:     if ($lines eq '-1') {
 6512: 	$scanlines{'corrected'}=[];
 6513:     } else {
 6514: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 6515:     }
 6516:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6517: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 6518:     if ($lines eq '-1') {
 6519: 	$scanlines{'skipped'}=[];
 6520:     } else {
 6521: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 6522:     }
 6523:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 6524:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 6525:     my %scan_data = @tmp;
 6526:     return (\%scanlines,\%scan_data);
 6527: }
 6528: 
 6529: =pod
 6530: 
 6531: =item lonnet_putfile
 6532: 
 6533:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 6534: 
 6535:  Arguments:
 6536:    $contents - data to store
 6537:    $filename - filename to store $contents into
 6538: 
 6539:  Returns:
 6540:    result value from &Apache::lonnet::finishuserfileupload
 6541: 
 6542: =cut
 6543: 
 6544: sub lonnet_putfile {
 6545:     my ($contents,$filename)=@_;
 6546:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6547:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6548:     $env{'form.sillywaytopassafilearound'}=$contents;
 6549:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 6550: 
 6551: }
 6552: 
 6553: =pod
 6554: 
 6555: =item scantron_putfile
 6556: 
 6557:     Stores the current version of the bubble sheet data files, and the
 6558:     scan_data hash. (Does not modify the original version only the
 6559:     corrected and skipped versions.
 6560: 
 6561:  Arguments:
 6562:     $scanlines - hash ref that looks like the first return value from
 6563:                  &scantron_getfile()
 6564:     $scan_data - hash ref that looks like the second return value from
 6565:                  &scantron_getfile()
 6566: 
 6567: =cut
 6568: 
 6569: sub scantron_putfile {
 6570:     my ($scanlines,$scan_data) = @_;
 6571:     #FIXME really would prefer a scantron directory
 6572:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6573:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6574:     if ($scanlines) {
 6575: 	my $prefix='scantron_';
 6576: # no need to update orig, shouldn't change
 6577: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 6578: #		    $env{'form.scantron_selectfile'});
 6579: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 6580: 			$prefix.'corrected_'.
 6581: 			$env{'form.scantron_selectfile'});
 6582: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 6583: 			$prefix.'skipped_'.
 6584: 			$env{'form.scantron_selectfile'});
 6585:     }
 6586:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 6587: }
 6588: 
 6589: =pod
 6590: 
 6591: =item scantron_get_line
 6592: 
 6593:    Returns the correct version of the scanline
 6594: 
 6595:  Arguments:
 6596:     $scanlines - hash ref that looks like the first return value from
 6597:                  &scantron_getfile()
 6598:     $scan_data - hash ref that looks like the second return value from
 6599:                  &scantron_getfile()
 6600:     $i         - number of the requested line (starts at 0)
 6601: 
 6602:  Returns:
 6603:    A scanline, (either the original or the corrected one if it
 6604:    exists), or undef if the requested scanline should be
 6605:    skipped. (Either because it's an skipped scanline, or it's an
 6606:    unskipped scanline and we are not doing a 'do skipped scanlines'
 6607:    pass.
 6608: 
 6609: =cut
 6610: 
 6611: sub scantron_get_line {
 6612:     my ($scanlines,$scan_data,$i)=@_;
 6613:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 6614:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 6615:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 6616:     return $scanlines->{'orig'}[$i]; 
 6617: }
 6618: 
 6619: =pod
 6620: 
 6621: =item scantron_todo_count
 6622: 
 6623:     Counts the number of scanlines that need processing.
 6624: 
 6625:  Arguments:
 6626:     $scanlines - hash ref that looks like the first return value from
 6627:                  &scantron_getfile()
 6628:     $scan_data - hash ref that looks like the second return value from
 6629:                  &scantron_getfile()
 6630: 
 6631:  Returns:
 6632:     $count - number of scanlines to process
 6633: 
 6634: =cut
 6635: 
 6636: sub get_todo_count {
 6637:     my ($scanlines,$scan_data)=@_;
 6638:     my $count=0;
 6639:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6640: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6641: 	if ($line=~/^[\s\cz]*$/) { next; }
 6642: 	$count++;
 6643:     }
 6644:     return $count;
 6645: }
 6646: 
 6647: =pod
 6648: 
 6649: =item scantron_put_line
 6650: 
 6651:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
 6652:     data file.
 6653: 
 6654:  Arguments:
 6655:     $scanlines - hash ref that looks like the first return value from
 6656:                  &scantron_getfile()
 6657:     $scan_data - hash ref that looks like the second return value from
 6658:                  &scantron_getfile()
 6659:     $i         - line number to update
 6660:     $newline   - contents of the updated scanline
 6661:     $skip      - if true make the line for skipping and update the
 6662:                  'skipped' file
 6663: 
 6664: =cut
 6665: 
 6666: sub scantron_put_line {
 6667:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 6668:     if ($skip) {
 6669: 	$scanlines->{'skipped'}[$i]=$newline;
 6670: 	&start_skipping($scan_data,$i);
 6671: 	return;
 6672:     }
 6673:     $scanlines->{'corrected'}[$i]=$newline;
 6674: }
 6675: 
 6676: =pod
 6677: 
 6678: =item scantron_clear_skip
 6679: 
 6680:    Remove a line from the 'skipped' file
 6681: 
 6682:  Arguments:
 6683:     $scanlines - hash ref that looks like the first return value from
 6684:                  &scantron_getfile()
 6685:     $scan_data - hash ref that looks like the second return value from
 6686:                  &scantron_getfile()
 6687:     $i         - line number to update
 6688: 
 6689: =cut
 6690: 
 6691: sub scantron_clear_skip {
 6692:     my ($scanlines,$scan_data,$i)=@_;
 6693:     if (exists($scanlines->{'skipped'}[$i])) {
 6694: 	undef($scanlines->{'skipped'}[$i]);
 6695: 	return 1;
 6696:     }
 6697:     return 0;
 6698: }
 6699: 
 6700: =pod
 6701: 
 6702: =item scantron_filter_not_exam
 6703: 
 6704:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 6705:    filter out resources that are not marked as 'exam' mode
 6706: 
 6707: =cut
 6708: 
 6709: sub scantron_filter_not_exam {
 6710:     my ($curres)=@_;
 6711:     
 6712:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 6713: 	# if the user has asked to not have either hidden
 6714: 	# or 'randomout' controlled resources to be graded
 6715: 	# don't include them
 6716: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6717: 	    && $curres->randomout) {
 6718: 	    return 0;
 6719: 	}
 6720: 	return 1;
 6721:     }
 6722:     return 0;
 6723: }
 6724: 
 6725: =pod
 6726: 
 6727: =item scantron_validate_sequence
 6728: 
 6729:     Validates the selected sequence, checking for resource that are
 6730:     not set to exam mode.
 6731: 
 6732: =cut
 6733: 
 6734: sub scantron_validate_sequence {
 6735:     my ($r,$currentphase) = @_;
 6736: 
 6737:     my $navmap=Apache::lonnavmaps::navmap->new();
 6738:     unless (ref($navmap)) {
 6739:         $r->print(&navmap_errormsg());
 6740:         return (1,$currentphase);
 6741:     }
 6742:     my (undef,undef,$sequence)=
 6743: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 6744: 
 6745:     my $map=$navmap->getResourceByUrl($sequence);
 6746: 
 6747:     $r->print('<input type="hidden" name="validate_sequence_exam"
 6748:                                     value="ignore" />');
 6749:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 6750: 	my @resources=
 6751: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 6752: 	if (@resources) {
 6753: 	    $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>");
 6754: 	    return (1,$currentphase);
 6755: 	}
 6756:     }
 6757: 
 6758:     return (0,$currentphase+1);
 6759: }
 6760: 
 6761: 
 6762: 
 6763: sub scantron_validate_ID {
 6764:     my ($r,$currentphase) = @_;
 6765:     
 6766:     #get student info
 6767:     my $classlist=&Apache::loncoursedata::get_classlist();
 6768:     my %idmap=&username_to_idmap($classlist);
 6769: 
 6770:     #get scantron line setup
 6771:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6772:     my ($scanlines,$scan_data)=&scantron_getfile();
 6773: 
 6774:     my $nav_error;
 6775:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble_lines.. array.
 6776:     if ($nav_error) {
 6777:         $r->print(&navmap_errormsg());
 6778:         return(1,$currentphase);
 6779:     }
 6780: 
 6781:     my %found=('ids'=>{},'usernames'=>{});
 6782:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6783: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6784: 	if ($line=~/^[\s\cz]*$/) { next; }
 6785: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 6786: 						 $scan_data);
 6787: 	my $id=$$scan_record{'scantron.ID'};
 6788: 	my $found;
 6789: 	foreach my $checkid (keys(%idmap)) {
 6790: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 6791: 	}
 6792: 	if ($found) {
 6793: 	    my $username=$idmap{$found};
 6794: 	    if ($found{'ids'}{$found}) {
 6795: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6796: 					 $line,'duplicateID',$found);
 6797: 		return(1,$currentphase);
 6798: 	    } elsif ($found{'usernames'}{$username}) {
 6799: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6800: 					 $line,'duplicateID',$username);
 6801: 		return(1,$currentphase);
 6802: 	    }
 6803: 	    #FIXME store away line we previously saw the ID on to use above
 6804: 	    $found{'ids'}{$found}++;
 6805: 	    $found{'usernames'}{$username}++;
 6806: 	} else {
 6807: 	    if ($id =~ /^\s*$/) {
 6808: 		my $username=&scan_data($scan_data,"$i.user");
 6809: 		if (defined($username) && $found{'usernames'}{$username}) {
 6810: 		    &scantron_get_correction($r,$i,$scan_record,
 6811: 					     \%scantron_config,
 6812: 					     $line,'duplicateID',$username);
 6813: 		    return(1,$currentphase);
 6814: 		} elsif (!defined($username)) {
 6815: 		    &scantron_get_correction($r,$i,$scan_record,
 6816: 					     \%scantron_config,
 6817: 					     $line,'incorrectID');
 6818: 		    return(1,$currentphase);
 6819: 		}
 6820: 		$found{'usernames'}{$username}++;
 6821: 	    } else {
 6822: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6823: 					 $line,'incorrectID');
 6824: 		return(1,$currentphase);
 6825: 	    }
 6826: 	}
 6827:     }
 6828: 
 6829:     return (0,$currentphase+1);
 6830: }
 6831: 
 6832: 
 6833: sub scantron_get_correction {
 6834:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
 6835: #FIXME in the case of a duplicated ID the previous line, probably need
 6836: #to show both the current line and the previous one and allow skipping
 6837: #the previous one or the current one
 6838: 
 6839:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 6840: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6841: 			    " for PaperID <tt>[_1]</tt>",
 6842: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
 6843:     } else {
 6844: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6845: 			    " in scanline [_1] <pre>[_2]</pre>",
 6846: 			    $i,$line)."</p> \n");
 6847:     }
 6848:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
 6849: 			  "The name on the paper is [_2],[_3]",
 6850: 			  $$scan_record{'scantron.ID'},
 6851: 			  $$scan_record{'scantron.LastName'},
 6852: 			  $$scan_record{'scantron.FirstName'})."</p>";
 6853: 
 6854:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 6855:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 6856:                            # Array populated for doublebubble or
 6857:     my @lines_to_correct;  # missingbubble errors to build javascript
 6858:                            # to validate radio button checking   
 6859: 
 6860:     if ($error =~ /ID$/) {
 6861: 	if ($error eq 'incorrectID') {
 6862: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
 6863: 		      "</p>\n");
 6864: 	} elsif ($error eq 'duplicateID') {
 6865: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 6866: 	}
 6867: 	$r->print($message);
 6868: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6869: 	$r->print("\n<ul><li> ");
 6870: 	#FIXME it would be nice if this sent back the user ID and
 6871: 	#could do partial userID matches
 6872: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 6873: 				       'scantron_username','scantron_domain'));
 6874: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 6875: 	$r->print("\n@".
 6876: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 6877: 
 6878: 	$r->print('</li>');
 6879:     } elsif ($error =~ /CODE$/) {
 6880: 	if ($error eq 'incorrectCODE') {
 6881: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 6882: 	} elsif ($error eq 'duplicateCODE') {
 6883: 	    $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");
 6884: 	}
 6885: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
 6886: 			    $$scan_record{'scantron.CODE'})."<br />\n");
 6887: 	$r->print($message);
 6888: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6889: 	$r->print("\n<br /> ");
 6890: 	my $i=0;
 6891: 	if ($error eq 'incorrectCODE' 
 6892: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 6893: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 6894: 	    if ($closest > 0) {
 6895: 		foreach my $testcode (@{$closest}) {
 6896: 		    my $checked='';
 6897: 		    if (!$i) { $checked=' checked="checked"'; }
 6898: 		    $r->print("
 6899:    <label>
 6900:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
 6901:        ".&mt("Use the similar CODE [_1] instead.",
 6902: 	    "<b><tt>".$testcode."</tt></b>")."
 6903:     </label>
 6904:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 6905: 		    $r->print("\n<br />");
 6906: 		    $i++;
 6907: 		}
 6908: 	    }
 6909: 	}
 6910: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 6911: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
 6912: 	    $r->print("
 6913:     <label>
 6914:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
 6915:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
 6916: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 6917:     </label>");
 6918: 	    $r->print("\n<br />");
 6919: 	}
 6920: 
 6921: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
 6922: function change_radio(field) {
 6923:     var slct=document.scantronupload.scantron_CODE_resolution;
 6924:     var i;
 6925:     for (i=0;i<slct.length;i++) {
 6926:         if (slct[i].value==field) { slct[i].checked=true; }
 6927:     }
 6928: }
 6929: ENDSCRIPT
 6930: 	my $href="/adm/pickcode?".
 6931: 	   "form=".&escape("scantronupload").
 6932: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 6933: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 6934: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 6935: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 6936: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 6937: 	    $r->print("
 6938:     <label>
 6939:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 6940:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 6941: 	     "<a target='_blank' href='$href'>","</a>")."
 6942:     </label> 
 6943:     ".&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\')" />'));
 6944: 	    $r->print("\n<br />");
 6945: 	}
 6946: 	$r->print("
 6947:     <label>
 6948:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 6949:        ".&mt("Use [_1] as the CODE.",
 6950: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 6951: 	$r->print("\n<br /><br />");
 6952:     } elsif ($error eq 'doublebubble') {
 6953: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 6954: 
 6955: 	# The form field scantron_questions is acutally a list of line numbers.
 6956: 	# represented by this form so:
 6957: 
 6958: 	my $line_list = &questions_to_line_list($arg);
 6959: 
 6960: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 6961: 		  $line_list.'" />');
 6962: 	$r->print($message);
 6963: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 6964: 	foreach my $question (@{$arg}) {
 6965: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 6966:                                                    $scan_record, $error);
 6967:             push(@lines_to_correct,@linenums);
 6968: 	}
 6969:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 6970:     } elsif ($error eq 'missingbubble') {
 6971: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
 6972: 	$r->print($message);
 6973: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 6974: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 6975: 
 6976: 	# The form field scantron_questions is actually a list of line numbers not
 6977: 	# a list of question numbers. Therefore:
 6978: 	#
 6979: 	
 6980: 	my $line_list = &questions_to_line_list($arg);
 6981: 
 6982: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 6983: 		  $line_list.'" />');
 6984: 	foreach my $question (@{$arg}) {
 6985: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 6986:                                                    $scan_record, $error);
 6987:             push(@lines_to_correct,@linenums);
 6988: 	}
 6989:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 6990:     } else {
 6991: 	$r->print("\n<ul>");
 6992:     }
 6993:     $r->print("\n</li></ul>");
 6994: }
 6995: 
 6996: sub verify_bubbles_checked {
 6997:     my (@ansnums) = @_;
 6998:     my $ansnumstr = join('","',@ansnums);
 6999:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 7000:     my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
 7001: function verify_bubble_radio(form) {
 7002:     var ansnumArray = new Array ("$ansnumstr");
 7003:     var need_bubble_count = 0;
 7004:     for (var i=0; i<ansnumArray.length; i++) {
 7005:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 7006:             var bubble_picked = 0; 
 7007:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 7008:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 7009:                     bubble_picked = 1;
 7010:                 }
 7011:             }
 7012:             if (bubble_picked == 0) {
 7013:                 need_bubble_count ++;
 7014:             }
 7015:         }
 7016:     }
 7017:     if (need_bubble_count) {
 7018:         alert("$warning");
 7019:         return;
 7020:     }
 7021:     form.submit(); 
 7022: }
 7023: ENDSCRIPT
 7024:     return $output;
 7025: }
 7026: 
 7027: =pod
 7028: 
 7029: =item  questions_to_line_list
 7030: 
 7031: Converts a list of questions into a string of comma separated
 7032: line numbers in the answer sheet used by the questions.  This is
 7033: used to fill in the scantron_questions form field.
 7034: 
 7035:   Arguments:
 7036:      questions    - Reference to an array of questions.
 7037: 
 7038: =cut
 7039: 
 7040: 
 7041: sub questions_to_line_list {
 7042:     my ($questions) = @_;
 7043:     my @lines;
 7044: 
 7045:     foreach my $item (@{$questions}) {
 7046:         my $question = $item;
 7047:         my ($first,$count,$last);
 7048:         if ($item =~ /^(\d+)\.(\d+)$/) {
 7049:             $question = $1;
 7050:             my $subquestion = $2;
 7051:             $first = $first_bubble_line{$question-1} + 1;
 7052:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7053:             my $subcount = 1;
 7054:             while ($subcount<$subquestion) {
 7055:                 $first += $subans[$subcount-1];
 7056:                 $subcount ++;
 7057:             }
 7058:             $count = $subans[$subquestion-1];
 7059:         } else {
 7060: 	    $first   = $first_bubble_line{$question-1} + 1;
 7061: 	    $count   = $bubble_lines_per_response{$question-1};
 7062:         }
 7063:         $last = $first+$count-1;
 7064:         push(@lines, ($first..$last));
 7065:     }
 7066:     return join(',', @lines);
 7067: }
 7068: 
 7069: =pod 
 7070: 
 7071: =item prompt_for_corrections
 7072: 
 7073: Prompts for a potentially multiline correction to the
 7074: user's bubbling (factors out common code from scantron_get_correction
 7075: for multi and missing bubble cases).
 7076: 
 7077:  Arguments:
 7078:    $r           - Apache request object.
 7079:    $question    - The question number to prompt for.
 7080:    $scan_config - The scantron file configuration hash.
 7081:    $scan_record - Reference to the hash that has the the parsed scanlines.
 7082:    $error       - Type of error
 7083: 
 7084:  Implicit inputs:
 7085:    %bubble_lines_per_response   - Starting line numbers for each question.
 7086:                                   Numbered from 0 (but question numbers are from
 7087:                                   1.
 7088:    %first_bubble_line           - Starting bubble line for each question.
 7089:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 7090:                                   type problems render as separate sub-questions, 
 7091:                                   in exam mode. This hash contains a 
 7092:                                   comma-separated list of the lines per 
 7093:                                   sub-question.
 7094:    %responsetype_per_response   - essayresponse, formularesponse,
 7095:                                   stringresponse, imageresponse, reactionresponse,
 7096:                                   and organicresponse type problem parts can have
 7097:                                   multiple lines per response if the weight
 7098:                                   assigned exceeds 10.  In this case, only
 7099:                                   one bubble per line is permitted, but more 
 7100:                                   than one line might contain bubbles, e.g.
 7101:                                   bubbling of: line 1 - J, line 2 - J, 
 7102:                                   line 3 - B would assign 22 points.  
 7103: 
 7104: =cut
 7105: 
 7106: sub prompt_for_corrections {
 7107:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
 7108:     my ($current_line,$lines);
 7109:     my @linenums;
 7110:     my $questionnum = $question;
 7111:     if ($question =~ /^(\d+)\.(\d+)$/) {
 7112:         $question = $1;
 7113:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7114:         my $subquestion = $2;
 7115:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7116:         my $subcount = 1;
 7117:         while ($subcount<$subquestion) {
 7118:             $current_line += $subans[$subcount-1];
 7119:             $subcount ++;
 7120:         }
 7121:         $lines = $subans[$subquestion-1];
 7122:     } else {
 7123:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7124:         $lines        = $bubble_lines_per_response{$question-1};
 7125:     }
 7126:     if ($lines > 1) {
 7127:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 7128:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
 7129:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
 7130:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
 7131:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
 7132:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
 7133:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
 7134:             $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 />');
 7135:         } else {
 7136:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 7137:         }
 7138:     }
 7139:     for (my $i =0; $i < $lines; $i++) {
 7140:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 7141: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
 7142: 	        		  $questionnum,$error,split('', $selected));
 7143:         push(@linenums,$current_line);
 7144: 	$current_line++;
 7145:     }
 7146:     if ($lines > 1) {
 7147: 	$r->print("<hr /><br />");
 7148:     }
 7149:     return @linenums;
 7150: }
 7151: 
 7152: =pod
 7153: 
 7154: =item scantron_bubble_selector
 7155:   
 7156:    Generates the html radiobuttons to correct a single bubble line
 7157:    possibly showing the existing the selected bubbles if known
 7158: 
 7159:  Arguments:
 7160:     $r           - Apache request object
 7161:     $scan_config - hash from &get_scantron_config()
 7162:     $line        - Number of the line being displayed.
 7163:     $questionnum - Question number (may include subquestion)
 7164:     $error       - Type of error.
 7165:     @selected    - Array of bubbles picked on this line.
 7166: 
 7167: =cut
 7168: 
 7169: sub scantron_bubble_selector {
 7170:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 7171:     my $max=$$scan_config{'Qlength'};
 7172: 
 7173:     my $scmode=$$scan_config{'Qon'};
 7174:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
 7175: 
 7176:     my @alphabet=('A'..'Z');
 7177:     $r->print(&Apache::loncommon::start_data_table().
 7178:               &Apache::loncommon::start_data_table_row());
 7179:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 7180:     for (my $i=0;$i<$max+1;$i++) {
 7181: 	$r->print("\n".'<td align="center">');
 7182: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 7183: 	else { $r->print('&nbsp;'); }
 7184: 	$r->print('</td>');
 7185:     }
 7186:     $r->print(&Apache::loncommon::end_data_table_row().
 7187:               &Apache::loncommon::start_data_table_row());
 7188:     for (my $i=0;$i<$max;$i++) {
 7189: 	$r->print("\n".
 7190: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 7191: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 7192:     }
 7193:     my $nobub_checked = ' ';
 7194:     if ($error eq 'missingbubble') {
 7195:         $nobub_checked = ' checked = "checked" ';
 7196:     }
 7197:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 7198: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 7199:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 7200:               $line.'" value="'.$questionnum.'" /></td>');
 7201:     $r->print(&Apache::loncommon::end_data_table_row().
 7202:               &Apache::loncommon::end_data_table());
 7203: }
 7204: 
 7205: =pod
 7206: 
 7207: =item num_matches
 7208: 
 7209:    Counts the number of characters that are the same between the two arguments.
 7210: 
 7211:  Arguments:
 7212:    $orig - CODE from the scanline
 7213:    $code - CODE to match against
 7214: 
 7215:  Returns:
 7216:    $count - integer count of the number of same characters between the
 7217:             two arguments
 7218: 
 7219: =cut
 7220: 
 7221: sub num_matches {
 7222:     my ($orig,$code) = @_;
 7223:     my @code=split(//,$code);
 7224:     my @orig=split(//,$orig);
 7225:     my $same=0;
 7226:     for (my $i=0;$i<scalar(@code);$i++) {
 7227: 	if ($code[$i] eq $orig[$i]) { $same++; }
 7228:     }
 7229:     return $same;
 7230: }
 7231: 
 7232: =pod
 7233: 
 7234: =item scantron_get_closely_matching_CODEs
 7235: 
 7236:    Cycles through all CODEs and finds the set that has the greatest
 7237:    number of same characters as the provided CODE
 7238: 
 7239:  Arguments:
 7240:    $allcodes - hash ref returned by &get_codes()
 7241:    $CODE     - CODE from the current scanline
 7242: 
 7243:  Returns:
 7244:    2 element list
 7245:     - first elements is number of how closely matching the best fit is 
 7246:       (5 means best set has 5 matching characters)
 7247:     - second element is an arrary ref containing the set of valid CODEs
 7248:       that best fit the passed in CODE
 7249: 
 7250: =cut
 7251: 
 7252: sub scantron_get_closely_matching_CODEs {
 7253:     my ($allcodes,$CODE)=@_;
 7254:     my @CODEs;
 7255:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 7256: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 7257:     }
 7258: 
 7259:     return ($#CODEs,$CODEs[-1]);
 7260: }
 7261: 
 7262: =pod
 7263: 
 7264: =item get_codes
 7265: 
 7266:    Builds a hash which has keys of all of the valid CODEs from the selected
 7267:    set of remembered CODEs.
 7268: 
 7269:  Arguments:
 7270:   $old_name - name of the set of remembered CODEs
 7271:   $cdom     - domain of the course
 7272:   $cnum     - internal course name
 7273: 
 7274:  Returns:
 7275:   %allcodes - keys are the valid CODEs, values are all 1
 7276: 
 7277: =cut
 7278: 
 7279: sub get_codes {
 7280:     my ($old_name, $cdom, $cnum) = @_;
 7281:     if (!$old_name) {
 7282: 	$old_name=$env{'form.scantron_CODElist'};
 7283:     }
 7284:     if (!$cdom) {
 7285: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 7286:     }
 7287:     if (!$cnum) {
 7288: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 7289:     }
 7290:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 7291: 				    $cdom,$cnum);
 7292:     my %allcodes;
 7293:     if ($result{"type\0$old_name"} eq 'number') {
 7294: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 7295:     } else {
 7296: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 7297:     }
 7298:     return %allcodes;
 7299: }
 7300: 
 7301: =pod
 7302: 
 7303: =item scantron_validate_CODE
 7304: 
 7305:    Validates all scanlines in the selected file to not have any
 7306:    invalid or underspecified CODEs and that none of the codes are
 7307:    duplicated if this was requested.
 7308: 
 7309: =cut
 7310: 
 7311: sub scantron_validate_CODE {
 7312:     my ($r,$currentphase) = @_;
 7313:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7314:     if ($scantron_config{'CODElocation'} &&
 7315: 	$scantron_config{'CODEstart'} &&
 7316: 	$scantron_config{'CODElength'}) {
 7317: 	if (!defined($env{'form.scantron_CODElist'})) {
 7318: 	    &FIXME_blow_up()
 7319: 	}
 7320:     } else {
 7321: 	return (0,$currentphase+1);
 7322:     }
 7323:     
 7324:     my %usedCODEs;
 7325: 
 7326:     my %allcodes=&get_codes();
 7327: 
 7328:     my $nav_error;
 7329:     &scantron_get_maxbubble(\$nav_error); # parse needs the lines per response array.
 7330:     if ($nav_error) {
 7331:         $r->print(&navmap_errormsg());
 7332:         return(1,$currentphase);
 7333:     }
 7334: 
 7335:     my ($scanlines,$scan_data)=&scantron_getfile();
 7336:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7337: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7338: 	if ($line=~/^[\s\cz]*$/) { next; }
 7339: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7340: 						 $scan_data);
 7341: 	my $CODE=$$scan_record{'scantron.CODE'};
 7342: 	my $error=0;
 7343: 	if (!&Apache::lonnet::validCODE($CODE)) {
 7344: 	    &scantron_get_correction($r,$i,$scan_record,
 7345: 				     \%scantron_config,
 7346: 				     $line,'incorrectCODE',\%allcodes);
 7347: 	    return(1,$currentphase);
 7348: 	}
 7349: 	if (%allcodes && !exists($allcodes{$CODE}) 
 7350: 	    && !$$scan_record{'scantron.useCODE'}) {
 7351: 	    &scantron_get_correction($r,$i,$scan_record,
 7352: 				     \%scantron_config,
 7353: 				     $line,'incorrectCODE',\%allcodes);
 7354: 	    return(1,$currentphase);
 7355: 	}
 7356: 	if (exists($usedCODEs{$CODE}) 
 7357: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 7358: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 7359: 	    &scantron_get_correction($r,$i,$scan_record,
 7360: 				     \%scantron_config,
 7361: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 7362: 	    return(1,$currentphase);
 7363: 	}
 7364: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 7365:     }
 7366:     return (0,$currentphase+1);
 7367: }
 7368: 
 7369: =pod
 7370: 
 7371: =item scantron_validate_doublebubble
 7372: 
 7373:    Validates all scanlines in the selected file to not have any
 7374:    bubble lines with multiple bubbles marked.
 7375: 
 7376: =cut
 7377: 
 7378: sub scantron_validate_doublebubble {
 7379:     my ($r,$currentphase) = @_;
 7380:     #get student info
 7381:     my $classlist=&Apache::loncoursedata::get_classlist();
 7382:     my %idmap=&username_to_idmap($classlist);
 7383: 
 7384:     #get scantron line setup
 7385:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7386:     my ($scanlines,$scan_data)=&scantron_getfile();
 7387:     my $nav_error;
 7388:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble line array.
 7389:     if ($nav_error) {
 7390:         $r->print(&navmap_errormsg());
 7391:         return(1,$currentphase);
 7392:     }
 7393: 
 7394:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7395: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7396: 	if ($line=~/^[\s\cz]*$/) { next; }
 7397: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7398: 						 $scan_data);
 7399: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 7400: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 7401: 				 'doublebubble',
 7402: 				 $$scan_record{'scantron.doubleerror'});
 7403:     	return (1,$currentphase);
 7404:     }
 7405:     return (0,$currentphase+1);
 7406: }
 7407: 
 7408: 
 7409: sub scantron_get_maxbubble {
 7410:     my ($nav_error) = @_;
 7411:     if (defined($env{'form.scantron_maxbubble'}) &&
 7412: 	$env{'form.scantron_maxbubble'}) {
 7413: 	&restore_bubble_lines();
 7414: 	return $env{'form.scantron_maxbubble'};
 7415:     }
 7416: 
 7417:     my (undef, undef, $sequence) =
 7418: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7419: 
 7420:     my $navmap=Apache::lonnavmaps::navmap->new();
 7421:     unless (ref($navmap)) {
 7422:         if (ref($nav_error)) {
 7423:             $$nav_error = 1;
 7424:         }
 7425:         return;
 7426:     }
 7427:     my $map=$navmap->getResourceByUrl($sequence);
 7428:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7429: 
 7430:     &Apache::lonxml::clear_problem_counter();
 7431: 
 7432:     my $uname       = $env{'user.name'};
 7433:     my $udom        = $env{'user.domain'};
 7434:     my $cid         = $env{'request.course.id'};
 7435:     my $total_lines = 0;
 7436:     %bubble_lines_per_response = ();
 7437:     %first_bubble_line         = ();
 7438:     %subdivided_bubble_lines   = ();
 7439:     %responsetype_per_response = ();
 7440: 
 7441:     my $response_number = 0;
 7442:     my $bubble_line     = 0;
 7443:     foreach my $resource (@resources) {
 7444:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom);
 7445:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 7446: 	    foreach my $part_id (@{$parts}) {
 7447:                 my $lines;
 7448: 
 7449: 	        # TODO - make this a persistent hash not an array.
 7450: 
 7451:                 # optionresponse, matchresponse and rankresponse type items 
 7452:                 # render as separate sub-questions in exam mode.
 7453:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 7454:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 7455:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 7456:                     my ($numbub,$numshown);
 7457:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 7458:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 7459:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 7460:                         }
 7461:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 7462:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 7463:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 7464:                         }
 7465:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 7466:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 7467:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 7468:                         }
 7469:                     }
 7470:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 7471:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 7472:                     }
 7473:                     my $bubbles_per_line = 10;
 7474:                     my $inner_bubble_lines = int($numbub/$bubbles_per_line);
 7475:                     if (($numbub % $bubbles_per_line) != 0) {
 7476:                         $inner_bubble_lines++;
 7477:                     }
 7478:                     for (my $i=0; $i<$numshown; $i++) {
 7479:                         $subdivided_bubble_lines{$response_number} .= 
 7480:                             $inner_bubble_lines.',';
 7481:                     }
 7482:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 7483:                     $lines = $numshown * $inner_bubble_lines;
 7484:                 } else {
 7485:                     $lines = $analysis->{"$part_id.bubble_lines"};
 7486:                 } 
 7487: 
 7488:                 $first_bubble_line{$response_number} = $bubble_line;
 7489: 	        $bubble_lines_per_response{$response_number} = $lines;
 7490:                 $responsetype_per_response{$response_number} = 
 7491:                     $analysis->{$part_id.'.type'};
 7492: 	        $response_number++;
 7493: 
 7494: 	        $bubble_line +=  $lines;
 7495: 	        $total_lines +=  $lines;
 7496: 	    }
 7497:         }
 7498:     }
 7499:     &Apache::lonnet::delenv('scantron.');
 7500: 
 7501:     &save_bubble_lines();
 7502:     $env{'form.scantron_maxbubble'} =
 7503: 	$total_lines;
 7504:     return $env{'form.scantron_maxbubble'};
 7505: }
 7506: 
 7507: sub scantron_validate_missingbubbles {
 7508:     my ($r,$currentphase) = @_;
 7509:     #get student info
 7510:     my $classlist=&Apache::loncoursedata::get_classlist();
 7511:     my %idmap=&username_to_idmap($classlist);
 7512: 
 7513:     #get scantron line setup
 7514:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7515:     my ($scanlines,$scan_data)=&scantron_getfile();
 7516:     my $nav_error;
 7517:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
 7518:     if ($nav_error) {
 7519:         return(1,$currentphase);
 7520:     }
 7521:     if (!$max_bubble) { $max_bubble=2**31; }
 7522:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7523: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7524: 	if ($line=~/^[\s\cz]*$/) { next; }
 7525: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7526: 						 $scan_data);
 7527: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 7528: 	my @to_correct;
 7529: 	
 7530: 	# Probably here's where the error is...
 7531: 
 7532: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 7533:             my $lastbubble;
 7534:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 7535:                my $question = $1;
 7536:                my $subquestion = $2;
 7537:                if (!defined($first_bubble_line{$question -1})) { next; }
 7538:                my $first = $first_bubble_line{$question-1};
 7539:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7540:                my $subcount = 1;
 7541:                while ($subcount<$subquestion) {
 7542:                    $first += $subans[$subcount-1];
 7543:                    $subcount ++;
 7544:                }
 7545:                my $count = $subans[$subquestion-1];
 7546:                $lastbubble = $first + $count;
 7547:             } else {
 7548:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
 7549:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
 7550:             }
 7551:             if ($lastbubble > $max_bubble) { next; }
 7552: 	    push(@to_correct,$missing);
 7553: 	}
 7554: 	if (@to_correct) {
 7555: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7556: 				     $line,'missingbubble',\@to_correct);
 7557: 	    return (1,$currentphase);
 7558: 	}
 7559: 
 7560:     }
 7561:     return (0,$currentphase+1);
 7562: }
 7563: 
 7564: 
 7565: sub scantron_process_students {
 7566:     my ($r,$symb) = @_;
 7567: 
 7568:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7569:     if (!$symb) {
 7570: 	return '';
 7571:     }
 7572:     my $default_form_data=&defaultFormData($symb);
 7573: 
 7574:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7575:     my ($scanlines,$scan_data)=&scantron_getfile();
 7576:     my $classlist=&Apache::loncoursedata::get_classlist();
 7577:     my %idmap=&username_to_idmap($classlist);
 7578:     my $navmap=Apache::lonnavmaps::navmap->new();
 7579:     unless (ref($navmap)) {
 7580:         $r->print(&navmap_errormsg());
 7581:         return '';
 7582:     }  
 7583:     my $map=$navmap->getResourceByUrl($sequence);
 7584:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7585:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
 7586:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 7587:                             \%grader_randomlists_by_symb);
 7588:     my $resource_error;
 7589:     foreach my $resource (@resources) {
 7590:         my $ressymb;
 7591:         if (ref($resource)) {
 7592:             $ressymb = $resource->symb();
 7593:         } else {
 7594:             $resource_error = 1;
 7595:             last;
 7596:         }
 7597:         my ($analysis,$parts) =
 7598:             &scantron_partids_tograde($resource,$env{'request.course.id'},
 7599:                                       $env{'user.name'},$env{'user.domain'},1);
 7600:         $grader_partids_by_symb{$ressymb} = $parts;
 7601:         if (ref($analysis) eq 'HASH') {
 7602:             if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 7603:                 $grader_randomlists_by_symb{$ressymb} = 
 7604:                     $analysis->{'parts_withrandomlist'};
 7605:             }
 7606:         }
 7607:     }
 7608:     if ($resource_error) {
 7609:         $r->print(&navmap_errormsg());
 7610:         return '';
 7611:     }
 7612: 
 7613:     my ($uname,$udom);
 7614:     my $result= <<SCANTRONFORM;
 7615: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 7616:   <input type="hidden" name="command" value="scantron_configphase" />
 7617:   $default_form_data
 7618: SCANTRONFORM
 7619:     $r->print($result);
 7620: 
 7621:     my @delayqueue;
 7622:     my (%completedstudents,%scandata);
 7623:     
 7624:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 7625:     my $count=&get_todo_count($scanlines,$scan_data);
 7626:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet Status',
 7627:  				    'Bubblesheet Progress',$count,
 7628: 				    'inline',undef,'scantronupload');
 7629:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 7630: 					  'Processing first student');
 7631:     $r->print('<br />');
 7632:     my $start=&Time::HiRes::time();
 7633:     my $i=-1;
 7634:     my $started;
 7635: 
 7636:     my $nav_error;
 7637:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
 7638:     if ($nav_error) {
 7639:         $r->print(&navmap_errormsg());
 7640:         return '';
 7641:     }
 7642: 
 7643:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 7644:     # the user and return.
 7645: 
 7646:     if ($ssi_error) {
 7647: 	$r->print("</form>");
 7648: 	&ssi_print_error($r);
 7649: 	$r->print(&show_grading_menu_form($symb));
 7650:         &Apache::lonnet::remove_lock($lock);
 7651: 	return '';		# Dunno why the other returns return '' rather than just returning.
 7652:     }
 7653: 
 7654:     my %lettdig = &letter_to_digits();
 7655:     my $numletts = scalar(keys(%lettdig));
 7656: 
 7657:     while ($i<$scanlines->{'count'}) {
 7658:  	($uname,$udom)=('','');
 7659:  	$i++;
 7660:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7661:  	if ($line=~/^[\s\cz]*$/) { next; }
 7662: 	if ($started) {
 7663: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 7664: 						     'last student');
 7665: 	}
 7666: 	$started=1;
 7667:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7668:  						 $scan_data);
 7669:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 7670:  					      \%idmap,$i)) {
 7671:   	    &scantron_add_delay(\@delayqueue,$line,
 7672:  				'Unable to find a student that matches',1);
 7673:  	    next;
 7674:   	}
 7675:  	if (exists $completedstudents{$uname}) {
 7676:  	    &scantron_add_delay(\@delayqueue,$line,
 7677:  				'Student '.$uname.' has multiple sheets',2);
 7678:  	    next;
 7679:  	}
 7680:   	($uname,$udom)=split(/:/,$uname);
 7681: 
 7682:         my (%partids_by_symb,$res_error);
 7683:         foreach my $resource (@resources) {
 7684:             my $ressymb;
 7685:             if (ref($resource)) {
 7686:                 $ressymb = $resource->symb();
 7687:             } else {
 7688:                 $res_error = 1;
 7689:                 last;
 7690:             }
 7691:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 7692:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 7693:                 my ($analysis,$parts) =
 7694:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom);
 7695:                 $partids_by_symb{$ressymb} = $parts;
 7696:             } else {
 7697:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
 7698:             }
 7699:         }
 7700: 
 7701:         if ($res_error) {
 7702:             &scantron_add_delay(\@delayqueue,$line,
 7703:                                 'An error occurred while grading student '.$uname,2);
 7704:             next;
 7705:         }
 7706: 
 7707: 	&Apache::lonxml::clear_problem_counter();
 7708:   	&Apache::lonnet::appenv($scan_record);
 7709: 
 7710: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 7711: 	    &scantron_putfile($scanlines,$scan_data);
 7712: 	}
 7713: 	
 7714:         my $scancode;
 7715:         if ((exists($scan_record->{'scantron.CODE'})) &&
 7716:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 7717:             $scancode = $scan_record->{'scantron.CODE'};
 7718:         } else {
 7719:             $scancode = '';
 7720:         }
 7721: 
 7722:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 7723:                                    \@resources,\%partids_by_symb) eq 'ssi_error') {
 7724:             $ssi_error = 0; # So end of handler error message does not trigger.
 7725:             $r->print("</form>");
 7726:             &ssi_print_error($r);
 7727:             $r->print(&show_grading_menu_form($symb));
 7728:             &Apache::lonnet::remove_lock($lock);
 7729:             return '';      # Why return ''?  Beats me.
 7730:         }
 7731: 
 7732: 	$completedstudents{$uname}={'line'=>$line};
 7733:         if ($env{'form.verifyrecord'}) {
 7734:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 7735:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 7736:             chomp($studentdata);
 7737:             $studentdata =~ s/\r$//;
 7738:             my $studentrecord = '';
 7739:             my $counter = -1;
 7740:             foreach my $resource (@resources) {
 7741:                 my $ressymb = $resource->symb();
 7742:                 ($counter,my $recording) =
 7743:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 7744:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
 7745:                                              \%scantron_config,\%lettdig,$numletts);
 7746:                 $studentrecord .= $recording;
 7747:             }
 7748:             if ($studentrecord ne $studentdata) {
 7749:                 &Apache::lonxml::clear_problem_counter();
 7750:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 7751:                                            \@resources,\%partids_by_symb) eq 'ssi_error') {
 7752:                     $ssi_error = 0; # So end of handler error message does not trigger.
 7753:                     $r->print("</form>");
 7754:                     &ssi_print_error($r);
 7755:                     $r->print(&show_grading_menu_form($symb));
 7756:                     &Apache::lonnet::remove_lock($lock);
 7757:                     delete($completedstudents{$uname});
 7758:                     return '';
 7759:                 }
 7760:                 $counter = -1;
 7761:                 $studentrecord = '';
 7762:                 foreach my $resource (@resources) {
 7763:                     my $ressymb = $resource->symb();
 7764:                     ($counter,my $recording) =
 7765:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 7766:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 7767:                                                  \%scantron_config,\%lettdig,$numletts);
 7768:                     $studentrecord .= $recording;
 7769:                 }
 7770:                 if ($studentrecord ne $studentdata) {
 7771:                     $r->print('<p><span class="LC_error">');
 7772:                     if ($scancode eq '') {
 7773:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2].',
 7774:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 7775:                     } else {
 7776:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2] and CODE: [_3].',
 7777:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 7778:                     }
 7779:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 7780:                               &Apache::loncommon::start_data_table_header_row()."\n".
 7781:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 7782:                               &Apache::loncommon::end_data_table_header_row()."\n".
 7783:                               &Apache::loncommon::start_data_table_row().
 7784:                               '<td>'.&mt('Bubble Sheet').'</td>'.
 7785:                               '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
 7786:                               &Apache::loncommon::end_data_table_row().
 7787:                               &Apache::loncommon::start_data_table_row().
 7788:                               '<td>Stored submissions</td>'.
 7789:                               '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
 7790:                               &Apache::loncommon::end_data_table_row().
 7791:                               &Apache::loncommon::end_data_table().'</p>');
 7792:                 } else {
 7793:                     $r->print('<br /><span class="LC_warning">'.
 7794:                              &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 />'.
 7795:                              &mt("As a consequence, this user's submission history records two tries.").
 7796:                                  '</span><br />');
 7797:                 }
 7798:             }
 7799:         }
 7800:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 7801:     } continue {
 7802: 	&Apache::lonxml::clear_problem_counter();
 7803: 	&Apache::lonnet::delenv('scantron.');
 7804:     }
 7805:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 7806:     &Apache::lonnet::remove_lock($lock);
 7807: #    my $lasttime = &Time::HiRes::time()-$start;
 7808: #    $r->print("<p>took $lasttime</p>");
 7809: 
 7810:     $r->print("</form>");
 7811:     $r->print(&show_grading_menu_form($symb));
 7812:     return '';
 7813: }
 7814: 
 7815: sub graders_resources_pass {
 7816:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb) = @_;
 7817:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
 7818:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
 7819:         foreach my $resource (@{$resources}) {
 7820:             my $ressymb = $resource->symb();
 7821:             my ($analysis,$parts) =
 7822:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
 7823:                                           $env{'user.name'},$env{'user.domain'},1);
 7824:             $grader_partids_by_symb->{$ressymb} = $parts;
 7825:             if (ref($analysis) eq 'HASH') {
 7826:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 7827:                     $grader_randomlists_by_symb->{$ressymb} =
 7828:                         $analysis->{'parts_withrandomlist'};
 7829:                 }
 7830:             }
 7831:         }
 7832:     }
 7833:     return;
 7834: }
 7835: 
 7836: sub grade_student_bubbles {
 7837:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts) = @_;
 7838:     if (ref($resources) eq 'ARRAY') {
 7839:         my $count = 0;
 7840:         foreach my $resource (@{$resources}) {
 7841:             my $ressymb = $resource->symb();
 7842:             my %form = ('submitted'      => 'scantron',
 7843:                         'grade_target'   => 'grade',
 7844:                         'grade_username' => $uname,
 7845:                         'grade_domain'   => $udom,
 7846:                         'grade_courseid' => $env{'request.course.id'},
 7847:                         'grade_symb'     => $ressymb,
 7848:                         'CODE'           => $scancode
 7849:                        );
 7850:             if (ref($parts) eq 'HASH') {
 7851:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 7852:                     foreach my $part (@{$parts->{$ressymb}}) {
 7853:                         $form{'scantron_questnum_start.'.$part} =
 7854:                             1+$env{'form.scantron.first_bubble_line.'.$count};
 7855:                         $count++;
 7856:                     }
 7857:                 }
 7858:             }
 7859:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 7860:             return 'ssi_error' if ($ssi_error);
 7861:             last if (&Apache::loncommon::connection_aborted($r));
 7862:         }
 7863:     }
 7864:     return;
 7865: }
 7866: 
 7867: sub scantron_upload_scantron_data {
 7868:     my ($r,$symb)=@_;
 7869:     my $dom = $env{'request.role.domain'};
 7870:     my $domdesc = &Apache::lonnet::domain($dom,'description');
 7871:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
 7872:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 7873: 							  'domainid',
 7874: 							  'coursename',$dom);
 7875:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
 7876:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
 7877:     my $default_form_data=&defaultFormData($symb);
 7878:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
 7879:     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.");
 7880:     $r->print(&Apache::lonhtmlcommon::scripttag('
 7881:     function checkUpload(formname) {
 7882: 	if (formname.upfile.value == "") {
 7883: 	    alert("'.$nofile_alert.'");
 7884: 	    return false;
 7885: 	}
 7886:         if (formname.courseid.value == "") {
 7887:             alert("'.$nocourseid_alert.'");
 7888:             return false;
 7889:         }
 7890: 	formname.submit();
 7891:     }
 7892: 
 7893:     function ToSyllabus() {
 7894:         var cdom = '."'$dom'".';
 7895:         var cnum = document.rules.courseid.value;
 7896:         if (cdom == "" || cdom == null) {
 7897:             return;
 7898:         }
 7899:         if (cnum == "" || cnum == null) {
 7900:            return;
 7901:         }
 7902:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
 7903:                             "height=350,width=350,scrollbars=yes,menubar=no");
 7904:         return;
 7905:     }
 7906: 
 7907: '));
 7908:     $r->print('
 7909: <h3>'.&mt('Send scanned bubblesheet data to a course').'</h3>
 7910: 
 7911: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 7912: '.$default_form_data.
 7913:   &Apache::lonhtmlcommon::start_pick_box().
 7914:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
 7915:   '<input name="courseid" type="text" size="30" />'.$select_link.
 7916:   &Apache::lonhtmlcommon::row_closure().
 7917:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
 7918:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
 7919:   &Apache::lonhtmlcommon::row_closure().
 7920:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
 7921:   '<input name="domainid" type="hidden" />'.$domdesc.
 7922:   &Apache::lonhtmlcommon::row_closure().
 7923:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
 7924:   '<input type="file" name="upfile" size="50" />'.
 7925:   &Apache::lonhtmlcommon::row_closure(1).
 7926:   &Apache::lonhtmlcommon::end_pick_box().'<br />
 7927: 
 7928: <input name="command" value="scantronupload_save" type="hidden" />
 7929: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 7930: </form>
 7931: ');
 7932:     return '';
 7933: }
 7934: 
 7935: 
 7936: sub scantron_upload_scantron_data_save {
 7937:     my($r,$symb)=@_;
 7938:     my $doanotherupload=
 7939: 	'<br /><form action="/adm/grades" method="post">'."\n".
 7940: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 7941: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 7942: 	'</form>'."\n";
 7943:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 7944: 	!&Apache::lonnet::allowed('usc',
 7945: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 7946: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
 7947: 	if ($symb) {
 7948: 	    $r->print(&show_grading_menu_form($symb));
 7949: 	} else {
 7950: 	    $r->print($doanotherupload);
 7951: 	}
 7952: 	return '';
 7953:     }
 7954:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 7955:     my $uploadedfile;
 7956:     $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
 7957:     if (length($env{'form.upfile'}) < 2) {
 7958:         $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>'));
 7959:     } else {
 7960:         my $result = 
 7961:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
 7962:                                             $env{'form.courseid'},$env{'form.domainid'});
 7963: 	if ($result =~ m{^/uploaded/}) {
 7964: 	    $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
 7965:                           '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
 7966: 			  '<span class="LC_filename">'.$result.'</span>'));
 7967:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
 7968:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
 7969:                                                        $env{'form.courseid'},$uploadedfile));
 7970: 	} else {
 7971: 	    $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
 7972:                           '<span class="LC_error">','</span>',$result,
 7973: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 7974: 	}
 7975:     }
 7976:     if ($symb) {
 7977: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
 7978:     } else {
 7979: 	$r->print($doanotherupload);
 7980:     }
 7981:     return '';
 7982: }
 7983: 
 7984: sub validate_uploaded_scantron_file {
 7985:     my ($cdom,$cname,$fname) = @_;
 7986:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
 7987:     my @lines;
 7988:     if ($scanlines ne '-1') {
 7989:         @lines=split("\n",$scanlines,-1);
 7990:     }
 7991:     my $output;
 7992:     if (@lines) {
 7993:         my (%counts,$max_match_format);
 7994:         my ($max_match_count,$max_match_pct) = (0,0);
 7995:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
 7996:         my %idmap = &username_to_idmap($classlist);
 7997:         foreach my $key (keys(%idmap)) {
 7998:             my $lckey = lc($key);
 7999:             $idmap{$lckey} = $idmap{$key};
 8000:         }
 8001:         my %unique_formats;
 8002:         my @formatlines = &get_scantronformat_file();
 8003:         foreach my $line (@formatlines) {
 8004:             chomp($line);
 8005:             my @config = split(/:/,$line);
 8006:             my $idstart = $config[5];
 8007:             my $idlength = $config[6];
 8008:             if (($idstart ne '') && ($idlength > 0)) {
 8009:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
 8010:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
 8011:                 } else {
 8012:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
 8013:                 }
 8014:             }
 8015:         }
 8016:         foreach my $key (keys(%unique_formats)) {
 8017:             my ($idstart,$idlength) = split(':',$key);
 8018:             %{$counts{$key}} = (
 8019:                                'found'   => 0,
 8020:                                'total'   => 0,
 8021:                               );
 8022:             foreach my $line (@lines) {
 8023:                 next if ($line =~ /^#/);
 8024:                 next if ($line =~ /^[\s\cz]*$/);
 8025:                 my $id = substr($line,$idstart-1,$idlength);
 8026:                 $id = lc($id);
 8027:                 if (exists($idmap{$id})) {
 8028:                     $counts{$key}{'found'} ++;
 8029:                 }
 8030:                 $counts{$key}{'total'} ++;
 8031:             }
 8032:             if ($counts{$key}{'total'}) {
 8033:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
 8034:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
 8035:                     $max_match_pct = $percent_match;
 8036:                     $max_match_format = $key;
 8037:                     $max_match_count = $counts{$key}{'total'};
 8038:                 }
 8039:             }
 8040:         }
 8041:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
 8042:             my $format_descs;
 8043:             my $numwithformat = @{$unique_formats{$max_match_format}};
 8044:             for (my $i=0; $i<$numwithformat; $i++) {
 8045:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
 8046:                 if ($i<$numwithformat-2) {
 8047:                     $format_descs .= '"<i>'.$desc.'</i>", ';
 8048:                 } elsif ($i==$numwithformat-2) {
 8049:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
 8050:                 } elsif ($i==$numwithformat-1) {
 8051:                     $format_descs .= '"<i>'.$desc.'</i>"';
 8052:                 }
 8053:             }
 8054:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
 8055:             $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).
 8056:                        '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
 8057:                        '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
 8058:                        '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
 8059:                                   '<i>'.$cdom.'</i>').'</li>'.
 8060:                        '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
 8061:                        '<li>'.&mt('The course roster is not up to date').'</li>'.
 8062:                        '</ul>';
 8063:         }
 8064:     } else {
 8065:         $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
 8066:     }
 8067:     return $output;
 8068: }
 8069: 
 8070: sub valid_file {
 8071:     my ($requested_file)=@_;
 8072:     foreach my $filename (sort(&scantron_filenames())) {
 8073: 	if ($requested_file eq $filename) { return 1; }
 8074:     }
 8075:     return 0;
 8076: }
 8077: 
 8078: sub scantron_download_scantron_data {
 8079:     my ($r,$symb)=@_;
 8080:     my $default_form_data=&defaultFormData($symb);
 8081:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 8082:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8083:     my $file=$env{'form.scantron_selectfile'};
 8084:     if (! &valid_file($file)) {
 8085: 	$r->print('
 8086: 	<p>
 8087: 	    '.&mt('The requested file name was invalid.').'
 8088:         </p>
 8089: ');
 8090: 	$r->print(&show_grading_menu_form($symb));
 8091: 	return;
 8092:     }
 8093:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 8094:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 8095:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 8096:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 8097:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 8098:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 8099:     $r->print('
 8100:     <p>
 8101: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
 8102: 	      '<a href="'.$orig.'">','</a>').'
 8103:     </p>
 8104:     <p>
 8105: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 8106: 	      '<a href="'.$corrected.'">','</a>').'
 8107:     </p>
 8108:     <p>
 8109: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 8110: 	      '<a href="'.$skipped.'">','</a>').'
 8111:     </p>
 8112: ');
 8113:     $r->print(&show_grading_menu_form($symb));
 8114:     return '';
 8115: }
 8116: 
 8117: sub checkscantron_results {
 8118:     my ($r,$symb) = @_;
 8119:     if (!$symb) {return '';}
 8120:     my $grading_menu_button=&show_grading_menu_form($symb);
 8121:     my $cid = $env{'request.course.id'};
 8122:     my %lettdig = &letter_to_digits();
 8123:     my $numletts = scalar(keys(%lettdig));
 8124:     my $cnum = $env{'course.'.$cid.'.num'};
 8125:     my $cdom = $env{'course.'.$cid.'.domain'};
 8126:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8127:     my %record;
 8128:     my %scantron_config =
 8129:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
 8130:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
 8131:     my $classlist=&Apache::loncoursedata::get_classlist();
 8132:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 8133:     my $navmap=Apache::lonnavmaps::navmap->new();
 8134:     unless (ref($navmap)) {
 8135:         $r->print(&navmap_errormsg());
 8136:         return '';
 8137:     }
 8138:     my $map=$navmap->getResourceByUrl($sequence);
 8139:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8140:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
 8141:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,                             \%grader_randomlists_by_symb);
 8142: 
 8143:     my ($uname,$udom);
 8144:     my (%scandata,%lastname,%bylast);
 8145:     $r->print('
 8146: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 8147: 
 8148:     my @delayqueue;
 8149:     my %completedstudents;
 8150: 
 8151:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
 8152:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet/Submissions Comparison Status',
 8153:                                     'Progress of Bubblesheet Data/Submission Records Comparison',$count,
 8154:                                     'inline',undef,'checkscantron');
 8155:     my ($username,$domain,$started);
 8156:     my $nav_error;
 8157:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
 8158:     if ($nav_error) {
 8159:         $r->print(&navmap_errormsg());
 8160:         return '';
 8161:     }
 8162: 
 8163:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 8164:                                           'Processing first student');
 8165:     my $start=&Time::HiRes::time();
 8166:     my $i=-1;
 8167: 
 8168:     while ($i<$scanlines->{'count'}) {
 8169:         ($username,$domain,$uname)=('','','');
 8170:         $i++;
 8171:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 8172:         if ($line=~/^[\s\cz]*$/) { next; }
 8173:         if ($started) {
 8174:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 8175:                                                      'last student');
 8176:         }
 8177:         $started=1;
 8178:         my $scan_record=
 8179:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 8180:                                                      $scan_data);
 8181:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
 8182:                                                               \%idmap,$i)) {
 8183:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 8184:                                 'Unable to find a student that matches',1);
 8185:             next;
 8186:         }
 8187:         if (exists $completedstudents{$uname}) {
 8188:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 8189:                                 'Student '.$uname.' has multiple sheets',2);
 8190:             next;
 8191:         }
 8192:         my $pid = $scan_record->{'scantron.ID'};
 8193:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 8194:         push(@{$bylast{$lastname{$pid}}},$pid);
 8195:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 8196:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 8197:         chomp($scandata{$pid});
 8198:         $scandata{$pid} =~ s/\r$//;
 8199:         ($username,$domain)=split(/:/,$uname);
 8200:         my $counter = -1;
 8201:         foreach my $resource (@resources) {
 8202:             my $parts;
 8203:             my $ressymb = $resource->symb();
 8204:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 8205:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 8206:                 (my $analysis,$parts) =
 8207:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$username,$domain);
 8208:             } else {
 8209:                 $parts = $grader_partids_by_symb{$ressymb};
 8210:             }
 8211:             ($counter,my $recording) =
 8212:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
 8213:                                          $scandata{$pid},$parts,
 8214:                                          \%scantron_config,\%lettdig,$numletts);
 8215:             $record{$pid} .= $recording;
 8216:         }
 8217:     }
 8218:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 8219:     $r->print('<br />');
 8220:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 8221:     $passed = 0;
 8222:     $failed = 0;
 8223:     $numstudents = 0;
 8224:     foreach my $last (sort(keys(%bylast))) {
 8225:         if (ref($bylast{$last}) eq 'ARRAY') {
 8226:             foreach my $pid (sort(@{$bylast{$last}})) {
 8227:                 my $showscandata = $scandata{$pid};
 8228:                 my $showrecord = $record{$pid};
 8229:                 $showscandata =~ s/\s/&nbsp;/g;
 8230:                 $showrecord =~ s/\s/&nbsp;/g;
 8231:                 if ($scandata{$pid} eq $record{$pid}) {
 8232:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 8233:                     $okstudents .= '<tr class="'.$css_class.'">'.
 8234: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 8235: '</tr>'."\n".
 8236: '<tr class="'.$css_class.'">'."\n".
 8237: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
 8238:                     $passed ++;
 8239:                 } else {
 8240:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
 8241:                     $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".
 8242: '</tr>'."\n".
 8243: '<tr class="'.$css_class.'">'."\n".
 8244: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
 8245: '</tr>'."\n";
 8246:                     $failed ++;
 8247:                 }
 8248:                 $numstudents ++;
 8249:             }
 8250:         }
 8251:     }
 8252:     $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>');
 8253:     $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>');
 8254:     if ($passed) {
 8255:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
 8256:         $r->print(&Apache::loncommon::start_data_table()."\n".
 8257:                  &Apache::loncommon::start_data_table_header_row()."\n".
 8258:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 8259:                  &Apache::loncommon::end_data_table_header_row()."\n".
 8260:                  $okstudents."\n".
 8261:                  &Apache::loncommon::end_data_table().'<br />');
 8262:     }
 8263:     if ($failed) {
 8264:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
 8265:         $r->print(&Apache::loncommon::start_data_table()."\n".
 8266:                  &Apache::loncommon::start_data_table_header_row()."\n".
 8267:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 8268:                  &Apache::loncommon::end_data_table_header_row()."\n".
 8269:                  $badstudents."\n".
 8270:                  &Apache::loncommon::end_data_table()).'<br />'.
 8271:                  &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.');  
 8272:     }
 8273:     $r->print('</form><br />'.$grading_menu_button);
 8274:     return;
 8275: }
 8276: 
 8277: sub verify_scantron_grading {
 8278:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
 8279:         $scantron_config,$lettdig,$numletts) = @_;
 8280:     my ($record,%expected,%startpos);
 8281:     return ($counter,$record) if (!ref($resource));
 8282:     return ($counter,$record) if (!$resource->is_problem());
 8283:     my $symb = $resource->symb();
 8284:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
 8285:     foreach my $part_id (@{$partids}) {
 8286:         $counter ++;
 8287:         $expected{$part_id} = 0;
 8288:         if ($env{"form.scantron.sub_bubblelines.$counter"}) {
 8289:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
 8290:             foreach my $item (@sub_lines) {
 8291:                 $expected{$part_id} += $item;
 8292:             }
 8293:         } else {
 8294:             $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
 8295:         }
 8296:         $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
 8297:     }
 8298:     if ($symb) {
 8299:         my %recorded;
 8300:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
 8301:         if ($returnhash{'version'}) {
 8302:             my %lasthash=();
 8303:             my $version;
 8304:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 8305:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 8306:                     $lasthash{$key}=$returnhash{$version.':'.$key};
 8307:                 }
 8308:             }
 8309:             foreach my $key (keys(%lasthash)) {
 8310:                 if ($key =~ /\.scantron$/) {
 8311:                     my $value = &unescape($lasthash{$key});
 8312:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
 8313:                     if ($value eq '') {
 8314:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
 8315:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
 8316:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8317:                             }
 8318:                         }
 8319:                     } else {
 8320:                         my @tocheck;
 8321:                         my @items = split(//,$value);
 8322:                         if (($scantron_config->{'Qon'} eq 'letter') ||
 8323:                             ($scantron_config->{'Qon'} eq 'number')) {
 8324:                             if (@items < $expected{$part_id}) {
 8325:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
 8326:                                 my @singles = split(//,$fragment);
 8327:                                 foreach my $pos (@singles) {
 8328:                                     if ($pos eq ' ') {
 8329:                                         push(@tocheck,$pos);
 8330:                                     } else {
 8331:                                         my $next = shift(@items);
 8332:                                         push(@tocheck,$next);
 8333:                                     }
 8334:                                 }
 8335:                             } else {
 8336:                                 @tocheck = @items;
 8337:                             }
 8338:                             foreach my $letter (@tocheck) {
 8339:                                 if ($scantron_config->{'Qon'} eq 'letter') {
 8340:                                     if ($letter !~ /^[A-J]$/) {
 8341:                                         $letter = $scantron_config->{'Qoff'};
 8342:                                     }
 8343:                                     $recorded{$part_id} .= $letter;
 8344:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
 8345:                                     my $digit;
 8346:                                     if ($letter !~ /^[A-J]$/) {
 8347:                                         $digit = $scantron_config->{'Qoff'};
 8348:                                     } else {
 8349:                                         $digit = $lettdig->{$letter};
 8350:                                     }
 8351:                                     $recorded{$part_id} .= $digit;
 8352:                                 }
 8353:                             }
 8354:                         } else {
 8355:                             @tocheck = @items;
 8356:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
 8357:                                 my $curr_sub = shift(@tocheck);
 8358:                                 my $digit;
 8359:                                 if ($curr_sub =~ /^[A-J]$/) {
 8360:                                     $digit = $lettdig->{$curr_sub}-1;
 8361:                                 }
 8362:                                 if ($curr_sub eq 'J') {
 8363:                                     $digit += scalar($numletts);
 8364:                                 }
 8365:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 8366:                                     if ($j == $digit) {
 8367:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
 8368:                                     } else {
 8369:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8370:                                     }
 8371:                                 }
 8372:                             }
 8373:                         }
 8374:                     }
 8375:                 }
 8376:             }
 8377:         }
 8378:         foreach my $part_id (@{$partids}) {
 8379:             if ($recorded{$part_id} eq '') {
 8380:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
 8381:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 8382:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8383:                     }
 8384:                 }
 8385:             }
 8386:             $record .= $recorded{$part_id};
 8387:         }
 8388:     }
 8389:     return ($counter,$record);
 8390: }
 8391: 
 8392: sub letter_to_digits { 
 8393:     my %lettdig = (
 8394:                     A => 1,
 8395:                     B => 2,
 8396:                     C => 3,
 8397:                     D => 4,
 8398:                     E => 5,
 8399:                     F => 6,
 8400:                     G => 7,
 8401:                     H => 8,
 8402:                     I => 9,
 8403:                     J => 0,
 8404:                   );
 8405:     return %lettdig;
 8406: }
 8407: 
 8408: 
 8409: #-------- end of section for handling grading scantron forms -------
 8410: #
 8411: #-------------------------------------------------------------------
 8412: 
 8413: #-------------------------- Menu interface -------------------------
 8414: #
 8415: #--- Show a Grading Menu button - Calls the next routine ---
 8416: sub show_grading_menu_form {
 8417:     my ($symb)=@_;
 8418:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
 8419: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8420: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 8421: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
 8422: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
 8423: 	'</form>'."\n";
 8424:     return $result;
 8425: }
 8426: 
 8427: sub grading_menu {
 8428:     my ($request,$symb) = @_;
 8429:     if (!$symb) {return '';}
 8430: 
 8431:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 8432:                   'command'=>'individual',
 8433:                   'gradingMenu'=>1,
 8434:                   'showgrading'=>"yes");
 8435:     
 8436:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8437: 
 8438:     $fields{'command'}='ungraded';
 8439:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8440: 
 8441:     $fields{'command'}='table';
 8442:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8443: 
 8444:     $fields{'command'}='all_for_one';
 8445:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8446: 
 8447:     $fields{'command'} = 'csvform';
 8448:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8449:     
 8450:     $fields{'command'} = 'processclicker';
 8451:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8452:     
 8453:     $fields{'command'} = 'scantron_selectphase';
 8454:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8455: 
 8456:     $fields{'command'} = 'initialverifyreceipt';
 8457:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8458:     
 8459:     my @menu = ({	categorytitle=>'Hand Grading',
 8460:             items =>[
 8461:                         {	linktext => 'Select individual students to grade',
 8462:                     		url => $url1a,
 8463:                     		permission => 'F',
 8464:                     		icon => 'edit-find-replace.png',
 8465:                     		linktitle => 'Grade current resource for a selection of students.'
 8466:                         }, 
 8467:                         {       linktext => 'Grade ungraded submissions.',
 8468:                                 url => $url1b,
 8469:                                 permission => 'F',
 8470:                                 icon => 'edit-find-replace.png',
 8471:                                 linktitle => 'Grade all submissions that have not been graded yet.'
 8472:                         },
 8473: 
 8474:                         {       linktext => 'Grading table',
 8475:                                 url => $url1c,
 8476:                                 permission => 'F',
 8477:                                 icon => 'edit-find-replace.png',
 8478:                                 linktitle => 'Grade current resource for all students.'
 8479:                         },
 8480:                         {       linktext => 'Grade complete page/sequence/folder for one student',
 8481:                                 url => $url1d,
 8482:                                 permission => 'F',
 8483:                                 icon => 'edit-find-replace.png',
 8484:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
 8485:                         }]},
 8486:                          { categorytitle=>'Automated Grading',
 8487:                items =>[
 8488: 
 8489:                 	    {	linktext => 'Upload Scores',
 8490:                     		url => $url2,
 8491:                     		permission => 'F',
 8492:                     		icon => 'uploadscores.png',
 8493:                     		linktitle => 'Specify a file containing the class scores for current resource.'
 8494:                 	    },
 8495:                 	    {	linktext => 'Process Clicker',
 8496:                     		url => $url3,
 8497:                     		permission => 'F',
 8498:                     		icon => 'addClickerInfoFile.png',
 8499:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
 8500:                 	    },
 8501:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
 8502:                     		url => $url4,
 8503:                     		permission => 'F',
 8504:                     		icon => 'stat.png',
 8505:                     		linktitle => 'Grade scantron exams, upload/download scantron data files, and review previously graded scantron exams.'
 8506:                 	    },
 8507:                             {   linktext => 'Verify Receipt No.',
 8508:                                 url => $url5,
 8509:                                 permission => 'F',
 8510:                                 icon => 'edit-find-replace.png',
 8511:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
 8512:                             }
 8513: 
 8514:                     ]
 8515:             });
 8516: 
 8517:     # Create the menu
 8518:     my $Str;
 8519:     $Str .= '<form method="post" action="" name="gradingMenu">';
 8520:     $Str .= '<input type="hidden" name="command" value="" />'.
 8521:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8522: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 8523: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 8524: 
 8525:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
 8526:     return $Str;    
 8527: }
 8528: 
 8529: 
 8530: sub ungraded {
 8531:     my ($request)=@_;
 8532:     &submit_options($request);
 8533: }
 8534: 
 8535: sub submit_options_sequence {
 8536:     my ($request,$symb) = @_;
 8537:     if (!$symb) {return '';}
 8538:     &commonJSfunctions($request);
 8539:     my $result;
 8540: 
 8541:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8542:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8543:         '<input type="hidden" name="gradingMenu" value="1" />'."\n".
 8544:         '<input type="hidden" name="showgrading" value="yes" />'."\n";
 8545: 
 8546:     $result.='
 8547: <h2>
 8548:   '.&mt('Grade complete page/sequence/folder for one student').'
 8549: </h2>'.
 8550:             &selectfield(0).
 8551:             '<input type="hidden" name="command" value="pickStudentPage" />
 8552:             <div>
 8553:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 8554:             </div>
 8555:         </div>
 8556:   </form>';
 8557:     $result .= &show_grading_menu_form($symb);
 8558:     return $result;
 8559: }
 8560: 
 8561: sub submit_options_table {
 8562:     my ($request,$symb) = @_;
 8563:     if (!$symb) {return '';}
 8564:     &commonJSfunctions($request);
 8565:     my $result;
 8566: 
 8567:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8568:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8569:         '<input type="hidden" name="gradingMenu" value="1" />'."\n".
 8570:         '<input type="hidden" name="showgrading" value="yes" />'."\n";
 8571: 
 8572:     $result.='
 8573: <h2>
 8574:   '.&mt('Grading table').'
 8575: </h2>'.
 8576:             &selectfield(0).
 8577:             '<input type="hidden" name="command" value="viewgrades" />
 8578:             <div>
 8579:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 8580:             </div>
 8581:         </div>
 8582:   </form>';
 8583:     $result .= &show_grading_menu_form($symb);
 8584:     return $result;
 8585: }
 8586: 
 8587: 
 8588: 
 8589: #--- Displays the submissions first page -------
 8590: sub submit_options {
 8591:     my ($request,$symb) = @_;
 8592:     if (!$symb) {return '';}
 8593: 
 8594:     &commonJSfunctions($request);
 8595:     my $result;
 8596: 
 8597:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8598: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8599: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 8600: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 8601: 
 8602:     $result.='
 8603: <h2>
 8604:   '.&mt('Select individual students to grade').'
 8605: </h2>'.&selectfield(1).'
 8606:                 <input type="hidden" name="command" value="submission" /> 
 8607: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
 8608:             </div>
 8609:           </div>
 8610: 
 8611: 
 8612:   </form>';
 8613:     $result .= &show_grading_menu_form($symb);
 8614:     return $result;
 8615: }
 8616: 
 8617: sub selectfield {
 8618:    my ($full)=@_;
 8619:    my $result='<div class="LC_columnSection">
 8620:   
 8621:     <fieldset>
 8622:       <legend>
 8623:        '.&mt('Sections').'
 8624:       </legend>
 8625:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
 8626:     </fieldset>
 8627:   
 8628:     <fieldset>
 8629:       <legend>
 8630:         '.&mt('Groups').'
 8631:       </legend>
 8632:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
 8633:     </fieldset>
 8634:   
 8635:     <fieldset>
 8636:       <legend>
 8637:         '.&mt('Access Status').'
 8638:       </legend>
 8639:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
 8640:     </fieldset>';
 8641:     if ($full) {
 8642:        $result.='
 8643:     <fieldset>
 8644:       <legend>
 8645:         '.&mt('Submission Status').'
 8646:       </legend>'.
 8647:        &Apache::loncommon::select_form('all','submitonly',
 8648:           (&Apache::lonlocal::texthash(
 8649:              'yes'       => 'with submissions',
 8650:              'queued'    => 'in grading queue',
 8651:              'graded'    => 'with ungraded submissions',
 8652:              'incorrect' => 'with incorrect submissions',
 8653:              'all'       => 'with any status'),
 8654:              'select_form_order' => ['yes','queued','graded','incorrect','all'])).
 8655:    '</fieldset>';
 8656:     }
 8657:     $result.='</div><br />';
 8658:     return $result;
 8659: }
 8660: 
 8661: sub reset_perm {
 8662:     undef(%perm);
 8663: }
 8664: 
 8665: sub init_perm {
 8666:     &reset_perm();
 8667:     foreach my $test_perm ('vgr','mgr','opa') {
 8668: 
 8669: 	my $scope = $env{'request.course.id'};
 8670: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
 8671: 
 8672: 	    $scope .= '/'.$env{'request.course.sec'};
 8673: 	    if ( $perm{$test_perm}=
 8674: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
 8675: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
 8676: 	    } else {
 8677: 		delete($perm{$test_perm});
 8678: 	    }
 8679: 	}
 8680:     }
 8681: }
 8682: 
 8683: sub gather_clicker_ids {
 8684:     my %clicker_ids;
 8685: 
 8686:     my $classlist = &Apache::loncoursedata::get_classlist();
 8687: 
 8688:     # Set up a couple variables.
 8689:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
 8690:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
 8691:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
 8692: 
 8693:     foreach my $student (keys(%$classlist)) {
 8694:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
 8695:         my $username = $classlist->{$student}->[$username_idx];
 8696:         my $domain   = $classlist->{$student}->[$domain_idx];
 8697:         my $clickers =
 8698: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
 8699:         foreach my $id (split(/\,/,$clickers)) {
 8700:             $id=~s/^[\#0]+//;
 8701:             $id=~s/[\-\:]//g;
 8702:             if (exists($clicker_ids{$id})) {
 8703: 		$clicker_ids{$id}.=','.$username.':'.$domain;
 8704:             } else {
 8705: 		$clicker_ids{$id}=$username.':'.$domain;
 8706:             }
 8707:         }
 8708:     }
 8709:     return %clicker_ids;
 8710: }
 8711: 
 8712: sub gather_adv_clicker_ids {
 8713:     my %clicker_ids;
 8714:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 8715:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8716:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
 8717:     foreach my $element (sort(keys(%coursepersonnel))) {
 8718:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
 8719:             my ($puname,$pudom)=split(/\:/,$person);
 8720:             my $clickers =
 8721: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
 8722:             foreach my $id (split(/\,/,$clickers)) {
 8723: 		$id=~s/^[\#0]+//;
 8724:                 $id=~s/[\-\:]//g;
 8725: 		if (exists($clicker_ids{$id})) {
 8726: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
 8727: 		} else {
 8728: 		    $clicker_ids{$id}=$puname.':'.$pudom;
 8729: 		}
 8730:             }
 8731:         }
 8732:     }
 8733:     return %clicker_ids;
 8734: }
 8735: 
 8736: sub clicker_grading_parameters {
 8737:     return ('gradingmechanism' => 'scalar',
 8738:             'upfiletype' => 'scalar',
 8739:             'specificid' => 'scalar',
 8740:             'pcorrect' => 'scalar',
 8741:             'pincorrect' => 'scalar');
 8742: }
 8743: 
 8744: sub process_clicker {
 8745:     my ($r,$symb)=@_;
 8746:     if (!$symb) {return '';}
 8747:     my $result=&checkforfile_js();
 8748:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 8749:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 8750:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource.').
 8751:         '</b></td></tr>'."\n";
 8752:     $result.='<tr bgcolor="#ffffe6"><td>'."\n";
 8753: # Attempt to restore parameters from last session, set defaults if not present
 8754:     my %Saveable_Parameters=&clicker_grading_parameters();
 8755:     &Apache::loncommon::restore_course_settings('grades_clicker',
 8756:                                                  \%Saveable_Parameters);
 8757:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
 8758:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
 8759:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
 8760:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
 8761: 
 8762:     my %checked;
 8763:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
 8764:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
 8765:           $checked{$gradingmechanism}=' checked="checked"';
 8766:        }
 8767:     }
 8768: 
 8769:     my $upload=&mt("Upload File");
 8770:     my $type=&mt("Type");
 8771:     my $attendance=&mt("Award points just for participation");
 8772:     my $personnel=&mt("Correctness determined from response by course personnel");
 8773:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
 8774:     my $given=&mt("Correctness determined from given list of answers").' '.
 8775:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
 8776:     my $pcorrect=&mt("Percentage points for correct solution");
 8777:     my $pincorrect=&mt("Percentage points for incorrect solution");
 8778:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
 8779: 						   ('iclicker' => 'i>clicker',
 8780:                                                     'interwrite' => 'interwrite PRS'));
 8781:     $symb = &Apache::lonenc::check_encrypt($symb);
 8782:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
 8783: function sanitycheck() {
 8784: // Accept only integer percentages
 8785:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
 8786:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
 8787: // Find out grading choice
 8788:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8789:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
 8790:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
 8791:       }
 8792:    }
 8793: // By default, new choice equals user selection
 8794:    newgradingchoice=gradingchoice;
 8795: // Not good to give more points for false answers than correct ones
 8796:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
 8797:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
 8798:    }
 8799: // If new choice is attendance only, and old choice was correctness-based, restore defaults
 8800:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
 8801:       document.forms.gradesupload.pcorrect.value=100;
 8802:       document.forms.gradesupload.pincorrect.value=100;
 8803:    }
 8804: // If the values are different, cannot be attendance only
 8805:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
 8806:        (gradingchoice=='attendance')) {
 8807:        newgradingchoice='personnel';
 8808:    }
 8809: // Change grading choice to new one
 8810:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8811:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
 8812:          document.forms.gradesupload.gradingmechanism[i].checked=true;
 8813:       } else {
 8814:          document.forms.gradesupload.gradingmechanism[i].checked=false;
 8815:       }
 8816:    }
 8817: // Remember the old state
 8818:    document.forms.gradesupload.waschecked.value=newgradingchoice;
 8819: }
 8820: ENDUPFORM
 8821:     $result.= <<ENDUPFORM;
 8822: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 8823: <input type="hidden" name="symb" value="$symb" />
 8824: <input type="hidden" name="command" value="processclickerfile" />
 8825: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 8826: <input type="file" name="upfile" size="50" />
 8827: <br /><label>$type: $selectform</label>
 8828: <br /><label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
 8829: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
 8830: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
 8831: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
 8832: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
 8833: <br />&nbsp;&nbsp;&nbsp;
 8834: <input type="text" name="givenanswer" size="50" />
 8835: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
 8836: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
 8837: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
 8838: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 8839: </form>'
 8840: ENDUPFORM
 8841:     $result.='</td></tr></table>'."\n".
 8842:              '</td></tr></table><br /><br />'."\n";
 8843:     $result.=&show_grading_menu_form($symb);
 8844:     return $result;
 8845: }
 8846: 
 8847: sub process_clicker_file {
 8848:     my ($r,$symb)=@_;
 8849:     if (!$symb) {return '';}
 8850: 
 8851:     my %Saveable_Parameters=&clicker_grading_parameters();
 8852:     &Apache::loncommon::store_course_settings('grades_clicker',
 8853:                                               \%Saveable_Parameters);
 8854:     my $result='';
 8855:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
 8856: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
 8857: 	return $result.&show_grading_menu_form($symb);
 8858:     }
 8859:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
 8860:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
 8861:         return $result.&show_grading_menu_form($symb);
 8862:     }
 8863:     my $foundgiven=0;
 8864:     if ($env{'form.gradingmechanism'} eq 'given') {
 8865:         $env{'form.givenanswer'}=~s/^\s*//gs;
 8866:         $env{'form.givenanswer'}=~s/\s*$//gs;
 8867:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-]+/\,/g;
 8868:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
 8869:         my @answers=split(/\,/,$env{'form.givenanswer'});
 8870:         $foundgiven=$#answers+1;
 8871:     }
 8872:     my %clicker_ids=&gather_clicker_ids();
 8873:     my %correct_ids;
 8874:     if ($env{'form.gradingmechanism'} eq 'personnel') {
 8875: 	%correct_ids=&gather_adv_clicker_ids();
 8876:     }
 8877:     if ($env{'form.gradingmechanism'} eq 'specific') {
 8878: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
 8879: 	   $correct_id=~tr/a-z/A-Z/;
 8880: 	   $correct_id=~s/\s//gs;
 8881: 	   $correct_id=~s/^[\#0]+//;
 8882:            $correct_id=~s/[\-\:]//g;
 8883:            if ($correct_id) {
 8884: 	      $correct_ids{$correct_id}='specified';
 8885:            }
 8886:         }
 8887:     }
 8888:     if ($env{'form.gradingmechanism'} eq 'attendance') {
 8889: 	$result.=&mt('Score based on attendance only');
 8890:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
 8891:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
 8892:     } else {
 8893: 	my $number=0;
 8894: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
 8895: 	foreach my $id (sort(keys(%correct_ids))) {
 8896: 	    $result.='<br /><tt>'.$id.'</tt> - ';
 8897: 	    if ($correct_ids{$id} eq 'specified') {
 8898: 		$result.=&mt('specified');
 8899: 	    } else {
 8900: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
 8901: 		$result.=&Apache::loncommon::plainname($uname,$udom);
 8902: 	    }
 8903: 	    $number++;
 8904: 	}
 8905:         $result.="</p>\n";
 8906: 	if ($number==0) {
 8907: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
 8908: 	    return $result.&show_grading_menu_form($symb);
 8909: 	}
 8910:     }
 8911:     if (length($env{'form.upfile'}) < 2) {
 8912:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
 8913: 		     '<span class="LC_error">',
 8914: 		     '</span>',
 8915: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
 8916:         return $result.&show_grading_menu_form($symb);
 8917:     }
 8918: 
 8919: # Were able to get all the info needed, now analyze the file
 8920: 
 8921:     $result.=&Apache::loncommon::studentbrowser_javascript();
 8922:     $symb = &Apache::lonenc::check_encrypt($symb);
 8923:     my $heading=&mt('Scanning clicker file');
 8924:     $result.=(<<ENDHEADER);
 8925: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 8926: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 8927: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 8928: <form method="post" action="/adm/grades" name="clickeranalysis">
 8929: <input type="hidden" name="symb" value="$symb" />
 8930: <input type="hidden" name="command" value="assignclickergrades" />
 8931: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 8932: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
 8933: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
 8934: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
 8935: ENDHEADER
 8936:     if ($env{'form.gradingmechanism'} eq 'given') {
 8937:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
 8938:     } 
 8939:     my %responses;
 8940:     my @questiontitles;
 8941:     my $errormsg='';
 8942:     my $number=0;
 8943:     if ($env{'form.upfiletype'} eq 'iclicker') {
 8944: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
 8945:     }
 8946:     if ($env{'form.upfiletype'} eq 'interwrite') {
 8947:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
 8948:     }
 8949:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
 8950:              '<input type="hidden" name="number" value="'.$number.'" />'.
 8951:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
 8952:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
 8953:              '<br />';
 8954:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
 8955:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
 8956:        return $result.&show_grading_menu_form($symb);
 8957:     } 
 8958: # Remember Question Titles
 8959: # FIXME: Possibly need delimiter other than ":"
 8960:     for (my $i=0;$i<$number;$i++) {
 8961:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
 8962:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
 8963:     }
 8964:     my $correct_count=0;
 8965:     my $student_count=0;
 8966:     my $unknown_count=0;
 8967: # Match answers with usernames
 8968: # FIXME: Possibly need delimiter other than ":"
 8969:     foreach my $id (keys(%responses)) {
 8970:        if ($correct_ids{$id}) {
 8971:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
 8972:           $correct_count++;
 8973:        } elsif ($clicker_ids{$id}) {
 8974:           if ($clicker_ids{$id}=~/\,/) {
 8975: # More than one user with the same clicker!
 8976:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
 8977:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 8978:                            "<select name='multi".$id."'>";
 8979:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
 8980:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
 8981:              }
 8982:              $result.='</select>';
 8983:              $unknown_count++;
 8984:           } else {
 8985: # Good: found one and only one user with the right clicker
 8986:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
 8987:              $student_count++;
 8988:           }
 8989:        } else {
 8990:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
 8991:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 8992:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
 8993:                    "\n".&mt("Domain").": ".
 8994:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
 8995:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
 8996:           $unknown_count++;
 8997:        }
 8998:     }
 8999:     $result.='<hr />'.
 9000:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
 9001:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
 9002:        if ($correct_count==0) {
 9003:           $errormsg.="Found no correct answers answers for grading!";
 9004:        } elsif ($correct_count>1) {
 9005:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
 9006:        }
 9007:     }
 9008:     if ($number<1) {
 9009:        $errormsg.="Found no questions.";
 9010:     }
 9011:     if ($errormsg) {
 9012:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
 9013:     } else {
 9014:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
 9015:     }
 9016:     $result.='</form></td></tr></table>'."\n".
 9017:              '</td></tr></table><br /><br />'."\n";
 9018:     return $result.&show_grading_menu_form($symb);
 9019: }
 9020: 
 9021: sub iclicker_eval {
 9022:     my ($questiontitles,$responses)=@_;
 9023:     my $number=0;
 9024:     my $errormsg='';
 9025:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 9026:         my %components=&Apache::loncommon::record_sep($line);
 9027:         my @entries=map {$components{$_}} (sort(keys(%components)));
 9028: 	if ($entries[0] eq 'Question') {
 9029: 	    for (my $i=3;$i<$#entries;$i+=6) {
 9030: 		$$questiontitles[$number]=$entries[$i];
 9031: 		$number++;
 9032: 	    }
 9033: 	}
 9034: 	if ($entries[0]=~/^\#/) {
 9035: 	    my $id=$entries[0];
 9036: 	    my @idresponses;
 9037: 	    $id=~s/^[\#0]+//;
 9038: 	    for (my $i=0;$i<$number;$i++) {
 9039: 		my $idx=3+$i*6;
 9040: 		push(@idresponses,$entries[$idx]);
 9041: 	    }
 9042: 	    $$responses{$id}=join(',',@idresponses);
 9043: 	}
 9044:     }
 9045:     return ($errormsg,$number);
 9046: }
 9047: 
 9048: sub interwrite_eval {
 9049:     my ($questiontitles,$responses)=@_;
 9050:     my $number=0;
 9051:     my $errormsg='';
 9052:     my $skipline=1;
 9053:     my $questionnumber=0;
 9054:     my %idresponses=();
 9055:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 9056:         my %components=&Apache::loncommon::record_sep($line);
 9057:         my @entries=map {$components{$_}} (sort(keys(%components)));
 9058:         if ($entries[1] eq 'Time') { $skipline=0; next; }
 9059:         if ($entries[1] eq 'Response') { $skipline=1; }
 9060:         next if $skipline;
 9061:         if ($entries[0]!=$questionnumber) {
 9062:            $questionnumber=$entries[0];
 9063:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
 9064:            $number++;
 9065:         }
 9066:         my $id=$entries[4];
 9067:         $id=~s/^[\#0]+//;
 9068:         $id=~s/^v\d*\://i;
 9069:         $id=~s/[\-\:]//g;
 9070:         $idresponses{$id}[$number]=$entries[6];
 9071:     }
 9072:     foreach my $id (keys(%idresponses)) {
 9073:        $$responses{$id}=join(',',@{$idresponses{$id}});
 9074:        $$responses{$id}=~s/^\s*\,//;
 9075:     }
 9076:     return ($errormsg,$number);
 9077: }
 9078: 
 9079: sub assign_clicker_grades {
 9080:     my ($r,$symb)=@_;
 9081:     if (!$symb) {return '';}
 9082: # See which part we are saving to
 9083:     my $res_error;
 9084:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 9085:     if ($res_error) {
 9086:         return &navmap_errormsg();
 9087:     }
 9088: # FIXME: This should probably look for the first handgradeable part
 9089:     my $part=$$partlist[0];
 9090: # Start screen output
 9091:     my $result='';
 9092: 
 9093:     my $heading=&mt('Assigning grades based on clicker file');
 9094:     $result.=(<<ENDHEADER);
 9095: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 9096: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 9097: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 9098: ENDHEADER
 9099: # Get correct result
 9100: # FIXME: Possibly need delimiter other than ":"
 9101:     my @correct=();
 9102:     my $gradingmechanism=$env{'form.gradingmechanism'};
 9103:     my $number=$env{'form.number'};
 9104:     if ($gradingmechanism ne 'attendance') {
 9105:        foreach my $key (keys(%env)) {
 9106:           if ($key=~/^form\.correct\:/) {
 9107:              my @input=split(/\,/,$env{$key});
 9108:              for (my $i=0;$i<=$#input;$i++) {
 9109:                  if (($correct[$i]) && ($input[$i]) &&
 9110:                      ($correct[$i] ne $input[$i])) {
 9111:                     $result.='<br /><span class="LC_warning">'.
 9112:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
 9113:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
 9114:                  } elsif ($input[$i]) {
 9115:                     $correct[$i]=$input[$i];
 9116:                  }
 9117:              }
 9118:           }
 9119:        }
 9120:        for (my $i=0;$i<$number;$i++) {
 9121:           if (!$correct[$i]) {
 9122:              $result.='<br /><span class="LC_error">'.
 9123:                       &mt('No correct result given for question "[_1]"!',
 9124:                           $env{'form.question:'.$i}).'</span>';
 9125:           }
 9126:        }
 9127:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
 9128:     }
 9129: # Start grading
 9130:     my $pcorrect=$env{'form.pcorrect'};
 9131:     my $pincorrect=$env{'form.pincorrect'};
 9132:     my $storecount=0;
 9133:     foreach my $key (keys(%env)) {
 9134:        my $user='';
 9135:        if ($key=~/^form\.student\:(.*)$/) {
 9136:           $user=$1;
 9137:        }
 9138:        if ($key=~/^form\.unknown\:(.*)$/) {
 9139:           my $id=$1;
 9140:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
 9141:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
 9142:           } elsif ($env{'form.multi'.$id}) {
 9143:              $user=$env{'form.multi'.$id};
 9144:           }
 9145:        }
 9146:        if ($user) { 
 9147:           my @answer=split(/\,/,$env{$key});
 9148:           my $sum=0;
 9149:           my $realnumber=$number;
 9150:           for (my $i=0;$i<$number;$i++) {
 9151:              if  ($correct[$i] eq '-') {
 9152:                 $realnumber--;
 9153:              } elsif ($answer[$i]) {
 9154:                 if ($gradingmechanism eq 'attendance') {
 9155:                    $sum+=$pcorrect;
 9156:                 } elsif ($correct[$i] eq '*') {
 9157:                    $sum+=$pcorrect;
 9158:                 } else {
 9159:                    if ($answer[$i] eq $correct[$i]) {
 9160:                       $sum+=$pcorrect;
 9161:                    } else {
 9162:                       $sum+=$pincorrect;
 9163:                    }
 9164:                 }
 9165:              }
 9166:           }
 9167:           my $ave=$sum/(100*$realnumber);
 9168: # Store
 9169:           my ($username,$domain)=split(/\:/,$user);
 9170:           my %grades=();
 9171:           $grades{"resource.$part.solved"}='correct_by_override';
 9172:           $grades{"resource.$part.awarded"}=$ave;
 9173:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 9174:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
 9175:                                                  $env{'request.course.id'},
 9176:                                                  $domain,$username);
 9177:           if ($returncode ne 'ok') {
 9178:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
 9179:           } else {
 9180:              $storecount++;
 9181:           }
 9182:        }
 9183:     }
 9184: # We are done
 9185:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
 9186:              '</td></tr></table>'."\n".
 9187:              '</td></tr></table><br /><br />'."\n";
 9188:     return $result.&show_grading_menu_form($symb);
 9189: }
 9190: 
 9191: sub navmap_errormsg {
 9192:     return '<div class="LC_error">'.
 9193:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
 9194:            &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>').
 9195:            '</div>';
 9196: }
 9197: 
 9198: sub startpage {
 9199:     my ($r,$symb,$crumbs,$onlyfolderflag) = @_;
 9200:     unshift(@$crumbs,{href=>"/adm/grades?command=gradingmenu&symb=".&HTML::Entities::encode($symb,'<>&"'),text=>"Grading"});
 9201:     $r->print(&Apache::loncommon::start_page('Grading',undef,
 9202:                                           {'bread_crumbs' => $crumbs}));
 9203:     $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag));
 9204: }
 9205: 
 9206: sub handler {
 9207:     my $request=$_[0];
 9208:     &reset_caches();
 9209:     if ($env{'browser.mathml'}) {
 9210: 	&Apache::loncommon::content_type($request,'text/xml');
 9211:     } else {
 9212: 	&Apache::loncommon::content_type($request,'text/html');
 9213:     }
 9214:     $request->send_http_header;
 9215:     return '' if $request->header_only;
 9216:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
 9217: 
 9218: # see what command we need to execute
 9219: 
 9220:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
 9221:     my $command=$commands[0];
 9222: 
 9223:     if ($#commands > 0) {
 9224: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
 9225:     }
 9226: 
 9227: # see what the symb is
 9228: 
 9229:     my $symb=$env{'form.symb'};
 9230:     unless ($symb) {
 9231:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
 9232:        $symb=&Apache::lonnet::symbread($url);
 9233:     }
 9234:     &Apache::lonenc::check_decrypt(\$symb);                             
 9235: 
 9236:     $ssi_error = 0;
 9237:     if ($symb eq '' && $command eq '') {
 9238: #
 9239: # Not called from a resource
 9240: #    
 9241: 
 9242:     } else {
 9243: 	&init_perm();
 9244: 	if ($command eq 'submission' && $perm{'vgr'}) {
 9245:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}]);
 9246: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
 9247: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
 9248:             &startpage($request,$symb);
 9249: 	    &pickStudentPage($request,$symb);
 9250: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
 9251:             &startpage($request,$symb);
 9252: 	    &displayPage($request,$symb);
 9253: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
 9254:             &startpage($request,$symb);
 9255: 	    &updateGradeByPage($request,$symb);
 9256: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
 9257:             &startpage($request,$symb);
 9258: 	    &processGroup($request,$symb);
 9259: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
 9260:             &startpage($request,$symb);
 9261: 	    $request->print(&grading_menu($request,$symb));
 9262: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
 9263:             &startpage($request,$symb);
 9264: 	    $request->print(&submit_options($request,$symb));
 9265:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
 9266:             &startpage($request,$symb);
 9267:             $request->print(&submit_options($request,$symb));
 9268:         } elsif ($command eq 'table' && $perm{'vgr'}) {
 9269:             &startpage($request,$symb);
 9270:             $request->print(&submit_options_table($request,$symb));
 9271:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
 9272:             &startpage($request,$symb);
 9273:             $request->print(&submit_options_sequence($request,$symb));
 9274: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
 9275:             &startpage($request,$symb);
 9276: 	    $request->print(&viewgrades($request,$symb));
 9277: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
 9278:             &startpage($request,$symb);
 9279: 	    $request->print(&processHandGrade($request,$symb));
 9280: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
 9281:             &startpage($request,$symb);
 9282: 	    $request->print(&editgrades($request,$symb));
 9283:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
 9284:             &startpage($request,$symb);
 9285:             $request->print(&initialverifyreceipt($request,$symb));
 9286: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
 9287:             &startpage($request,$symb);
 9288: 	    $request->print(&verifyreceipt($request,$symb));
 9289:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
 9290:             &startpage($request,$symb);
 9291:             $request->print(&process_clicker($request,$symb));
 9292:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
 9293:             &startpage($request,$symb);
 9294:             $request->print(&process_clicker_file($request,$symb));
 9295:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
 9296:             &startpage($request,$symb);
 9297:             $request->print(&assign_clicker_grades($request,$symb));
 9298: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
 9299:             &startpage($request,$symb);
 9300: 	    $request->print(&upcsvScores_form($request,$symb));
 9301: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
 9302:             &startpage($request,$symb);
 9303: 	    $request->print(&csvupload($request,$symb));
 9304: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
 9305:             &startpage($request,$symb);
 9306: 	    $request->print(&csvuploadmap($request,$symb));
 9307: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
 9308: 	    if ($env{'form.associate'} ne 'Reverse Association') {
 9309:                 &startpage($request,$symb);
 9310: 		$request->print(&csvuploadoptions($request,$symb));
 9311: 	    } else {
 9312: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
 9313: 		    $env{'form.upfile_associate'} = 'reverse';
 9314: 		} else {
 9315: 		    $env{'form.upfile_associate'} = 'forward';
 9316: 		}
 9317:                 &startpage($request,$symb);
 9318: 		$request->print(&csvuploadmap($request,$symb));
 9319: 	    }
 9320: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
 9321:             &startpage($request,$symb);
 9322: 	    $request->print(&csvuploadassign($request,$symb));
 9323: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
 9324:             &startpage($request,$symb);
 9325: 	    $request->print(&scantron_selectphase($request,undef,$symb));
 9326:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
 9327:             &startpage($request,$symb);
 9328:  	    $request->print(&scantron_do_warning($request,$symb));
 9329: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
 9330:             &startpage($request,$symb);
 9331: 	    $request->print(&scantron_validate_file($request,$symb));
 9332: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
 9333:             &startpage($request,$symb);
 9334: 	    $request->print(&scantron_process_students($request,$symb));
 9335:  	} elsif ($command eq 'scantronupload' && 
 9336:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9337: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9338:             &startpage($request,$symb);
 9339:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
 9340:  	} elsif ($command eq 'scantronupload_save' &&
 9341:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9342: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9343:             &startpage($request,$symb);
 9344:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
 9345:  	} elsif ($command eq 'scantron_download' &&
 9346: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 9347:             &startpage($request,$symb);
 9348:  	    $request->print(&scantron_download_scantron_data($request,$symb));
 9349:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
 9350:             &startpage($request,$symb);
 9351:             $request->print(&checkscantron_results($request,$symb));     
 9352: 	} elsif ($command) {
 9353:             &startpage($request,$symb);
 9354: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
 9355: 	}
 9356:     }
 9357:     if ($ssi_error) {
 9358: 	&ssi_print_error($request);
 9359:     }
 9360:     $request->print(&Apache::loncommon::end_page());
 9361:     &reset_caches();
 9362:     return '';
 9363: }
 9364: 
 9365: 1;
 9366: 
 9367: __END__;
 9368: 
 9369: 
 9370: =head1 NAME
 9371: 
 9372: Apache::grades
 9373: 
 9374: =head1 SYNOPSIS
 9375: 
 9376: Handles the viewing of grades.
 9377: 
 9378: This is part of the LearningOnline Network with CAPA project
 9379: described at http://www.lon-capa.org.
 9380: 
 9381: =head1 OVERVIEW
 9382: 
 9383: Do an ssi with retries:
 9384: While I'd love to factor out this with the vesrion in lonprintout,
 9385: 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
 9386: I'm not quite ready to invent (e.g. an ssi_with_retry object).
 9387: 
 9388: At least the logic that drives this has been pulled out into loncommon.
 9389: 
 9390: 
 9391: 
 9392: ssi_with_retries - Does the server side include of a resource.
 9393:                      if the ssi call returns an error we'll retry it up to
 9394:                      the number of times requested by the caller.
 9395:                      If we still have a proble, no text is appended to the
 9396:                      output and we set some global variables.
 9397:                      to indicate to the caller an SSI error occurred.  
 9398:                      All of this is supposed to deal with the issues described
 9399:                      in LonCAPA BZ 5631 see:
 9400:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
 9401:                      by informing the user that this happened.
 9402: 
 9403: Parameters:
 9404:   resource   - The resource to include.  This is passed directly, without
 9405:                interpretation to lonnet::ssi.
 9406:   form       - The form hash parameters that guide the interpretation of the resource
 9407:                
 9408:   retries    - Number of retries allowed before giving up completely.
 9409: Returns:
 9410:   On success, returns the rendered resource identified by the resource parameter.
 9411: Side Effects:
 9412:   The following global variables can be set:
 9413:    ssi_error                - If an unrecoverable error occurred this becomes true.
 9414:                               It is up to the caller to initialize this to false
 9415:                               if desired.
 9416:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
 9417:                               of the resource that could not be rendered by the ssi
 9418:                               call.
 9419:    ssi_error_message   - The error string fetched from the ssi response
 9420:                               in the event of an error.
 9421: 
 9422: 
 9423: =head1 HANDLER SUBROUTINE
 9424: 
 9425: ssi_with_retries()
 9426: 
 9427: =head1 SUBROUTINES
 9428: 
 9429: =over
 9430: 
 9431: =item scantron_get_correction() : 
 9432: 
 9433:    Builds the interface screen to interact with the operator to fix a
 9434:    specific error condition in a specific scanline
 9435: 
 9436:  Arguments:
 9437:     $r           - Apache request object
 9438:     $i           - number of the current scanline
 9439:     $scan_record - hash ref as returned from &scantron_parse_scanline()
 9440:     $scan_config - hash ref as returned from &get_scantron_config()
 9441:     $line        - full contents of the current scanline
 9442:     $error       - error condition, valid values are
 9443:                    'incorrectCODE', 'duplicateCODE',
 9444:                    'doublebubble', 'missingbubble',
 9445:                    'duplicateID', 'incorrectID'
 9446:     $arg         - extra information needed
 9447:        For errors:
 9448:          - duplicateID   - paper number that this studentID was seen before on
 9449:          - duplicateCODE - array ref of the paper numbers this CODE was
 9450:                            seen on before
 9451:          - incorrectCODE - current incorrect CODE 
 9452:          - doublebubble  - array ref of the bubble lines that have double
 9453:                            bubble errors
 9454:          - missingbubble - array ref of the bubble lines that have missing
 9455:                            bubble errors
 9456: 
 9457: =item  scantron_get_maxbubble() : 
 9458: 
 9459:    Arguments:
 9460:        $nav_error  - Reference to scalar which is a flag to indicate a
 9461:                       failure to retrieve a navmap object.
 9462:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
 9463:        calling routine should trap the error condition and display the warning
 9464:        found in &navmap_errormsg().
 9465: 
 9466:    Returns the maximum number of bubble lines that are expected to
 9467:    occur. Does this by walking the selected sequence rendering the
 9468:    resource and then checking &Apache::lonxml::get_problem_counter()
 9469:    for what the current value of the problem counter is.
 9470: 
 9471:    Caches the results to $env{'form.scantron_maxbubble'},
 9472:    $env{'form.scantron.bubble_lines.n'}, 
 9473:    $env{'form.scantron.first_bubble_line.n'} and
 9474:    $env{"form.scantron.sub_bubblelines.n"}
 9475:    which are the total number of bubble, lines, the number of bubble
 9476:    lines for response n and number of the first bubble line for response n,
 9477:    and a comma separated list of numbers of bubble lines for sub-questions
 9478:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
 9479: 
 9480: 
 9481: =item  scantron_validate_missingbubbles() : 
 9482: 
 9483:    Validates all scanlines in the selected file to not have any
 9484:     answers that don't have bubbles that have not been verified
 9485:     to be bubble free.
 9486: 
 9487: =item  scantron_process_students() : 
 9488: 
 9489:    Routine that does the actual grading of the bubble sheet information.
 9490: 
 9491:    The parsed scanline hash is added to %env 
 9492: 
 9493:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
 9494:    foreach resource , with the form data of
 9495: 
 9496: 	'submitted'     =>'scantron' 
 9497: 	'grade_target'  =>'grade',
 9498: 	'grade_username'=> username of student
 9499: 	'grade_domain'  => domain of student
 9500: 	'grade_courseid'=> of course
 9501: 	'grade_symb'    => symb of resource to grade
 9502: 
 9503:     This triggers a grading pass. The problem grading code takes care
 9504:     of converting the bubbled letter information (now in %env) into a
 9505:     valid submission.
 9506: 
 9507: =item  scantron_upload_scantron_data() :
 9508: 
 9509:     Creates the screen for adding a new bubble sheet data file to a course.
 9510: 
 9511: =item  scantron_upload_scantron_data_save() : 
 9512: 
 9513:    Adds a provided bubble information data file to the course if user
 9514:    has the correct privileges to do so. 
 9515: 
 9516: =item  valid_file() :
 9517: 
 9518:    Validates that the requested bubble data file exists in the course.
 9519: 
 9520: =item  scantron_download_scantron_data() : 
 9521: 
 9522:    Shows a list of the three internal files (original, corrected,
 9523:    skipped) for a specific bubble sheet data file that exists in the
 9524:    course.
 9525: 
 9526: =item  scantron_validate_ID() : 
 9527: 
 9528:    Validates all scanlines in the selected file to not have any
 9529:    invalid or underspecified student/employee IDs
 9530: 
 9531: =item navmap_errormsg() :
 9532: 
 9533:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
 9534:    Should be called whenever the request to instantiate a navmap object fails.  
 9535: 
 9536: =back
 9537: 
 9538: =cut

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