File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.622: download - view: text, annotated - select for diffs
Sat Apr 17 22:48:52 2010 UTC (14 years ago) by www
Branches: MAIN
CVS tags: HEAD
Allow user to select probem when called context-free

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.622 2010/04/17 22:48:52 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 Apache::lonstathelpers;
   47: use String::Similarity;
   48: use LONCAPA;
   49: 
   50: use POSIX qw(floor);
   51: 
   52: 
   53: 
   54: my %perm=();
   55: 
   56: #  These variables are used to recover from ssi errors
   57: 
   58: my $ssi_retries = 5;
   59: my $ssi_error;
   60: my $ssi_error_resource;
   61: my $ssi_error_message;
   62: 
   63: 
   64: sub ssi_with_retries {
   65:     my ($resource, $retries, %form) = @_;
   66:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
   67:     if ($response->is_error) {
   68: 	$ssi_error          = 1;
   69: 	$ssi_error_resource = $resource;
   70: 	$ssi_error_message  = $response->code . " " . $response->message;
   71:     }
   72: 
   73:     return $content;
   74: 
   75: }
   76: #
   77: #  Prodcuces an ssi retry failure error message to the user:
   78: #
   79: 
   80: sub ssi_print_error {
   81:     my ($r) = @_;
   82:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
   83:     $r->print('
   84: <br />
   85: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
   86: <p>
   87: '.&mt('Unable to retrieve a resource from a server:').'<br />
   88: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
   89: '.&mt('Error:').' '.$ssi_error_message.'
   90: </p>
   91: <p>'.
   92: &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 />'.
   93: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
   94: '</p>');
   95:     return;
   96: }
   97: 
   98: #
   99: # --- Retrieve the parts from the metadata file.---
  100: # Returns an array of everything that the resources stores away
  101: #
  102: 
  103: sub getpartlist {
  104:     my ($symb,$errorref) = @_;
  105: 
  106:     my $navmap   = Apache::lonnavmaps::navmap->new();
  107:     unless (ref($navmap)) {
  108:         if (ref($errorref)) { 
  109:             $$errorref = 'navmap';
  110:             return;
  111:         }
  112:     }
  113:     my $res      = $navmap->getBySymb($symb);
  114:     my $partlist = $res->parts();
  115:     my $url      = $res->src();
  116:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
  117: 
  118:     my @stores;
  119:     foreach my $part (@{ $partlist }) {
  120: 	foreach my $key (@metakeys) {
  121: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
  122: 	}
  123:     }
  124:     return @stores;
  125: }
  126: 
  127: #--- Format fullname, username:domain if different for display
  128: #--- Use anywhere where the student names are listed
  129: sub nameUserString {
  130:     my ($type,$fullname,$uname,$udom) = @_;
  131:     if ($type eq 'header') {
  132: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
  133:     } else {
  134: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
  135: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
  136:     }
  137: }
  138: 
  139: #--- Get the partlist and the response type for a given problem. ---
  140: #--- Indicate if a response type is coded handgraded or not. ---
  141: sub response_type {
  142:     my ($symb,$response_error) = @_;
  143: 
  144:     my $navmap = Apache::lonnavmaps::navmap->new();
  145:     unless (ref($navmap)) {
  146:         if (ref($response_error)) {
  147:             $$response_error = 1;
  148:         }
  149:         return;
  150:     }
  151:     my $res = $navmap->getBySymb($symb);
  152:     unless (ref($res)) {
  153:         $$response_error = 1;
  154:         return;
  155:     }
  156:     my $partlist = $res->parts();
  157:     my %vPart = 
  158: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
  159:     my (%response_types,%handgrade);
  160:     foreach my $part (@{ $partlist }) {
  161: 	next if (%vPart && !exists($vPart{$part}));
  162: 
  163: 	my @types = $res->responseType($part);
  164: 	my @ids = $res->responseIds($part);
  165: 	for (my $i=0; $i < scalar(@ids); $i++) {
  166: 	    $response_types{$part}{$ids[$i]} = $types[$i];
  167: 	    $handgrade{$part.'_'.$ids[$i]} = 
  168: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
  169: 				     '.handgrade',$symb);
  170: 	}
  171:     }
  172:     return ($partlist,\%handgrade,\%response_types);
  173: }
  174: 
  175: sub flatten_responseType {
  176:     my ($responseType) = @_;
  177:     my @part_response_id =
  178: 	map { 
  179: 	    my $part = $_;
  180: 	    map {
  181: 		[$part,$_]
  182: 		} sort(keys(%{ $responseType->{$part} }));
  183: 	} sort(keys(%$responseType));
  184:     return @part_response_id;
  185: }
  186: 
  187: sub get_display_part {
  188:     my ($partID,$symb)=@_;
  189:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
  190:     if (defined($display) and $display ne '') {
  191:         $display.= ' (<span class="LC_internal_info">'
  192:                   .&mt('Part ID: [_1]',$partID).'</span>)';
  193:     } else {
  194: 	$display=$partID;
  195:     }
  196:     return $display;
  197: }
  198: 
  199: sub reset_caches {
  200:     &reset_analyze_cache();
  201:     &reset_perm();
  202: }
  203: 
  204: {
  205:     my %analyze_cache;
  206:     my %analyze_cache_formkeys;
  207: 
  208:     sub reset_analyze_cache {
  209: 	undef(%analyze_cache);
  210:         undef(%analyze_cache_formkeys);
  211:     }
  212: 
  213:     sub get_analyze {
  214: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash)=@_;
  215: 	my $key = "$symb\0$uname\0$udom";
  216: 	if (exists($analyze_cache{$key})) {
  217:             my $getupdate = 0;
  218:             if (ref($add_to_hash) eq 'HASH') {
  219:                 foreach my $item (keys(%{$add_to_hash})) {
  220:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
  221:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
  222:                             $getupdate = 1;
  223:                             last;
  224:                         }
  225:                     } else {
  226:                         $getupdate = 1;
  227:                     }
  228:                 }
  229:             }
  230:             if (!$getupdate) {
  231:                 return $analyze_cache{$key};
  232:             }
  233:         }
  234: 
  235: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
  236: 	$url=&Apache::lonnet::clutter($url);
  237:         my %form = ('grade_target'      => 'analyze',
  238:                     'grade_domain'      => $udom,
  239:                     'grade_symb'        => $symb,
  240:                     'grade_courseid'    =>  $env{'request.course.id'},
  241:                     'grade_username'    => $uname,
  242:                     'grade_noincrement' => $no_increment);
  243:         if (ref($add_to_hash)) {
  244:             %form = (%form,%{$add_to_hash});
  245:         } 
  246: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
  247: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
  248: 	my %analyze=&Apache::lonnet::str2hash($subresult);
  249:         if (ref($add_to_hash) eq 'HASH') {
  250:             $analyze_cache_formkeys{$key} = $add_to_hash;
  251:         } else {
  252:             $analyze_cache_formkeys{$key} = {};
  253:         }
  254: 	return $analyze_cache{$key} = \%analyze;
  255:     }
  256: 
  257:     sub get_order {
  258: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment)=@_;
  259: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment);
  260: 	return $analyze->{"$partid.$respid.shown"};
  261:     }
  262: 
  263:     sub get_radiobutton_correct_foil {
  264: 	my ($partid,$respid,$symb,$uname,$udom)=@_;
  265: 	my $analyze = &get_analyze($symb,$uname,$udom);
  266:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom);
  267:         if (ref($foils) eq 'ARRAY') {
  268: 	    foreach my $foil (@{$foils}) {
  269: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
  270: 		    return $foil;
  271: 	        }
  272: 	    }
  273: 	}
  274:     }
  275: 
  276:     sub scantron_partids_tograde {
  277:         my ($resource,$cid,$uname,$udom,$check_for_randomlist) = @_;
  278:         my (%analysis,@parts);
  279:         if (ref($resource)) {
  280:             my $symb = $resource->symb();
  281:             my $add_to_form;
  282:             if ($check_for_randomlist) {
  283:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
  284:             }
  285:             my $analyze = &get_analyze($symb,$uname,$udom,undef,$add_to_form);
  286:             if (ref($analyze) eq 'HASH') {
  287:                 %analysis = %{$analyze};
  288:             }
  289:             if (ref($analysis{'parts'}) eq 'ARRAY') {
  290:                 foreach my $part (@{$analysis{'parts'}}) {
  291:                     my ($id,$respid) = split(/\./,$part);
  292:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
  293:                         push(@parts,$part);
  294:                     }
  295:                 }
  296:             }
  297:         }
  298:         return (\%analysis,\@parts);
  299:     }
  300: 
  301: }
  302: 
  303: #--- Clean response type for display
  304: #--- Currently filters option/rank/radiobutton/match/essay/Task
  305: #        response types only.
  306: sub cleanRecord {
  307:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
  308: 	$uname,$udom) = @_;
  309:     my $grayFont = '<span class="LC_internal_info">';
  310:     if ($response =~ /^(option|rank)$/) {
  311: 	my %answer=&Apache::lonnet::str2hash($answer);
  312: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  313: 	my ($toprow,$bottomrow);
  314: 	foreach my $foil (@$order) {
  315: 	    if ($grading{$foil} == 1) {
  316: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
  317: 	    } else {
  318: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
  319: 	    }
  320: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  321: 	}
  322: 	return '<blockquote><table border="1">'.
  323: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  324: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  325: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
  326:     } elsif ($response eq 'match') {
  327: 	my %answer=&Apache::lonnet::str2hash($answer);
  328: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  329: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
  330: 	my ($toprow,$middlerow,$bottomrow);
  331: 	foreach my $foil (@$order) {
  332: 	    my $item=shift(@items);
  333: 	    if ($grading{$foil} == 1) {
  334: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
  335: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
  336: 	    } else {
  337: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
  338: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
  339: 	    }
  340: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  341: 	}
  342: 	return '<blockquote><table border="1">'.
  343: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  344: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
  345: 	    $middlerow.'</tr>'.
  346: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  347: 	    $bottomrow.'</tr>'.'</table></blockquote>';
  348:     } elsif ($response eq 'radiobutton') {
  349: 	my %answer=&Apache::lonnet::str2hash($answer);
  350: 	my ($toprow,$bottomrow);
  351: 	my $correct = 
  352: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom);
  353: 	foreach my $foil (@$order) {
  354: 	    if (exists($answer{$foil})) {
  355: 		if ($foil eq $correct) {
  356: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
  357: 		} else {
  358: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
  359: 		}
  360: 	    } else {
  361: 		$toprow.='<td>'.&mt('false').'</td>';
  362: 	    }
  363: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  364: 	}
  365: 	return '<blockquote><table border="1">'.
  366: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  367: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  368: 	    $bottomrow.'</tr>'.'</table></blockquote>';
  369:     } elsif ($response eq 'essay') {
  370: 	if (! exists ($env{'form.'.$symb})) {
  371: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
  372: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
  373: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
  374: 
  375: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
  376: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
  377: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
  378: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
  379: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
  380: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
  381: 	}
  382: 	$answer =~ s-\n-<br />-g;
  383: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
  384:     } elsif ( $response eq 'organic') {
  385: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
  386: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
  387: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
  388: 	return $result;
  389:     } elsif ( $response eq 'Task') {
  390: 	if ( $answer eq 'SUBMITTED') {
  391: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
  392: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
  393: 	    return $result;
  394: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
  395: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
  396: 			       keys(%{$record}));
  397: 	    return join('<br />',($version,@matches));
  398: 			       
  399: 			       
  400: 	} else {
  401: 	    my $result =
  402: 		'<p>'
  403: 		.&mt('Overall result: [_1]',
  404: 		     $record->{$version."resource.$respid.$partid.status"})
  405: 		.'</p>';
  406: 	    
  407: 	    $result .= '<ul>';
  408: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
  409: 			     keys(%{$record}));
  410: 	    foreach my $grade (sort(@grade)) {
  411: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
  412: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
  413: 				     $dim, $record->{$grade}).
  414: 			  '</li>';
  415: 	    }
  416: 	    $result.='</ul>';
  417: 	    return $result;
  418: 	}
  419:     } elsif ( $response =~ m/(?:numerical|formula)/) {
  420: 	$answer = 
  421: 	    &Apache::loncommon::format_previous_attempt_value('submission',
  422: 							      $answer);
  423:     }
  424:     return $answer;
  425: }
  426: 
  427: #-- A couple of common js functions
  428: sub commonJSfunctions {
  429:     my $request = shift;
  430:     $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
  431:     function radioSelection(radioButton) {
  432: 	var selection=null;
  433: 	if (radioButton.length > 1) {
  434: 	    for (var i=0; i<radioButton.length; i++) {
  435: 		if (radioButton[i].checked) {
  436: 		    return radioButton[i].value;
  437: 		}
  438: 	    }
  439: 	} else {
  440: 	    if (radioButton.checked) return radioButton.value;
  441: 	}
  442: 	return selection;
  443:     }
  444: 
  445:     function pullDownSelection(selectOne) {
  446: 	var selection="";
  447: 	if (selectOne.length > 1) {
  448: 	    for (var i=0; i<selectOne.length; i++) {
  449: 		if (selectOne[i].selected) {
  450: 		    return selectOne[i].value;
  451: 		}
  452: 	    }
  453: 	} else {
  454:             // only one value it must be the selected one
  455: 	    return selectOne.value;
  456: 	}
  457:     }
  458: COMMONJSFUNCTIONS
  459: }
  460: 
  461: #--- Dumps the class list with usernames,list of sections,
  462: #--- section, ids and fullnames for each user.
  463: sub getclasslist {
  464:     my ($getsec,$filterlist,$getgroup) = @_;
  465:     my @getsec;
  466:     my @getgroup;
  467:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  468:     if (!ref($getsec)) {
  469: 	if ($getsec ne '' && $getsec ne 'all') {
  470: 	    @getsec=($getsec);
  471: 	}
  472:     } else {
  473: 	@getsec=@{$getsec};
  474:     }
  475:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
  476:     if (!ref($getgroup)) {
  477: 	if ($getgroup ne '' && $getgroup ne 'all') {
  478: 	    @getgroup=($getgroup);
  479: 	}
  480:     } else {
  481: 	@getgroup=@{$getgroup};
  482:     }
  483:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
  484: 
  485:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
  486:     # Bail out if we were unable to get the classlist
  487:     return if (! defined($classlist));
  488:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
  489:     #
  490:     my %sections;
  491:     my %fullnames;
  492:     foreach my $student (keys(%$classlist)) {
  493:         my $end      = 
  494:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
  495:         my $start    = 
  496:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
  497:         my $id       = 
  498:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
  499:         my $section  = 
  500:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
  501:         my $fullname = 
  502:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
  503:         my $status   = 
  504:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
  505:         my $group   = 
  506:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
  507: 	# filter students according to status selected
  508: 	if ($filterlist && (!($stu_status =~ /Any/))) {
  509: 	    if (!($stu_status =~ $status)) {
  510: 		delete($classlist->{$student});
  511: 		next;
  512: 	    }
  513: 	}
  514: 	# filter students according to groups selected
  515: 	my @stu_groups = split(/,/,$group);
  516: 	if (@getgroup) {
  517: 	    my $exclude = 1;
  518: 	    foreach my $grp (@getgroup) {
  519: 	        foreach my $stu_group (@stu_groups) {
  520: 	            if ($stu_group eq $grp) {
  521: 	                $exclude = 0;
  522:     	            } 
  523: 	        }
  524:     	        if (($grp eq 'none') && !$group) {
  525:         	        $exclude = 0;
  526:         	}
  527: 	    }
  528: 	    if ($exclude) {
  529: 	        delete($classlist->{$student});
  530: 	    }
  531: 	}
  532: 	$section = ($section ne '' ? $section : 'none');
  533: 	if (&canview($section)) {
  534: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
  535: 		$sections{$section}++;
  536: 		if ($classlist->{$student}) {
  537: 		    $fullnames{$student}=$fullname;
  538: 		}
  539: 	    } else {
  540: 		delete($classlist->{$student});
  541: 	    }
  542: 	} else {
  543: 	    delete($classlist->{$student});
  544: 	}
  545:     }
  546:     my %seen = ();
  547:     my @sections = sort(keys(%sections));
  548:     return ($classlist,\@sections,\%fullnames);
  549: }
  550: 
  551: sub canmodify {
  552:     my ($sec)=@_;
  553:     if ($perm{'mgr'}) {
  554: 	if (!defined($perm{'mgr_section'})) {
  555: 	    # can modify whole class
  556: 	    return 1;
  557: 	} else {
  558: 	    if ($sec eq $perm{'mgr_section'}) {
  559: 		#can modify the requested section
  560: 		return 1;
  561: 	    } else {
  562: 		# can't modify the request section
  563: 		return 0;
  564: 	    }
  565: 	}
  566:     }
  567:     #can't modify
  568:     return 0;
  569: }
  570: 
  571: sub canview {
  572:     my ($sec)=@_;
  573:     if ($perm{'vgr'}) {
  574: 	if (!defined($perm{'vgr_section'})) {
  575: 	    # can modify whole class
  576: 	    return 1;
  577: 	} else {
  578: 	    if ($sec eq $perm{'vgr_section'}) {
  579: 		#can modify the requested section
  580: 		return 1;
  581: 	    } else {
  582: 		# can't modify the request section
  583: 		return 0;
  584: 	    }
  585: 	}
  586:     }
  587:     #can't modify
  588:     return 0;
  589: }
  590: 
  591: #--- Retrieve the grade status of a student for all the parts
  592: sub student_gradeStatus {
  593:     my ($symb,$udom,$uname,$partlist) = @_;
  594:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
  595:     my %partstatus = ();
  596:     foreach (@$partlist) {
  597: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
  598: 	$status              = 'nothing' if ($status eq '');
  599: 	$partstatus{$_}      = $status;
  600: 	my $subkey           = "resource.$_.submitted_by";
  601: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
  602:     }
  603:     return %partstatus;
  604: }
  605: 
  606: # hidden form and javascript that calls the form
  607: # Use by verifyscript and viewgrades
  608: # Shows a student's view of problem and submission
  609: sub jscriptNform {
  610:     my ($symb) = @_;
  611:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  612:     my $jscript= &Apache::lonhtmlcommon::scripttag(
  613: 	'    function viewOneStudent(user,domain) {'."\n".
  614: 	'	document.onestudent.student.value = user;'."\n".
  615: 	'	document.onestudent.userdom.value = domain;'."\n".
  616: 	'	document.onestudent.submit();'."\n".
  617: 	'    }'."\n".
  618: 	"\n");
  619:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
  620: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\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;
  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,$submitonly) = @_;
  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:     unless ($submitonly) {
  819:        $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
  820:     }
  821: 
  822:     my $result='<h3><span class="LC_info">&nbsp;'
  823: 	.&mt("View/Grade/Regrade Submissions for a Student or a Group of Students")
  824: 	.'</span></h3>';
  825: 
  826:     my ($partlist,$handgrade,$responseType) = &response_type($symb
  827: #,$res_error
  828:     );
  829: 
  830:     my %lt = &Apache::lonlocal::texthash (
  831: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
  832: 		'single'   => 'Please select the student before clicking on the Next button.',
  833: 	     );
  834:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
  835:     function checkSelect(checkBox) {
  836: 	var ctr=0;
  837: 	var sense="";
  838: 	if (checkBox.length > 1) {
  839: 	    for (var i=0; i<checkBox.length; i++) {
  840: 		if (checkBox[i].checked) {
  841: 		    ctr++;
  842: 		}
  843: 	    }
  844: 	    sense = '$lt{'multiple'}';
  845: 	} else {
  846: 	    if (checkBox.checked) {
  847: 		ctr = 1;
  848: 	    }
  849: 	    sense = '$lt{'single'}';
  850: 	}
  851: 	if (ctr == 0) {
  852: 	    alert(sense);
  853: 	    return false;
  854: 	}
  855: 	document.gradesub.submit();
  856:     }
  857: 
  858:     function reLoadList(formname) {
  859: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
  860: 	formname.command.value = 'submission';
  861: 	formname.submit();
  862:     }
  863: LISTJAVASCRIPT
  864: 
  865:     &commonJSfunctions($request);
  866:     $request->print($result);
  867: 
  868:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
  869:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
  870:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
  871: 	"\n";
  872: 	
  873:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
  874:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
  875:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
  876:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
  877:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
  878:                   .&Apache::lonhtmlcommon::row_closure();
  879:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
  880:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
  881:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
  882:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
  883:                   .&Apache::lonhtmlcommon::row_closure();
  884: 
  885:     my $submission_options;
  886:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
  887: 	$submission_options.=
  888: 	    '<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> '.&mt('essay part only').' </label>'."\n";
  889:     }
  890:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  891:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
  892:     $env{'form.Status'} = $saveStatus;
  893:     $submission_options.=
  894:         '<span class="LC_nobreak">'.
  895:         '<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> '.
  896:         &mt('last submission only').' </label></span>'."\n".
  897:         '<span class="LC_nobreak">'.
  898:         '<label><input type="radio" name="lastSub" value="last" /> '.
  899:         &mt('last submission &amp; parts info').' </label></span>'."\n".
  900:         '<span class="LC_nobreak">'.
  901:         '<label><input type="radio" name="lastSub" value="datesub" /> '.
  902:         &mt('by dates and submissions').'</label></span>'."\n".
  903:         '<span class="LC_nobreak">'.
  904:         '<label><input type="radio" name="lastSub" value="all" /> '.
  905:         &mt('all details').'</label></span>';
  906:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
  907:                   .$submission_options
  908:                   .&Apache::lonhtmlcommon::row_closure();
  909: 
  910:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
  911:                   .'<select name="increment">'
  912:                   .'<option value="1">'.&mt('Whole Points').'</option>'
  913:                   .'<option value=".5">'.&mt('Half Points').'</option>'
  914:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
  915:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
  916:                   .'</select>'
  917:                   .&Apache::lonhtmlcommon::row_closure();
  918: 
  919:     $gradeTable .= 
  920:         &build_section_inputs().
  921: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
  922: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
  923: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  924: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
  925: 
  926:     if (exists($env{'form.Status'})) {
  927: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
  928:     } else {
  929:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
  930:                       .&Apache::lonhtmlcommon::StatusOptions(
  931:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
  932:                       .&Apache::lonhtmlcommon::row_closure();
  933:     }
  934: 
  935:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
  936:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
  937:                   .&Apache::lonhtmlcommon::row_closure(1)
  938:                   .&Apache::lonhtmlcommon::end_pick_box();
  939: 
  940:     $gradeTable .= '<p>'
  941:                   .&mt("To view/grade/regrade a submission or a group of submissions, click on the check box(es) next to the student's name(s). Then click on the Next button.")."\n"
  942:                   .'<input type="hidden" name="command" value="processGroup" />'
  943:                   .'</p>';
  944: 
  945: # checkall buttons
  946:     $gradeTable.=&check_script('gradesub', 'stuinfo');
  947:     $gradeTable.='<input type="button" '."\n".
  948:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
  949:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
  950:     $gradeTable.=&check_buttons();
  951:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
  952:     $gradeTable.= &Apache::loncommon::start_data_table().
  953: 	&Apache::loncommon::start_data_table_header_row();
  954:     my $loop = 0;
  955:     while ($loop < 2) {
  956: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
  957: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
  958: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
  959: 	    foreach my $part (sort(@$partlist)) {
  960: 		my $display_part=
  961: 		    &get_display_part((split(/_/,$part))[0],$symb);
  962: 		$gradeTable.=
  963: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
  964: 	    }
  965: 	} elsif ($submitonly eq 'queued') {
  966: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
  967: 	}
  968: 	$loop++;
  969: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
  970:     }
  971:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
  972: 
  973:     my $ctr = 0;
  974:     foreach my $student (sort 
  975: 			 {
  976: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  977: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  978: 			     }
  979: 			     return $a cmp $b;
  980: 			 }
  981: 			 (keys(%$fullname))) {
  982: 	my ($uname,$udom) = split(/:/,$student);
  983: 
  984: 	my %status = ();
  985: 
  986: 	if ($submitonly eq 'queued') {
  987: 	    my %queue_status = 
  988: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
  989: 							$udom,$uname);
  990: 	    next if (!defined($queue_status{'gradingqueue'}));
  991: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
  992: 	}
  993: 
  994: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
  995: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
  996: 	    my $submitted = 0;
  997: 	    my $graded = 0;
  998: 	    my $incorrect = 0;
  999: 	    foreach (keys(%status)) {
 1000: 		$submitted = 1 if ($status{$_} ne 'nothing');
 1001: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
 1002: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
 1003: 		
 1004: 		my ($foo,$partid,$foo1) = split(/\./,$_);
 1005: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 1006: 		    $submitted = 0;
 1007: 		    my ($part)=split(/\./,$partid);
 1008: 		    $gradeTable.='<input type="hidden" name="'.
 1009: 			$student.':'.$part.':submitted_by" value="'.
 1010: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
 1011: 		}
 1012: 	    }
 1013: 	    
 1014: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 1015: 				     $submitonly eq 'incorrect' ||
 1016: 				     $submitonly eq 'graded'));
 1017: 	    next if (!$graded && ($submitonly eq 'graded'));
 1018: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 1019: 	}
 1020: 
 1021: 	$ctr++;
 1022: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
 1023:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
 1024: 	if ( $perm{'vgr'} eq 'F' ) {
 1025: 	    if ($ctr%2 ==1) {
 1026: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
 1027: 	    }
 1028: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
 1029:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
 1030:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
 1031: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
 1032: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
 1033: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
 1034: 
 1035: 	    if ($submitonly ne 'all') {
 1036: 		foreach (sort(keys(%status))) {
 1037: 		    next if ($_ =~ /^resource.*?submitted_by$/);
 1038: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
 1039: 		}
 1040: 	    }
 1041: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
 1042: 	    if ($ctr%2 ==0) {
 1043: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
 1044: 	    }
 1045: 	}
 1046:     }
 1047:     if ($ctr%2 ==1) {
 1048: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
 1049: 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1050: 		foreach (@$partlist) {
 1051: 		    $gradeTable.='<td>&nbsp;</td>';
 1052: 		}
 1053: 	    } elsif ($submitonly eq 'queued') {
 1054: 		$gradeTable.='<td>&nbsp;</td>';
 1055: 	    }
 1056: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
 1057:     }
 1058: 
 1059:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
 1060:         '<input type="button" '.
 1061:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
 1062:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
 1063:     if ($ctr == 0) {
 1064: 	my $num_students=(scalar(keys(%$fullname)));
 1065: 	if ($num_students eq 0) {
 1066: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
 1067: 	} else {
 1068: 	    my $submissions='submissions';
 1069: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
 1070: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
 1071: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
 1072: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
 1073: 		&mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
 1074: 		    $num_students).
 1075: 		'</span><br />';
 1076: 	}
 1077:     } elsif ($ctr == 1) {
 1078: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
 1079:     }
 1080:     $request->print($gradeTable);
 1081:     return '';
 1082: }
 1083: 
 1084: #---- Called from the listStudents routine
 1085: 
 1086: sub check_script {
 1087:     my ($form, $type)=@_;
 1088:     my $chkallscript= &Apache::lonhtmlcommon::scripttag('
 1089:     function checkall() {
 1090:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1091:             ele = document.forms.'.$form.'.elements[i];
 1092:             if (ele.name == "'.$type.'") {
 1093:             document.forms.'.$form.'.elements[i].checked=true;
 1094:                                        }
 1095:         }
 1096:     }
 1097: 
 1098:     function checksec() {
 1099:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1100:             ele = document.forms.'.$form.'.elements[i];
 1101:            string = document.forms.'.$form.'.chksec.value;
 1102:            if
 1103:           (ele.value.indexOf(":::SECTION"+string)>0) {
 1104:               document.forms.'.$form.'.elements[i].checked=true;
 1105:             }
 1106:         }
 1107:     }
 1108: 
 1109: 
 1110:     function uncheckall() {
 1111:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1112:             ele = document.forms.'.$form.'.elements[i];
 1113:             if (ele.name == "'.$type.'") {
 1114:             document.forms.'.$form.'.elements[i].checked=false;
 1115:                                        }
 1116:         }
 1117:     }
 1118: 
 1119: '."\n");
 1120:     return $chkallscript;
 1121: }
 1122: 
 1123: sub check_buttons {
 1124:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
 1125:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
 1126:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
 1127:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
 1128:     return $buttons;
 1129: }
 1130: 
 1131: #     Displays the submissions for one student or a group of students
 1132: sub processGroup {
 1133:     my ($request,$symb)  = @_;
 1134:     my $ctr        = 0;
 1135:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1136:     my $total      = scalar(@stuchecked)-1;
 1137: 
 1138:     foreach my $student (@stuchecked) {
 1139: 	my ($uname,$udom,$fullname) = split(/:/,$student);
 1140: 	$env{'form.student'}        = $uname;
 1141: 	$env{'form.userdom'}        = $udom;
 1142: 	$env{'form.fullname'}       = $fullname;
 1143: 	&submission($request,$ctr,$total,$symb);
 1144: 	$ctr++;
 1145:     }
 1146:     return '';
 1147: }
 1148: 
 1149: #------------------------------------------------------------------------------------
 1150: #
 1151: #-------------------------- Next few routines handles grading by student, essentially
 1152: #                           handles essay response type problem/part
 1153: #
 1154: #--- Javascript to handle the submission page functionality ---
 1155: sub sub_page_js {
 1156:     my $request = shift;
 1157: 	    my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 1158:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1159:     function updateRadio(formname,id,weight) {
 1160: 	var gradeBox = formname["GD_BOX"+id];
 1161: 	var radioButton = formname["RADVAL"+id];
 1162: 	var oldpts = formname["oldpts"+id].value;
 1163: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
 1164: 	gradeBox.value = pts;
 1165: 	var resetbox = false;
 1166: 	if (isNaN(pts) || pts < 0) {
 1167: 	    alert("$alertmsg"+pts);
 1168: 	    for (var i=0; i<radioButton.length; i++) {
 1169: 		if (radioButton[i].checked) {
 1170: 		    gradeBox.value = i;
 1171: 		    resetbox = true;
 1172: 		}
 1173: 	    }
 1174: 	    if (!resetbox) {
 1175: 		formtextbox.value = "";
 1176: 	    }
 1177: 	    return;
 1178: 	}
 1179: 
 1180: 	if (pts > weight) {
 1181: 	    var resp = confirm("You entered a value ("+pts+
 1182: 			       ") greater than the weight for the part. Accept?");
 1183: 	    if (resp == false) {
 1184: 		gradeBox.value = oldpts;
 1185: 		return;
 1186: 	    }
 1187: 	}
 1188: 
 1189: 	for (var i=0; i<radioButton.length; i++) {
 1190: 	    radioButton[i].checked=false;
 1191: 	    if (pts == i && pts != "") {
 1192: 		radioButton[i].checked=true;
 1193: 	    }
 1194: 	}
 1195: 	updateSelect(formname,id);
 1196: 	formname["stores"+id].value = "0";
 1197:     }
 1198: 
 1199:     function writeBox(formname,id,pts) {
 1200: 	var gradeBox = formname["GD_BOX"+id];
 1201: 	if (checkSolved(formname,id) == 'update') {
 1202: 	    gradeBox.value = pts;
 1203: 	} else {
 1204: 	    var oldpts = formname["oldpts"+id].value;
 1205: 	    gradeBox.value = oldpts;
 1206: 	    var radioButton = formname["RADVAL"+id];
 1207: 	    for (var i=0; i<radioButton.length; i++) {
 1208: 		radioButton[i].checked=false;
 1209: 		if (i == oldpts) {
 1210: 		    radioButton[i].checked=true;
 1211: 		}
 1212: 	    }
 1213: 	}
 1214: 	formname["stores"+id].value = "0";
 1215: 	updateSelect(formname,id);
 1216: 	return;
 1217:     }
 1218: 
 1219:     function clearRadBox(formname,id) {
 1220: 	if (checkSolved(formname,id) == 'noupdate') {
 1221: 	    updateSelect(formname,id);
 1222: 	    return;
 1223: 	}
 1224: 	gradeSelect = formname["GD_SEL"+id];
 1225: 	for (var i=0; i<gradeSelect.length; i++) {
 1226: 	    if (gradeSelect[i].selected) {
 1227: 		var selectx=i;
 1228: 	    }
 1229: 	}
 1230: 	var stores = formname["stores"+id];
 1231: 	if (selectx == stores.value) { return };
 1232: 	var gradeBox = formname["GD_BOX"+id];
 1233: 	gradeBox.value = "";
 1234: 	var radioButton = formname["RADVAL"+id];
 1235: 	for (var i=0; i<radioButton.length; i++) {
 1236: 	    radioButton[i].checked=false;
 1237: 	}
 1238: 	stores.value = selectx;
 1239:     }
 1240: 
 1241:     function checkSolved(formname,id) {
 1242: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
 1243: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
 1244: 	    if (!reply) {return "noupdate";}
 1245: 	    formname.overRideScore.value = 'yes';
 1246: 	}
 1247: 	return "update";
 1248:     }
 1249: 
 1250:     function updateSelect(formname,id) {
 1251: 	formname["GD_SEL"+id][0].selected = true;
 1252: 	return;
 1253:     }
 1254: 
 1255: //=========== Check that a point is assigned for all the parts  ============
 1256:     function checksubmit(formname,val,total,parttot) {
 1257: 	formname.gradeOpt.value = val;
 1258: 	if (val == "Save & Next") {
 1259: 	    for (i=0;i<=total;i++) {
 1260: 		for (j=0;j<parttot;j++) {
 1261: 		    var partid = formname["partid"+i+"_"+j].value;
 1262: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1263: 			var points = formname["GD_BOX"+i+"_"+partid].value;
 1264: 			if (points == "") {
 1265: 			    var name = formname["name"+i].value;
 1266: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
 1267: 			    var resp = confirm("You did not assign a score for "+studentID+
 1268: 					       ", part "+partid+". Continue?");
 1269: 			    if (resp == false) {
 1270: 				formname["GD_BOX"+i+"_"+partid].focus();
 1271: 				return false;
 1272: 			    }
 1273: 			}
 1274: 		    }
 1275: 		    
 1276: 		}
 1277: 	    }
 1278: 	    
 1279: 	}
 1280: 	if (val == "Grade Student") {
 1281: 	    if (formname.Status.value == "") {
 1282: 		formname.Status.value = "Active";
 1283: 	    }
 1284: 	    formname.studentNo.value = total;
 1285: 	}
 1286: 	formname.submit();
 1287:     }
 1288: 
 1289: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1290:     function checkSubmitPage(formname,total) {
 1291: 	noscore = new Array(100);
 1292: 	var ptr = 0;
 1293: 	for (i=1;i<total;i++) {
 1294: 	    var partid = formname["q_"+i].value;
 1295: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1296: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1297: 		var status = formname["solved"+i+"_"+partid].value;
 1298: 		if (points == "" && status != "correct_by_student") {
 1299: 		    noscore[ptr] = i;
 1300: 		    ptr++;
 1301: 		}
 1302: 	    }
 1303: 	}
 1304: 	if (ptr != 0) {
 1305: 	    var sense = ptr == 1 ? ": " : "s: ";
 1306: 	    var prolist = "";
 1307: 	    if (ptr == 1) {
 1308: 		prolist = noscore[0];
 1309: 	    } else {
 1310: 		var i = 0;
 1311: 		while (i < ptr-1) {
 1312: 		    prolist += noscore[i]+", ";
 1313: 		    i++;
 1314: 		}
 1315: 		prolist += "and "+noscore[i];
 1316: 	    }
 1317: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1318: 	    if (resp == false) {
 1319: 		return false;
 1320: 	    }
 1321: 	}
 1322: 
 1323: 	formname.submit();
 1324:     }
 1325: SUBJAVASCRIPT
 1326: }
 1327: 
 1328: #--- javascript for essay type problem --
 1329: sub sub_page_kw_js {
 1330:     my $request = shift;
 1331:     my $iconpath = $request->dir_config('lonIconsURL');
 1332:     &commonJSfunctions($request);
 1333: 
 1334:     my $inner_js_msg_central= &Apache::lonhtmlcommon::scripttag(<<INNERJS);
 1335:     function checkInput() {
 1336:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1337:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1338:       var usrctr = document.msgcenter.usrctr.value;
 1339:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1340:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1341: 
 1342:       var msgchk = "";
 1343:       if (document.msgcenter.subchk.checked) {
 1344:          msgchk = "msgsub,";
 1345:       }
 1346:       var includemsg = 0;
 1347:       for (var i=1; i<=nmsg; i++) {
 1348:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1349:           var frmmsg = document.msgcenter["msg"+i];
 1350:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1351:           var showflg = opener.document.SCORE["shownOnce"+i];
 1352:           showflg.value = "1";
 1353:           var chkbox = document.msgcenter["msgn"+i];
 1354:           if (chkbox.checked) {
 1355:              msgchk += "savemsg"+i+",";
 1356:              includemsg = 1;
 1357:           }
 1358:       }
 1359:       if (document.msgcenter.newmsgchk.checked) {
 1360:          msgchk += "newmsg"+usrctr;
 1361:          includemsg = 1;
 1362:       }
 1363:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1364:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1365:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1366:       includemsg.value = msgchk;
 1367: 
 1368:       self.close()
 1369: 
 1370:     }
 1371: INNERJS
 1372: 
 1373:     my $inner_js_highlight_central= &Apache::lonhtmlcommon::scripttag(<<INNERJS);
 1374:     function updateChoice(flag) {
 1375:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1376:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1377:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1378:       opener.document.SCORE.refresh.value = "on";
 1379:       if (opener.document.SCORE.keywords.value!=""){
 1380:          opener.document.SCORE.submit();
 1381:       }
 1382:       self.close()
 1383:     }
 1384: INNERJS
 1385: 
 1386:     my $start_page_msg_central = 
 1387:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1388: 				       {'js_ready'  => 1,
 1389: 					'only_body' => 1,
 1390: 					'bgcolor'   =>'#FFFFFF',});
 1391:     my $end_page_msg_central = 
 1392: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1393: 
 1394: 
 1395:     my $start_page_highlight_central = 
 1396:         &Apache::loncommon::start_page('Highlight Central',
 1397: 				       $inner_js_highlight_central,
 1398: 				       {'js_ready'  => 1,
 1399: 					'only_body' => 1,
 1400: 					'bgcolor'   =>'#FFFFFF',});
 1401:     my $end_page_highlight_central = 
 1402: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1403: 
 1404:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1405:     $docopen=~s/^document\.//;
 1406:     my $alertmsg = &mt('Please select a word or group of words from document and then click this link.');
 1407:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1408: 
 1409: //===================== Show list of keywords ====================
 1410:   function keywords(formname) {
 1411:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
 1412:     if (nret==null) return;
 1413:     formname.keywords.value = nret;
 1414: 
 1415:     if (formname.keywords.value != "") {
 1416: 	formname.refresh.value = "on";
 1417: 	formname.submit();
 1418:     }
 1419:     return;
 1420:   }
 1421: 
 1422: //===================== Script to view submitted by ==================
 1423:   function viewSubmitter(submitter) {
 1424:     document.SCORE.refresh.value = "on";
 1425:     document.SCORE.NCT.value = "1";
 1426:     document.SCORE.unamedom0.value = submitter;
 1427:     document.SCORE.submit();
 1428:     return;
 1429:   }
 1430: 
 1431: //===================== Script to add keyword(s) ==================
 1432:   function getSel() {
 1433:     if (document.getSelection) txt = document.getSelection();
 1434:     else if (document.selection) txt = document.selection.createRange().text;
 1435:     else return;
 1436:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1437:     if (cleantxt=="") {
 1438: 	alert("$alertmsg");
 1439: 	return;
 1440:     }
 1441:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
 1442:     if (nret==null) return;
 1443:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1444:     if (document.SCORE.keywords.value != "") {
 1445: 	document.SCORE.refresh.value = "on";
 1446: 	document.SCORE.submit();
 1447:     }
 1448:     return;
 1449:   }
 1450: 
 1451: //====================== Script for composing message ==============
 1452:    // preload images
 1453:    img1 = new Image();
 1454:    img1.src = "$iconpath/mailbkgrd.gif";
 1455:    img2 = new Image();
 1456:    img2.src = "$iconpath/mailto.gif";
 1457: 
 1458:   function msgCenter(msgform,usrctr,fullname) {
 1459:     var Nmsg  = msgform.savemsgN.value;
 1460:     savedMsgHeader(Nmsg,usrctr,fullname);
 1461:     var subject = msgform.msgsub.value;
 1462:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1463:     re = /msgsub/;
 1464:     var shwsel = "";
 1465:     if (re.test(msgchk)) { shwsel = "checked" }
 1466:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1467:     displaySubject(checkEntities(subject),shwsel);
 1468:     for (var i=1; i<=Nmsg; i++) {
 1469: 	var testmsg = "savemsg"+i+",";
 1470: 	re = new RegExp(testmsg,"g");
 1471: 	shwsel = "";
 1472: 	if (re.test(msgchk)) { shwsel = "checked" }
 1473: 	var message = document.SCORE["savemsg"+i].value;
 1474: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1475: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1476: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1477:     }
 1478:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1479:     shwsel = "";
 1480:     re = /newmsg/;
 1481:     if (re.test(msgchk)) { shwsel = "checked" }
 1482:     newMsg(newmsg,shwsel);
 1483:     msgTail(); 
 1484:     return;
 1485:   }
 1486: 
 1487:   function checkEntities(strx) {
 1488:     if (strx.length == 0) return strx;
 1489:     var orgStr = ["&", "<", ">", '"']; 
 1490:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1491:     var counter = 0;
 1492:     while (counter < 4) {
 1493: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1494: 	counter++;
 1495:     }
 1496:     return strx;
 1497:   }
 1498: 
 1499:   function strReplace(strx, orgStr, newStr) {
 1500:     return strx.split(orgStr).join(newStr);
 1501:   }
 1502: 
 1503:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1504:     var height = 70*Nmsg+250;
 1505:     var scrollbar = "no";
 1506:     if (height > 600) {
 1507: 	height = 600;
 1508: 	scrollbar = "yes";
 1509:     }
 1510:     var xpos = (screen.width-600)/2;
 1511:     xpos = (xpos < 0) ? '0' : xpos;
 1512:     var ypos = (screen.height-height)/2-30;
 1513:     ypos = (ypos < 0) ? '0' : ypos;
 1514: 
 1515:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
 1516:     pWin.focus();
 1517:     pDoc = pWin.document;
 1518:     pDoc.$docopen;
 1519:     pDoc.write('$start_page_msg_central');
 1520: 
 1521:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1522:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1523:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
 1524: 
 1525:     pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
 1526:     pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
 1527:     pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
 1528: }
 1529:     function displaySubject(msg,shwsel) {
 1530:     pDoc = pWin.document;
 1531:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1532:     pDoc.write("<td>Subject<\\/td>");
 1533:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1534:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
 1535: }
 1536: 
 1537:   function displaySavedMsg(ctr,msg,shwsel) {
 1538:     pDoc = pWin.document;
 1539:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1540:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
 1541:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1542:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
 1543: }
 1544: 
 1545:   function newMsg(newmsg,shwsel) {
 1546:     pDoc = pWin.document;
 1547:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1548:     pDoc.write("<td align=\\"center\\">New<\\/td>");
 1549:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1550:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
 1551: }
 1552: 
 1553:   function msgTail() {
 1554:     pDoc = pWin.document;
 1555:     pDoc.write("<\\/table>");
 1556:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1557:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1558:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onclick=\\"self.close()\\"><br /><br />");
 1559:     pDoc.write("<\\/form>");
 1560:     pDoc.write('$end_page_msg_central');
 1561:     pDoc.close();
 1562: }
 1563: 
 1564: //====================== Script for keyword highlight options ==============
 1565:   function kwhighlight() {
 1566:     var kwclr    = document.SCORE.kwclr.value;
 1567:     var kwsize   = document.SCORE.kwsize.value;
 1568:     var kwstyle  = document.SCORE.kwstyle.value;
 1569:     var redsel = "";
 1570:     var grnsel = "";
 1571:     var blusel = "";
 1572:     if (kwclr=="red")   {var redsel="checked"};
 1573:     if (kwclr=="green") {var grnsel="checked"};
 1574:     if (kwclr=="blue")  {var blusel="checked"};
 1575:     var sznsel = "";
 1576:     var sz1sel = "";
 1577:     var sz2sel = "";
 1578:     if (kwsize=="0")  {var sznsel="checked"};
 1579:     if (kwsize=="+1") {var sz1sel="checked"};
 1580:     if (kwsize=="+2") {var sz2sel="checked"};
 1581:     var synsel = "";
 1582:     var syisel = "";
 1583:     var sybsel = "";
 1584:     if (kwstyle=="")    {var synsel="checked"};
 1585:     if (kwstyle=="<i>") {var syisel="checked"};
 1586:     if (kwstyle=="<b>") {var sybsel="checked"};
 1587:     highlightCentral();
 1588:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
 1589:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
 1590:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
 1591:     highlightend();
 1592:     return;
 1593:   }
 1594: 
 1595:   function highlightCentral() {
 1596: //    if (window.hwdWin) window.hwdWin.close();
 1597:     var xpos = (screen.width-400)/2;
 1598:     xpos = (xpos < 0) ? '0' : xpos;
 1599:     var ypos = (screen.height-330)/2-30;
 1600:     ypos = (ypos < 0) ? '0' : ypos;
 1601: 
 1602:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1603:     hwdWin.focus();
 1604:     var hDoc = hwdWin.document;
 1605:     hDoc.$docopen;
 1606:     hDoc.write('$start_page_highlight_central');
 1607:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1608:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options<\\/span><\\/h3><br /><br />");
 1609: 
 1610:     hDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
 1611:     hDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
 1612:     hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
 1613:   }
 1614: 
 1615:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1616:     var hDoc = hwdWin.document;
 1617:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1618:     hDoc.write("<td align=\\"left\\">");
 1619:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
 1620:     hDoc.write("<td align=\\"left\\">");
 1621:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
 1622:     hDoc.write("<td align=\\"left\\">");
 1623:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
 1624:     hDoc.write("<\\/tr>");
 1625:   }
 1626: 
 1627:   function highlightend() { 
 1628:     var hDoc = hwdWin.document;
 1629:     hDoc.write("<\\/table>");
 1630:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1631:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onclick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
 1632:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onclick=\\"self.close()\\"><br /><br />");
 1633:     hDoc.write("<\\/form>");
 1634:     hDoc.write('$end_page_highlight_central');
 1635:     hDoc.close();
 1636:   }
 1637: 
 1638: SUBJAVASCRIPT
 1639: }
 1640: 
 1641: sub get_increment {
 1642:     my $increment = $env{'form.increment'};
 1643:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1644:         $increment != .1) {
 1645:         $increment = 1;
 1646:     }
 1647:     return $increment;
 1648: }
 1649: 
 1650: sub gradeBox_start {
 1651:     return (
 1652:         &Apache::loncommon::start_data_table()
 1653:        .&Apache::loncommon::start_data_table_header_row()
 1654:        .'<th>'.&mt('Part').'</th>'
 1655:        .'<th>'.&mt('Points').'</th>'
 1656:        .'<th>&nbsp;</th>'
 1657:        .'<th>'.&mt('Assign Grade').'</th>'
 1658:        .'<th>'.&mt('Weight').'</th>'
 1659:        .'<th>'.&mt('Grade Status').'</th>'
 1660:        .&Apache::loncommon::end_data_table_header_row()
 1661:     );
 1662: }
 1663: 
 1664: sub gradeBox_end {
 1665:     return (
 1666:         &Apache::loncommon::end_data_table()
 1667:     );
 1668: }
 1669: #--- displays the grading box, used in essay type problem and grading by page/sequence
 1670: sub gradeBox {
 1671:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 1672:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1673: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 1674:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 1675:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
 1676:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
 1677:     $wgt       = ($wgt > 0 ? $wgt : '1');
 1678:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 1679: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 1680:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 1681:     my $display_part= &get_display_part($partid,$symb);
 1682:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 1683: 				       [$partid]);
 1684:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 1685:     if ($last_resets{$partid}) {
 1686:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 1687:     }
 1688:     $result.=&Apache::loncommon::start_data_table_row();
 1689:     my $ctr = 0;
 1690:     my $thisweight = 0;
 1691:     my $increment = &get_increment();
 1692: 
 1693:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 1694:     while ($thisweight<=$wgt) {
 1695: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 1696:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 1697: 	    $thisweight.')" value="'.$thisweight.'" '.
 1698: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 1699: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 1700:         $thisweight += $increment;
 1701: 	$ctr++;
 1702:     }
 1703:     $radio.='</tr></table>';
 1704: 
 1705:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 1706: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 1707: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 1708: 	$wgt.')" /></td>'."\n";
 1709:     $line.='<td>/'.$wgt.' '.$wgtmsg.
 1710: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 1711: 	' </td>'."\n";
 1712:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
 1713: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 1714:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 1715: 	$line.='<option></option>'.
 1716: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
 1717:     } else {
 1718: 	$line.='<option selected="selected"></option>'.
 1719: 	    '<option value="excused" >'.&mt('excused').'</option>';
 1720:     }
 1721:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
 1722: 
 1723: 
 1724:     $result .= 
 1725: 	    '<td>'.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
 1726:     $result.=&Apache::loncommon::end_data_table_row();
 1727:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 1728: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 1729: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 1730: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 1731:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 1732:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 1733:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 1734:         $aggtries.'" />'."\n";
 1735:     my $res_error;
 1736:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
 1737:     if ($res_error) {
 1738:         return &navmap_errormsg();
 1739:     }
 1740:     return $result;
 1741: }
 1742: 
 1743: sub handback_box {
 1744:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error) = @_;
 1745:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
 1746:     my (@respids);
 1747:      my @part_response_id = &flatten_responseType($responseType);
 1748:     foreach my $part_response_id (@part_response_id) {
 1749:     	my ($part,$resp) = @{ $part_response_id };
 1750:         if ($part eq $partid) {
 1751:             push(@respids,$resp);
 1752:         }
 1753:     }
 1754:     my $result;
 1755:     foreach my $respid (@respids) {
 1756: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 1757: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 1758: 	next if (!@$files);
 1759: 	my $file_counter = 1;
 1760: 	foreach my $file (@$files) {
 1761: 	    if ($file =~ /\/portfolio\//) {
 1762:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 1763:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
 1764:     	        $file_disp = "$name.$ext";
 1765:     	        $file = $file_path.$file_disp;
 1766:     	        $result.=&mt('Return commented version of [_1] to student.',
 1767:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 1768:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 1769:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
 1770:     	        $result.='('.&mt('File will be uploaded when you click on Save &amp; Next below.').')<br />';
 1771:     	        $file_counter++;
 1772: 	    }
 1773: 	}
 1774:     }
 1775:     return $result;    
 1776: }
 1777: 
 1778: sub show_problem {
 1779:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 1780:     my $rendered;
 1781:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 1782:     &Apache::lonxml::remember_problem_counter();
 1783:     if ($mode eq 'both' or $mode eq 'text') {
 1784: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 1785: 						       $env{'request.course.id'},
 1786: 						       undef,\%form);
 1787:     }
 1788:     if ($removeform) {
 1789: 	$rendered=~s|<form(.*?)>||g;
 1790: 	$rendered=~s|</form>||g;
 1791: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 1792:     }
 1793:     my $companswer;
 1794:     if ($mode eq 'both' or $mode eq 'answer') {
 1795: 	&Apache::lonxml::restore_problem_counter();
 1796: 	$companswer=
 1797: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 1798: 						    $env{'request.course.id'},
 1799: 						    %form);
 1800:     }
 1801:     if ($removeform) {
 1802: 	$companswer=~s|<form(.*?)>||g;
 1803: 	$companswer=~s|</form>||g;
 1804: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 1805:     }
 1806:     $rendered=
 1807:         '<div class="LC_Box">'
 1808:        .'<h3 class="LC_hcell">'.&mt('View of the problem').'</h3>'
 1809:        .$rendered
 1810:        .'</div>';
 1811:     $companswer=
 1812:         '<div class="LC_Box">'
 1813:        .'<h3 class="LC_hcell">'.&mt('Correct answer').'</h3>'
 1814:        .$companswer
 1815:        .'</div>';
 1816:     my $result;
 1817:     if ($mode eq 'both') {
 1818:         $result=$rendered.$companswer;
 1819:     } elsif ($mode eq 'text') {
 1820:         $result=$rendered;
 1821:     } elsif ($mode eq 'answer') {
 1822:         $result=$companswer;
 1823:     }
 1824:     return $result;
 1825: }
 1826: 
 1827: sub files_exist {
 1828:     my ($r, $symb) = @_;
 1829:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1830: 
 1831:     foreach my $student (@students) {
 1832:         my ($uname,$udom,$fullname) = split(/:/,$student);
 1833:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 1834: 					      $udom,$uname);
 1835:         my ($string,$timestamp)= &get_last_submission(\%record);
 1836:         foreach my $submission (@$string) {
 1837:             my ($partid,$respid) =
 1838: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 1839:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 1840: 					   \%record);
 1841:             return 1 if (@$files);
 1842:         }
 1843:     }
 1844:     return 0;
 1845: }
 1846: 
 1847: sub download_all_link {
 1848:     my ($r,$symb) = @_;
 1849:     unless (&files_exist($r, $symb)) {
 1850:        $r->print(&mt('There are currently no submitted documents.'));
 1851:        return;
 1852:     }
 1853: 
 1854:     my $all_students = 
 1855: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 1856: 
 1857:     my $parts =
 1858: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 1859: 
 1860:     my $identifier = &Apache::loncommon::get_cgi_id();
 1861:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 1862:                              'cgi.'.$identifier.'.symb' => $symb,
 1863:                              'cgi.'.$identifier.'.parts' => $parts,});
 1864:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 1865: 	      &mt('Download All Submitted Documents').'</a>');
 1866:     return;
 1867: }
 1868: 
 1869: sub submit_download_link {
 1870:     my ($request,$symb) = @_;
 1871:     if (!$symb) { return ''; }
 1872: #FIXME: Figure out which type of problem this is and provide appropriate download
 1873:     &download_all_link($request,$symb);
 1874: }
 1875: 
 1876: sub build_section_inputs {
 1877:     my $section_inputs;
 1878:     if ($env{'form.section'} eq '') {
 1879:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 1880:     } else {
 1881:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 1882:         foreach my $section (@sections) {
 1883:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 1884:         }
 1885:     }
 1886:     return $section_inputs;
 1887: }
 1888: 
 1889: # --------------------------- show submissions of a student, option to grade 
 1890: sub submission {
 1891:     my ($request,$counter,$total,$symb) = @_;
 1892:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 1893:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 1894:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 1895:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 1896: 
 1897:     my $probtitle=&Apache::lonnet::gettitle($symb); 
 1898:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 1899: 
 1900:     if (!&canview($usec)) {
 1901: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
 1902: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
 1903: 			$env{'request.course.id'}.')</span>');
 1904: 	return;
 1905:     }
 1906: 
 1907:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 1908:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 1909:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 1910:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 1911:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1912: 	'" src="'.$request->dir_config('lonIconsURL').
 1913: 	'/check.gif" height="16" border="0" />';
 1914: 
 1915:     my %old_essays;
 1916:     # header info
 1917:     if ($counter == 0) {
 1918: 	&sub_page_js($request);
 1919: 	&sub_page_kw_js($request);
 1920: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>');
 1921: 
 1922: 	# option to display problem, only once else it cause problems 
 1923:         # with the form later since the problem has a form.
 1924: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 1925: 	    my $mode;
 1926: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 1927: 		$mode='both';
 1928: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 1929: 		$mode='text';
 1930: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 1931: 		$mode='answer';
 1932: 	    }
 1933: 	    &Apache::lonxml::clear_problem_counter();
 1934: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 1935: 	}
 1936: 
 1937: 	# kwclr is the only variable that is guaranteed to be non blank 
 1938:         # if this subroutine has been called once.
 1939: 	my %keyhash = ();
 1940: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
 1941: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 1942: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 1943: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 1944: 
 1945: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 1946: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 1947: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 1948: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 1949: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 1950: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
 1951: 		$keyhash{$symb.'_subject'} : $probtitle;
 1952: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 1953: 	}
 1954: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 1955: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 1956: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 1957: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 1958: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 1959: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 1960: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 1961: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 1962: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 1963: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 1964: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 1965: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 1966: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 1967: 			&build_section_inputs().
 1968: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 1969: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
 1970: 			'<input type="hidden" name="NCT"'.
 1971: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 1972: 	if ($env{'form.handgrade'} eq 'yes') {
 1973: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 1974: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 1975: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 1976: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
 1977: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 1978: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 1979: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 1980: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
 1981: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
 1982: 	    }
 1983: 	}
 1984: 	
 1985: 	my ($cts,$prnmsg) = (1,'');
 1986: 	while ($cts <= $env{'form.savemsgN'}) {
 1987: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 1988: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 1989: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 1990: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 1991: 		'" />'."\n".
 1992: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 1993: 	    $cts++;
 1994: 	}
 1995: 	$request->print($prnmsg);
 1996: 
 1997: 	if ($env{'form.handgrade'} eq 'yes') {
 1998: #
 1999: # Print out the keyword options line
 2000: #
 2001: 	    $request->print(<<KEYWORDS);
 2002: &nbsp;<b>Keyword Options:</b>&nbsp;
 2003: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
 2004: <a href="#" onmousedown="javascript:getSel(); return false"
 2005:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
 2006: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
 2007: KEYWORDS
 2008: #
 2009: # Load the other essays for similarity check
 2010: #
 2011:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 2012: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 2013: 	    $apath=&escape($apath);
 2014: 	    $apath=~s/\W/\_/gs;
 2015: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
 2016:         }
 2017:     }
 2018: 
 2019: # This is where output for one specific student would start
 2020:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
 2021:     $request->print(
 2022:         "\n\n"
 2023:        .'<div class="LC_grade_show_user'.$add_class.'">'
 2024:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
 2025:        ."\n"
 2026:     );
 2027: 
 2028:     # Show additional functions if allowed
 2029:     if ($perm{'vgr'}) {
 2030:         $request->print(
 2031:             &Apache::loncommon::track_student_link(
 2032:                 &mt('View recent activity'),
 2033:                 $uname,$udom,'check')
 2034:            .' '
 2035:         );
 2036:     }
 2037:     if ($perm{'opa'}) {
 2038:         $request->print(
 2039:             &Apache::loncommon::pprmlink(
 2040:                 &mt('Set/Change parameters'),
 2041:                 $uname,$udom,$symb,'check'));
 2042:     }
 2043: 
 2044:     # Show Problem
 2045:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2046: 	my $mode;
 2047: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2048: 	    $mode='both';
 2049: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2050: 	    $mode='text';
 2051: 	} elsif ($env{'form.vAns'} eq 'all') {
 2052: 	    $mode='answer';
 2053: 	}
 2054: 	&Apache::lonxml::clear_problem_counter();
 2055: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2056:     }
 2057: 
 2058:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2059:     my $res_error;
 2060:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2061:     if ($res_error) {
 2062:         $request->print(&navmap_errormsg());
 2063:         return;
 2064:     }
 2065: 
 2066:     # Display student info
 2067:     $request->print(($counter == 0 ? '' : '<br />'));
 2068: 
 2069:     my $result='<div class="LC_Box">'
 2070:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
 2071:     $result.='<input type="hidden" name="name'.$counter.
 2072:              '" value="'.$env{'form.fullname'}.'" />'."\n";
 2073:     if ($env{'form.handgrade'} eq 'no') {
 2074:         $result.='<p class="LC_info">'
 2075:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
 2076:                 ."</p>\n";
 2077:     }
 2078: 
 2079:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
 2080:     my $fullname;
 2081:     my $col_fullnames = [];
 2082:     if ($env{'form.handgrade'} eq 'yes') {
 2083: 	(my $sub_result,$fullname,$col_fullnames)=
 2084: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2085: 				 $counter);
 2086: 	$result.=$sub_result;
 2087:     }
 2088:     $request->print($result."\n");
 2089: 
 2090:     # print student answer/submission
 2091:     # Options are (1) Handgraded submission only
 2092:     #             (2) Last submission, includes submission that is not handgraded 
 2093:     #                  (for multi-response type part)
 2094:     #             (3) Last submission plus the parts info
 2095:     #             (4) The whole record for this student
 2096:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
 2097: 	my ($string,$timestamp)= &get_last_submission(\%record);
 2098: 	
 2099: 	my $lastsubonly;
 2100: 
 2101:         if ($$timestamp eq '') {
 2102:             $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
 2103:         } else {
 2104:             $lastsubonly =
 2105:                 '<div class="LC_grade_submissions_body">'
 2106:                .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
 2107: 
 2108: 	    my %seenparts;
 2109: 	    my @part_response_id = &flatten_responseType($responseType);
 2110: 	    foreach my $part (@part_response_id) {
 2111: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
 2112: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
 2113: 
 2114: 		my ($partid,$respid) = @{ $part };
 2115: 		my $display_part=&get_display_part($partid,$symb);
 2116: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2117: 		    if (exists($seenparts{$partid})) { next; }
 2118: 		    $seenparts{$partid}=1;
 2119: 		    my $submitby='<b>Part:</b> '.$display_part.
 2120: 			' <b>Collaborative submission by:</b> '.
 2121: 			'<a href="javascript:viewSubmitter(\''.
 2122: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
 2123: 			'\');" target="_self">'.
 2124: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
 2125: 		    $request->print($submitby);
 2126: 		    next;
 2127: 		}
 2128: 		my $responsetype = $responseType->{$partid}->{$respid};
 2129: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
 2130:                     $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
 2131:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2132:                         ' <span class="LC_internal_info">'.
 2133:                         '('.&mt('Part ID: [_1]',$respid).')'.
 2134:                         '</span>&nbsp; &nbsp;'.
 2135: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
 2136: 		    next;
 2137: 		}
 2138: 		foreach my $submission (@$string) {
 2139: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2140: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2141: 		    my ($ressub,$hide,$subval) = split(/:/,$submission,3);
 2142: 		    # Similarity check
 2143: 		    my $similar='';
 2144: 		    if($env{'form.checkPlag'}){
 2145: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2146: 			    &most_similar($uname,$udom,$subval,\%old_essays);
 2147: 			if ($osim) {
 2148: 			    $osim=int($osim*100.0);
 2149: 			    my %old_course_desc = 
 2150: 				&Apache::lonnet::coursedescription($ocrsid,
 2151: 								   {'one_time' => 1});
 2152: 
 2153:                             if ($hide) {
 2154:                                 $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
 2155:                                          &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
 2156:                             } else {
 2157: 			        $similar="<hr /><h3><span class=\"LC_warning\">".
 2158: 				    &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
 2159: 				        $osim,
 2160: 				        &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
 2161: 				        $old_course_desc{'description'},
 2162: 				        $old_course_desc{'num'},
 2163: 				        $old_course_desc{'domain'}).
 2164: 				    '</span></h3><blockquote><i>'.
 2165: 				    &keywords_highlight($oessay).
 2166: 				    '</i></blockquote><hr />';
 2167:                             }
 2168: 			}
 2169: 		    }
 2170: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
 2171: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
 2172: 			($env{'form.lastSub'} eq 'hdgrade' && 
 2173: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
 2174: 			my $display_part=&get_display_part($partid,$symb);
 2175:                         $lastsubonly.='<div class="LC_grade_submission_part">'.
 2176:                             '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2177:                             ' <span class="LC_internal_info">'.
 2178:                             '('.&mt('Part ID: [_1]',$respid).')'.
 2179:                             '</span>&nbsp; &nbsp;';
 2180: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2181: 			if (@$files) {
 2182:                             if ($hide) {
 2183:                                 $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
 2184:                             } else {
 2185:                                 $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
 2186:                                 foreach my $file (@$files) {
 2187:                                     &Apache::lonnet::allowuploaded('/adm/grades',$file);
 2188:                                     $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" /> '.$file.'</a>';
 2189:                                 }
 2190:                             }
 2191: 			    $lastsubonly.='<br />';
 2192: 			}
 2193:                         if ($hide) {
 2194:                             $lastsubonly.='<b>'.&mt('Anonymous Survey').'</b>'; 
 2195:                         } else {
 2196: 			    $lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
 2197: 			        &cleanRecord($subval,$responsetype,$symb,$partid,
 2198: 					     $respid,\%record,$order,undef,$uname,$udom);
 2199:                         }
 2200: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2201: 			$lastsubonly.='</div>';
 2202: 		    }
 2203: 		}
 2204: 	    }
 2205: 	    $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
 2206: 	}
 2207: 	$request->print($lastsubonly);
 2208:    } elsif ($env{'form.lastSub'} eq 'datesub') {
 2209:         my ($parts,$handgrade,$responseType) = &response_type($symb);
 2210: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2211:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2212: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2213: 								 $env{'request.course.id'},
 2214: 								 $last,'.submission',
 2215: 								 'Apache::grades::keywords_highlight'));
 2216:     }
 2217: 
 2218:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2219: 	.$udom.'" />'."\n");
 2220:     # return if view submission with no grading option
 2221: # FIXME: the logic seems off here. Why show the grade button if you cannot grade?
 2222:     if (!&canmodify($usec)) {
 2223: 	my $toGrade.='<input type="button" value="Grade Student" '.
 2224: 	    'onclick="javascript:checksubmit(this.form,\'Grade Student\',\''
 2225: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
 2226: 	$toGrade.='</div>'."\n";
 2227: 	$request->print($toGrade);
 2228: 	return;
 2229:     } else {
 2230: 	$request->print('</div>'."\n");
 2231:     }
 2232: 
 2233:     # essay grading message center
 2234:     if ($env{'form.handgrade'} eq 'yes') {
 2235: 	my $result='<div class="LC_grade_message_center">';
 2236:     
 2237: 	$result.='<div class="LC_grade_message_center_header">'.
 2238: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
 2239: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2240: 	my $msgfor = $givenn.' '.$lastname;
 2241: 	if (scalar(@$col_fullnames) > 0) {
 2242: 	    my $lastone = pop(@$col_fullnames);
 2243: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2244: 	}
 2245: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2246: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2247: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
 2248: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2249: 	    ',\''.$msgfor.'\');" target="_self">'.
 2250: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
 2251: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2252: 	    '<img src="'.$request->dir_config('lonIconsURL').
 2253: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
 2254: 	    '<br />&nbsp;('.
 2255: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
 2256: 	$result.='</div></div>';
 2257: 	$request->print($result);
 2258:     }
 2259: 
 2260:     my %seen = ();
 2261:     my @partlist;
 2262:     my @gradePartRespid;
 2263:     my @part_response_id = &flatten_responseType($responseType);
 2264:     $request->print(
 2265:         '<div class="LC_Box">'
 2266:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
 2267:     );
 2268:     $request->print(&gradeBox_start());
 2269:     foreach my $part_response_id (@part_response_id) {
 2270:     	my ($partid,$respid) = @{ $part_response_id };
 2271: 	my $part_resp = join('_',@{ $part_response_id });
 2272: 	next if ($seen{$partid} > 0);
 2273: 	$seen{$partid}++;
 2274: 	next if ($$handgrade{$part_resp} ne 'yes' 
 2275: 		 && $env{'form.lastSub'} eq 'hdgrade');
 2276: 	push(@partlist,$partid);
 2277: 	push(@gradePartRespid,$partid.'.'.$respid);
 2278: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2279:     }
 2280:     $request->print(&gradeBox_end()); # </div>
 2281:     $request->print('</div>');
 2282: 
 2283:     $request->print('<div class="LC_grade_info_links">');
 2284:     $request->print('</div>');
 2285: 
 2286:     $result='<input type="hidden" name="partlist'.$counter.
 2287: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2288:     $result.='<input type="hidden" name="gradePartRespid'.
 2289: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2290:     my $ctr = 0;
 2291:     while ($ctr < scalar(@partlist)) {
 2292: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2293: 	    $partlist[$ctr].'" />'."\n";
 2294: 	$ctr++;
 2295:     }
 2296:     $request->print($result.''."\n");
 2297: 
 2298: # Done with printing info for one student
 2299: 
 2300:     $request->print('</div>');#LC_grade_show_user
 2301: 
 2302: 
 2303:     # print end of form
 2304:     if ($counter == $total) {
 2305:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
 2306: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2307: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
 2308: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2309: 	my $ntstu ='<select name="NTSTU">'.
 2310: 	    '<option>1</option><option>2</option>'.
 2311: 	    '<option>3</option><option>5</option>'.
 2312: 	    '<option>7</option><option>10</option></select>'."\n";
 2313: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2314: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2315:         $endform.=&mt('[_1]student(s)',$ntstu);
 2316: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2317: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2318: 	    '<input type="button" value="'.&mt('Next').'" '.
 2319: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2320:         $endform.='<span class="LC_warning">'.
 2321:                   &mt('(Next and Previous (student) do not save the scores.)').
 2322:                   '</span>'."\n" ;
 2323:         $endform.="<input type='hidden' value='".&get_increment().
 2324:             "' name='increment' />";
 2325: 	$endform.='</td></tr></table></form>';
 2326: 	$request->print($endform);
 2327:     }
 2328:     return '';
 2329: }
 2330: 
 2331: sub check_collaborators {
 2332:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2333:     my ($result,@col_fullnames);
 2334:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2335:     foreach my $part (keys(%$handgrade)) {
 2336: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2337: 					'.maxcollaborators',
 2338: 					$symb,$udom,$uname);
 2339: 	next if ($ncol <= 0);
 2340: 	$part =~ s/\_/\./g;
 2341: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2342: 	my (@good_collaborators, @bad_collaborators);
 2343: 	foreach my $possible_collaborator
 2344: 	    (split(/,?\s+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2345: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2346: 	    next if ($possible_collaborator eq '');
 2347: 	    my ($co_name,$co_dom) = split(/\@|:/,$possible_collaborator);
 2348: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2349: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2350: 	    # Doing this grep allows 'fuzzy' specification
 2351: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2352: 			       keys(%$classlist));
 2353: 	    if (! scalar(@matches)) {
 2354: 		push(@bad_collaborators, $possible_collaborator);
 2355: 	    } else {
 2356: 		push(@good_collaborators, @matches);
 2357: 	    }
 2358: 	}
 2359: 	if (scalar(@good_collaborators) != 0) {
 2360: 	    $result.='<br />'.&mt('Collaborators: ');
 2361: 	    foreach my $name (@good_collaborators) {
 2362: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2363: 		push(@col_fullnames, $givenn.' '.$lastname);
 2364: 		$result.=$fullname->{$name}.'&nbsp; &nbsp; &nbsp;';
 2365: 	    }
 2366: 	    $result.='<br />'."\n";
 2367: 	    my ($part)=split(/\./,$part);
 2368: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2369: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2370: 		"\n";
 2371: 	}
 2372: 	if (scalar(@bad_collaborators) > 0) {
 2373: 	    $result.='<div class="LC_warning">';
 2374: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2375: 	    $result .= '</div>';
 2376: 	}         
 2377: 	if (scalar(@bad_collaborators > $ncol)) {
 2378: 	    $result .= '<div class="LC_warning">';
 2379: 	    $result .= &mt('This student has submitted too many '.
 2380: 		'collaborators.  Maximum is [_1].',$ncol);
 2381: 	    $result .= '</div>';
 2382: 	}
 2383:     }
 2384:     return ($result,$fullname,\@col_fullnames);
 2385: }
 2386: 
 2387: #--- Retrieve the last submission for all the parts
 2388: sub get_last_submission {
 2389:     my ($returnhash)=@_;
 2390:     my (@string,$timestamp,%lasthidden);
 2391:     if ($$returnhash{'version'}) {
 2392: 	my %lasthash=();
 2393: 	my ($version);
 2394: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2395: 	    foreach my $key (sort(split(/\:/,
 2396: 					$$returnhash{$version.':keys'}))) {
 2397: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2398: 		$timestamp = 
 2399: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2400: 	    }
 2401: 	}
 2402:         my %typeparts;
 2403:         my $showsurv = 
 2404:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
 2405:         foreach my $key (sort(keys(%lasthash))) {
 2406:             if ($key =~ /\.type$/) {
 2407:                 if (($lasthash{$key} eq 'anonsurvey') || 
 2408:                     ($lasthash{$key} eq 'anonsurveycred')) {
 2409:                     my ($ign,@parts) = split(/\./,$key);
 2410:                     pop(@parts);
 2411:                     unless ($showsurv) {
 2412:                         my $id = join(',',@parts);
 2413:                         $typeparts{$ign.'.'.$id} = $lasthash{$key};
 2414:                     }
 2415:                     delete($lasthash{$key});
 2416:                 }
 2417:             }
 2418:         }
 2419:         my @hidden = keys(%typeparts);
 2420: 	foreach my $key (keys(%lasthash)) {
 2421: 	    next if ($key !~ /\.submission$/);
 2422:             my $hide;
 2423:             if (@hidden) {
 2424:                 foreach my $id (@hidden) {
 2425:                     if ($key =~ /^\Q$id\E/) {
 2426:                         $hide = 1;
 2427:                         last;
 2428:                     }
 2429:                 }
 2430:             }
 2431: 	    my ($partid,$foo) = split(/submission$/,$key);
 2432: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
 2433: 		'<span class="LC_warning">Draft Copy</span> ' : '';
 2434: 	    push(@string, join(':', $key, $hide, $draft.$lasthash{$key}));
 2435: 	}
 2436:     }
 2437:     if (!@string) {
 2438: 	$string[0] =
 2439: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
 2440:     }
 2441:     return (\@string,\$timestamp);
 2442: }
 2443: 
 2444: #--- High light keywords, with style choosen by user.
 2445: sub keywords_highlight {
 2446:     my $string    = shift;
 2447:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2448:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2449:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2450:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2451:     foreach my $keyword (@keylist) {
 2452: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2453:     }
 2454:     return $string;
 2455: }
 2456: 
 2457: #--- Called from submission routine
 2458: sub processHandGrade {
 2459:     my ($request,$symb) = @_;
 2460:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2461:     my $button = $env{'form.gradeOpt'};
 2462:     my $ngrade = $env{'form.NCT'};
 2463:     my $ntstu  = $env{'form.NTSTU'};
 2464:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2465:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 2466: 
 2467:     if ($button eq 'Save & Next') {
 2468: 	my $ctr = 0;
 2469: 	while ($ctr < $ngrade) {
 2470: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 2471: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 2472: 	    if ($errorflag eq 'no_score') {
 2473: 		$ctr++;
 2474: 		next;
 2475: 	    }
 2476: 	    if ($errorflag eq 'not_allowed') {
 2477: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
 2478: 		$ctr++;
 2479: 		next;
 2480: 	    }
 2481: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 2482: 	    my ($subject,$message,$msgstatus) = ('','','');
 2483: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 2484:             my ($feedurl,$showsymb) =
 2485: 		&get_feedurl_and_symb($symb,$uname,$udom);
 2486: 	    my $messagetail;
 2487: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 2488: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 2489: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 2490: 		$subject.=' ['.$restitle.']';
 2491: 		my (@msgnum) = split(/,/,$includemsg);
 2492: 		foreach (@msgnum) {
 2493: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 2494: 		}
 2495: 		$message =&Apache::lonfeedback::clear_out_html($message);
 2496: 		if ($env{'form.withgrades'.$ctr}) {
 2497: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 2498: 		    $messagetail = " for <a href=\"".
 2499: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
 2500: 		}
 2501: 		$msgstatus = 
 2502:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 2503: 						     $message.$messagetail,
 2504:                                                      undef,$feedurl,undef,
 2505:                                                      undef,undef,$showsymb,
 2506:                                                      $restitle);
 2507: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
 2508: 				$msgstatus);
 2509: 	    }
 2510: 	    if ($env{'form.collaborator'.$ctr}) {
 2511: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 2512: 		foreach my $collabstr (@collabstrs) {
 2513: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 2514: 		    foreach my $collaborator (@collaborators) {
 2515: 			my ($errorflag,$pts,$wgt) = 
 2516: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 2517: 					   $env{'form.unamedom'.$ctr},$part);
 2518: 			if ($errorflag eq 'not_allowed') {
 2519: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 2520: 			    next;
 2521: 			} elsif ($message ne '') {
 2522: 			    my ($baseurl,$showsymb) = 
 2523: 				&get_feedurl_and_symb($symb,$collaborator,
 2524: 						      $udom);
 2525: 			    if ($env{'form.withgrades'.$ctr}) {
 2526: 				$messagetail = " for <a href=\"".
 2527:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
 2528: 			    }
 2529: 			    $msgstatus = 
 2530: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 2531: 			}
 2532: 		    }
 2533: 		}
 2534: 	    }
 2535: 	    $ctr++;
 2536: 	}
 2537:     }
 2538: 
 2539:     if ($env{'form.handgrade'} eq 'yes') {
 2540: 	# Keywords sorted in alphabatical order
 2541: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2542: 	my %keyhash = ();
 2543: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 2544: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 2545: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 2546: 	$env{'form.keywords'} = join(' ',@keywords);
 2547: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 2548: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 2549: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 2550: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 2551: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 2552: 
 2553: 	# message center - Order of message gets changed. Blank line is eliminated.
 2554: 	# New messages are saved in env for the next student.
 2555: 	# All messages are saved in nohist_handgrade.db
 2556: 	my ($ctr,$idx) = (1,1);
 2557: 	while ($ctr <= $env{'form.savemsgN'}) {
 2558: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 2559: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 2560: 		$idx++;
 2561: 	    }
 2562: 	    $ctr++;
 2563: 	}
 2564: 	$ctr = 0;
 2565: 	while ($ctr < $ngrade) {
 2566: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 2567: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2568: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2569: 		$idx++;
 2570: 	    }
 2571: 	    $ctr++;
 2572: 	}
 2573: 	$env{'form.savemsgN'} = --$idx;
 2574: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 2575: 	my $putresult = &Apache::lonnet::put
 2576: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 2577:     }
 2578:     # Called by Save & Refresh from Highlight Attribute Window
 2579:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 2580:     if ($env{'form.refresh'} eq 'on') {
 2581: 	my ($ctr,$total) = (0,0);
 2582: 	while ($ctr < $ngrade) {
 2583: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 2584: 	    $ctr++;
 2585: 	}
 2586: 	$env{'form.NTSTU'}=$ngrade;
 2587: 	$ctr = 0;
 2588: 	while ($ctr < $total) {
 2589: 	    my $processUser = $env{'form.unamedom'.$ctr};
 2590: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2591: 	    $env{'form.fullname'} = $$fullname{$processUser};
 2592: 	    &submission($request,$ctr,$total-1);
 2593: 	    $ctr++;
 2594: 	}
 2595: 	return '';
 2596:     }
 2597: 
 2598: # Go directly to grade student - from submission or link from chart page
 2599:     if ($button eq 'Grade Student') {
 2600: #	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
 2601: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
 2602: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2603: 	$env{'form.fullname'} = $$fullname{$processUser};
 2604: 	&submission($request,0,0);
 2605: 	return '';
 2606:     }
 2607: 
 2608:     # Get the next/previous one or group of students
 2609:     my $firststu = $env{'form.unamedom0'};
 2610:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 2611:     my $ctr = 2;
 2612:     while ($laststu eq '') {
 2613: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 2614: 	$ctr++;
 2615: 	$laststu = $firststu if ($ctr > $ngrade);
 2616:     }
 2617: 
 2618:     my (@parsedlist,@nextlist);
 2619:     my ($nextflg) = 0;
 2620:     foreach my $item (sort 
 2621: 	     {
 2622: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 2623: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 2624: 		 }
 2625: 		 return $a cmp $b;
 2626: 	     } (keys(%$fullname))) {
 2627: # FIXME: this is fishy, looks like the button label
 2628: 	if ($nextflg == 1 && $button =~ /Next$/) {
 2629: 	    push(@parsedlist,$item);
 2630: 	}
 2631: 	$nextflg = 1 if ($item eq $laststu);
 2632: 	if ($button eq 'Previous') {
 2633: 	    last if ($item eq $firststu);
 2634: 	    push(@parsedlist,$item);
 2635: 	}
 2636:     }
 2637:     $ctr = 0;
 2638: # FIXME: this is fishy, looks like the button label
 2639:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 2640:     my $res_error;
 2641:     my ($partlist) = &response_type($symb,\$res_error);
 2642:     if ($res_error) {
 2643:         $request->print(&navmap_errormsg());
 2644:         return;
 2645:     }
 2646:     foreach my $student (@parsedlist) {
 2647: 	my $submitonly=$env{'form.submitonly'};
 2648: 	my ($uname,$udom) = split(/:/,$student);
 2649: 	
 2650: 	if ($submitonly eq 'queued') {
 2651: 	    my %queue_status = 
 2652: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 2653: 							$udom,$uname);
 2654: 	    next if (!defined($queue_status{'gradingqueue'}));
 2655: 	}
 2656: 
 2657: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 2658: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2659: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 2660: 	    my $submitted = 0;
 2661: 	    my $ungraded = 0;
 2662: 	    my $incorrect = 0;
 2663: 	    foreach my $item (keys(%status)) {
 2664: 		$submitted = 1 if ($status{$item} ne 'nothing');
 2665: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 2666: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 2667: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 2668: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 2669: 		    $submitted = 0;
 2670: 		}
 2671: 	    }
 2672: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 2673: 				     $submitonly eq 'incorrect' ||
 2674: 				     $submitonly eq 'graded'));
 2675: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 2676: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 2677: 	}
 2678: 	push(@nextlist,$student) if ($ctr < $ntstu);
 2679: 	last if ($ctr == $ntstu);
 2680: 	$ctr++;
 2681:     }
 2682: 
 2683:     $ctr = 0;
 2684:     my $total = scalar(@nextlist)-1;
 2685: 
 2686:     foreach (sort(@nextlist)) {
 2687: 	my ($uname,$udom,$submitter) = split(/:/);
 2688: 	$env{'form.student'}  = $uname;
 2689: 	$env{'form.userdom'}  = $udom;
 2690: 	$env{'form.fullname'} = $$fullname{$_};
 2691: 	&submission($request,$ctr,$total);
 2692: 	$ctr++;
 2693:     }
 2694:     if ($total < 0) {
 2695: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
 2696: 	$the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
 2697: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
 2698: 	$request->print($the_end);
 2699:     }
 2700:     return '';
 2701: }
 2702: 
 2703: #---- Save the score and award for each student, if changed
 2704: sub saveHandGrade {
 2705:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 2706:     my @version_parts;
 2707:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 2708: 					   $env{'request.course.id'});
 2709:     if (!&canmodify($usec)) { return('not_allowed'); }
 2710:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 2711:     my @parts_graded;
 2712:     my %newrecord  = ();
 2713:     my ($pts,$wgt) = ('','');
 2714:     my %aggregate = ();
 2715:     my $aggregateflag = 0;
 2716:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 2717:     foreach my $new_part (@parts) {
 2718: 	#collaborator ($submi may vary for different parts
 2719: 	if ($submitter && $new_part ne $part) { next; }
 2720: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 2721: 	if ($dropMenu eq 'excused') {
 2722: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 2723: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 2724: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 2725: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 2726: 		}
 2727: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 2728: 	    }
 2729: 	} elsif ($dropMenu eq 'reset status'
 2730: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 2731: 	    foreach my $key (keys(%record)) {
 2732: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 2733: 	    }
 2734: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2735: 		"$env{'user.name'}:$env{'user.domain'}";
 2736:             my $totaltries = $record{'resource.'.$part.'.tries'};
 2737: 
 2738:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 2739: 					       [$new_part]);
 2740:             my $aggtries =$totaltries;
 2741:             if ($last_resets{$new_part}) {
 2742:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 2743: 					   $new_part);
 2744:             }
 2745: 
 2746:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 2747:             if ($aggtries > 0) {
 2748:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 2749:                 $aggregateflag = 1;
 2750:             }
 2751: 	} elsif ($dropMenu eq '') {
 2752: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 2753: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 2754: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 2755: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 2756: 		next;
 2757: 	    }
 2758: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 2759: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 2760: 	    my $partial= $pts/$wgt;
 2761: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 2762: 		#do not update score for part if not changed.
 2763:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 2764: 		next;
 2765: 	    } else {
 2766: 	        push(@parts_graded,$new_part);
 2767: 	    }
 2768: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 2769: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 2770: 	    }
 2771: 	    my $reckey = 'resource.'.$new_part.'.solved';
 2772: 	    if ($partial == 0) {
 2773: 		if ($record{$reckey} ne 'incorrect_by_override') {
 2774: 		    $newrecord{$reckey} = 'incorrect_by_override';
 2775: 		}
 2776: 	    } else {
 2777: 		if ($record{$reckey} ne 'correct_by_override') {
 2778: 		    $newrecord{$reckey} = 'correct_by_override';
 2779: 		}
 2780: 	    }	    
 2781: 	    if ($submitter && 
 2782: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 2783: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 2784: 	    }
 2785: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2786: 		"$env{'user.name'}:$env{'user.domain'}";
 2787: 	}
 2788: 	# unless problem has been graded, set flag to version the submitted files
 2789: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 2790: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 2791: 	        $dropMenu eq 'reset status')
 2792: 	   {
 2793: 	    push(@version_parts,$new_part);
 2794: 	}
 2795:     }
 2796:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2797:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2798: 
 2799:     if (%newrecord) {
 2800:         if (@version_parts) {
 2801:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 2802:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 2803: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 2804: 	    foreach my $new_part (@version_parts) {
 2805: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 2806: 				$new_part,\%newrecord);
 2807: 	    }
 2808:         }
 2809: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 2810: 				$env{'request.course.id'},$domain,$stuname);
 2811: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 2812: 				     $cdom,$cnum,$domain,$stuname);
 2813:     }
 2814:     if ($aggregateflag) {
 2815:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 2816: 			      $cdom,$cnum);
 2817:     }
 2818:     return ('',$pts,$wgt);
 2819: }
 2820: 
 2821: sub check_and_remove_from_queue {
 2822:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 2823:     my @ungraded_parts;
 2824:     foreach my $part (@{$parts}) {
 2825: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 2826: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 2827: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 2828: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 2829: 		) {
 2830: 	    push(@ungraded_parts, $part);
 2831: 	}
 2832:     }
 2833:     if ( !@ungraded_parts ) {
 2834: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 2835: 					       $cnum,$domain,$stuname);
 2836:     }
 2837: }
 2838: 
 2839: sub handback_files {
 2840:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 2841:     my $portfolio_root = '/userfiles/portfolio';
 2842:     my $res_error;
 2843:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2844:     if ($res_error) {
 2845:         $request->print('<br />'.&navmap_errormsg().'<br />');
 2846:         return;
 2847:     }
 2848:     my @part_response_id = &flatten_responseType($responseType);
 2849:     foreach my $part_response_id (@part_response_id) {
 2850:     	my ($part_id,$resp_id) = @{ $part_response_id };
 2851: 	my $part_resp = join('_',@{ $part_response_id });
 2852:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
 2853:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
 2854:                 my $file_counter = 1;
 2855: 		my $file_msg;
 2856:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
 2857:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
 2858:                     my ($directory,$answer_file) = 
 2859:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
 2860:                     my ($answer_name,$answer_ver,$answer_ext) =
 2861: 		        &file_name_version_ext($answer_file);
 2862: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 2863:                     my $getpropath = 1;
 2864: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
 2865: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 2866:                     # fix file name
 2867:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 2868:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 2869:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
 2870:             	                                $save_file_name);
 2871:                     if ($result !~ m|^/uploaded/|) {
 2872:                         $request->print('<br /><span class="LC_error">'.
 2873:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 2874:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$file_counter).
 2875:                                         '</span>');
 2876:                     } else {
 2877:                         # mark the file as read only
 2878:                         my @files = ($save_file_name);
 2879:                         my @what = ($symb,$env{'request.course.id'},'handback');
 2880:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
 2881: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 2882: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 2883: 			}
 2884:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 2885: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
 2886: 
 2887:                     }
 2888:                     $request->print("<br />".$fname." will be the uploaded file name");
 2889:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
 2890:                     $file_counter++;
 2891:                 }
 2892: 		my $subject = "File Handed Back by Instructor ";
 2893: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
 2894: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
 2895: 		$message .= ' The returned file(s) are named: '. $file_msg;
 2896: 		$message .= " and can be found in your portfolio space.";
 2897: 		my ($feedurl,$showsymb) = 
 2898: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
 2899:                 my $restitle = &Apache::lonnet::gettitle($symb);
 2900: 		my $msgstatus = 
 2901:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
 2902: 			 ' (File Returned) ['.$restitle.']',$message,undef,
 2903:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
 2904:             }
 2905:         }
 2906:     return;
 2907: }
 2908: 
 2909: sub get_feedurl_and_symb {
 2910:     my ($symb,$uname,$udom) = @_;
 2911:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2912:     $url = &Apache::lonnet::clutter($url);
 2913:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 2914: 					$symb,$udom,$uname);
 2915:     if ($encrypturl =~ /^yes$/i) {
 2916: 	&Apache::lonenc::encrypted(\$url,1);
 2917: 	&Apache::lonenc::encrypted(\$symb,1);
 2918:     }
 2919:     return ($url,$symb);
 2920: }
 2921: 
 2922: sub get_submitted_files {
 2923:     my ($udom,$uname,$partid,$respid,$record) = @_;
 2924:     my @files;
 2925:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 2926:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 2927:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 2928:     	    push(@files,$file_url.$file);
 2929:         }
 2930:     }
 2931:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 2932:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 2933:     }
 2934:     return (\@files);
 2935: }
 2936: 
 2937: # ----------- Provides number of tries since last reset.
 2938: sub get_num_tries {
 2939:     my ($record,$last_reset,$part) = @_;
 2940:     my $timestamp = '';
 2941:     my $num_tries = 0;
 2942:     if ($$record{'version'}) {
 2943:         for (my $version=$$record{'version'};$version>=1;$version--) {
 2944:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 2945:                 $timestamp = $$record{$version.':timestamp'};
 2946:                 if ($timestamp > $last_reset) {
 2947:                     $num_tries ++;
 2948:                 } else {
 2949:                     last;
 2950:                 }
 2951:             }
 2952:         }
 2953:     }
 2954:     return $num_tries;
 2955: }
 2956: 
 2957: # ----------- Determine decrements required in aggregate totals 
 2958: sub decrement_aggs {
 2959:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 2960:     my %decrement = (
 2961:                         attempts => 0,
 2962:                         users => 0,
 2963:                         correct => 0
 2964:                     );
 2965:     $decrement{'attempts'} = $aggtries;
 2966:     if ($solvedstatus =~ /^correct/) {
 2967:         $decrement{'correct'} = 1;
 2968:     }
 2969:     if ($aggtries == $totaltries) {
 2970:         $decrement{'users'} = 1;
 2971:     }
 2972:     foreach my $type (keys(%decrement)) {
 2973:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 2974:     }
 2975:     return;
 2976: }
 2977: 
 2978: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 2979: sub get_last_resets {
 2980:     my ($symb,$courseid,$partids) =@_;
 2981:     my %last_resets;
 2982:     my $cdom = $env{'course.'.$courseid.'.domain'};
 2983:     my $cname = $env{'course.'.$courseid.'.num'};
 2984:     my @keys;
 2985:     foreach my $part (@{$partids}) {
 2986: 	push(@keys,"$symb\0$part\0resettime");
 2987:     }
 2988:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 2989: 				     $cdom,$cname);
 2990:     foreach my $part (@{$partids}) {
 2991: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 2992:     }
 2993:     return %last_resets;
 2994: }
 2995: 
 2996: # ----------- Handles creating versions for portfolio files as answers
 2997: sub version_portfiles {
 2998:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 2999:     my $version_parts = join('|',@$v_flag);
 3000:     my @returned_keys;
 3001:     my $parts = join('|', @$parts_graded);
 3002:     my $portfolio_root = '/userfiles/portfolio';
 3003:     foreach my $key (keys(%$record)) {
 3004:         my $new_portfiles;
 3005:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 3006:             my @versioned_portfiles;
 3007:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 3008:             foreach my $file (@portfiles) {
 3009:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 3010:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 3011: 		my ($answer_name,$answer_ver,$answer_ext) =
 3012: 		    &file_name_version_ext($answer_file);
 3013:                 my $getpropath = 1;    
 3014:                 my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
 3015:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 3016:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
 3017:                 if ($new_answer ne 'problem getting file') {
 3018:                     push(@versioned_portfiles, $directory.$new_answer);
 3019:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
 3020:                         [$directory.$new_answer],
 3021:                         [$symb,$env{'request.course.id'},'graded']);
 3022:                 }
 3023:             }
 3024:             $$record{$key} = join(',',@versioned_portfiles);
 3025:             push(@returned_keys,$key);
 3026:         }
 3027:     } 
 3028:     return (@returned_keys);   
 3029: }
 3030: 
 3031: sub get_next_version {
 3032:     my ($answer_name, $answer_ext, $dir_list) = @_;
 3033:     my $version;
 3034:     foreach my $row (@$dir_list) {
 3035:         my ($file) = split(/\&/,$row,2);
 3036:         my ($file_name,$file_version,$file_ext) =
 3037: 	    &file_name_version_ext($file);
 3038:         if (($file_name eq $answer_name) && 
 3039: 	    ($file_ext eq $answer_ext)) {
 3040:                 # gets here if filename and extension match, regardless of version
 3041:                 if ($file_version ne '') {
 3042:                 # a versioned file is found  so save it for later
 3043:                 if ($file_version > $version) {
 3044: 		    $version = $file_version;
 3045: 	        }
 3046:             }
 3047:         }
 3048:     } 
 3049:     $version ++;
 3050:     return($version);
 3051: }
 3052: 
 3053: sub version_selected_portfile {
 3054:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 3055:     my ($answer_name,$answer_ver,$answer_ext) =
 3056:         &file_name_version_ext($file_name);
 3057:     my $new_answer;
 3058:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 3059:     if($env{'form.copy'} eq '-1') {
 3060:         $new_answer = 'problem getting file';
 3061:     } else {
 3062:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 3063:         my $copy_result = &Apache::lonnet::finishuserfileupload(
 3064:                             $stu_name,$domain,'copy',
 3065: 		        '/portfolio'.$directory.$new_answer);
 3066:     }    
 3067:     return ($new_answer);
 3068: }
 3069: 
 3070: sub file_name_version_ext {
 3071:     my ($file)=@_;
 3072:     my @file_parts = split(/\./, $file);
 3073:     my ($name,$version,$ext);
 3074:     if (@file_parts > 1) {
 3075: 	$ext=pop(@file_parts);
 3076: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 3077: 	    $version=pop(@file_parts);
 3078: 	}
 3079: 	$name=join('.',@file_parts);
 3080:     } else {
 3081: 	$name=join('.',@file_parts);
 3082:     }
 3083:     return($name,$version,$ext);
 3084: }
 3085: 
 3086: #--------------------------------------------------------------------------------------
 3087: #
 3088: #-------------------------- Next few routines handles grading by section or whole class
 3089: #
 3090: #--- Javascript to handle grading by section or whole class
 3091: sub viewgrades_js {
 3092:     my ($request) = shift;
 3093: 
 3094:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3095:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
 3096:    function writePoint(partid,weight,point) {
 3097: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3098: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3099: 	if (point == "textval") {
 3100: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3101: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3102: 		alert("$alertmsg"+parseFloat(point));
 3103: 		var resetbox = false;
 3104: 		for (var i=0; i<radioButton.length; i++) {
 3105: 		    if (radioButton[i].checked) {
 3106: 			textbox.value = i;
 3107: 			resetbox = true;
 3108: 		    }
 3109: 		}
 3110: 		if (!resetbox) {
 3111: 		    textbox.value = "";
 3112: 		}
 3113: 		return;
 3114: 	    }
 3115: 	    if (parseFloat(point) > parseFloat(weight)) {
 3116: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3117: 				   ") greater than the weight for the part. Accept?");
 3118: 		if (resp == false) {
 3119: 		    textbox.value = "";
 3120: 		    return;
 3121: 		}
 3122: 	    }
 3123: 	    for (var i=0; i<radioButton.length; i++) {
 3124: 		radioButton[i].checked=false;
 3125: 		if (parseFloat(point) == i) {
 3126: 		    radioButton[i].checked=true;
 3127: 		}
 3128: 	    }
 3129: 
 3130: 	} else {
 3131: 	    textbox.value = parseFloat(point);
 3132: 	}
 3133: 	for (i=0;i<document.classgrade.total.value;i++) {
 3134: 	    var user = document.classgrade["ctr"+i].value;
 3135: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3136: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3137: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3138: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3139: 	    if (saveval != "correct") {
 3140: 		scorename.value = point;
 3141: 		if (selname[0].selected != true) {
 3142: 		    selname[0].selected = true;
 3143: 		}
 3144: 	    }
 3145: 	}
 3146: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3147:     }
 3148: 
 3149:     function writeRadText(partid,weight) {
 3150: 	var selval   = document.classgrade["SELVAL_"+partid];
 3151: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3152:         var override = document.classgrade["FORCE_"+partid].checked;
 3153: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3154: 	if (selval[1].selected || selval[2].selected) {
 3155: 	    for (var i=0; i<radioButton.length; i++) {
 3156: 		radioButton[i].checked=false;
 3157: 
 3158: 	    }
 3159: 	    textbox.value = "";
 3160: 
 3161: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3162: 		var user = document.classgrade["ctr"+i].value;
 3163: 		user = user.replace(new RegExp(':', 'g'),"_");
 3164: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3165: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3166: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3167: 		if ((saveval != "correct") || override) {
 3168: 		    scorename.value = "";
 3169: 		    if (selval[1].selected) {
 3170: 			selname[1].selected = true;
 3171: 		    } else {
 3172: 			selname[2].selected = true;
 3173: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3174: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3175: 		    }
 3176: 		}
 3177: 	    }
 3178: 	} else {
 3179: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3180: 		var user = document.classgrade["ctr"+i].value;
 3181: 		user = user.replace(new RegExp(':', 'g'),"_");
 3182: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3183: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3184: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3185: 		if ((saveval != "correct") || override) {
 3186: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3187: 		    selname[0].selected = true;
 3188: 		}
 3189: 	    }
 3190: 	}	    
 3191:     }
 3192: 
 3193:     function changeSelect(partid,user) {
 3194: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3195: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3196: 	var point  = textbox.value;
 3197: 	var weight = document.classgrade["weight_"+partid].value;
 3198: 
 3199: 	if (isNaN(point) || parseFloat(point) < 0) {
 3200: 	    alert("$alertmsg"+parseFloat(point));
 3201: 	    textbox.value = "";
 3202: 	    return;
 3203: 	}
 3204: 	if (parseFloat(point) > parseFloat(weight)) {
 3205: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3206: 			       ") greater than the weight of the part. Accept?");
 3207: 	    if (resp == false) {
 3208: 		textbox.value = "";
 3209: 		return;
 3210: 	    }
 3211: 	}
 3212: 	selval[0].selected = true;
 3213:     }
 3214: 
 3215:     function changeOneScore(partid,user) {
 3216: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3217: 	if (selval[1].selected || selval[2].selected) {
 3218: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3219: 	    if (selval[2].selected) {
 3220: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3221: 	    }
 3222:         }
 3223:     }
 3224: 
 3225:     function resetEntry(numpart) {
 3226: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3227: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3228: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3229: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3230: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3231: 	    for (var i=0; i<radioButton.length; i++) {
 3232: 		radioButton[i].checked=false;
 3233: 
 3234: 	    }
 3235: 	    textbox.value = "";
 3236: 	    selval[0].selected = true;
 3237: 
 3238: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3239: 		var user = document.classgrade["ctr"+i].value;
 3240: 		user = user.replace(new RegExp(':', 'g'),"_");
 3241: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3242: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3243: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3244: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3245: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3246: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3247: 		if (saveselval == "excused") {
 3248: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3249: 		} else {
 3250: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3251: 		}
 3252: 	    }
 3253: 	}
 3254:     }
 3255: 
 3256: VIEWJAVASCRIPT
 3257: }
 3258: 
 3259: #--- show scores for a section or whole class w/ option to change/update a score
 3260: sub viewgrades {
 3261:     my ($request,$symb) = @_;
 3262:     &viewgrades_js($request);
 3263: 
 3264:     #need to make sure we have the correct data for later EXT calls, 
 3265:     #thus invalidate the cache
 3266:     &Apache::lonnet::devalidatecourseresdata(
 3267:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3268:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3269:     &Apache::lonnet::clear_EXT_cache_status();
 3270: 
 3271:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3272: 
 3273:     #view individual student submission form - called using Javascript viewOneStudent
 3274:     $result.=&jscriptNform($symb);
 3275: 
 3276:     #beginning of class grading form
 3277:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3278:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3279: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3280: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3281: 	&build_section_inputs().
 3282: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3283: 
 3284:     my ($common_header,$specific_header);
 3285:     if ($env{'form.section'} eq 'all') {
 3286: 	$common_header = &mt('Assign Common Grade to Class');
 3287:         $specific_header = &mt('Assign Grade to Specific Students in Class');
 3288:     } elsif ($env{'form.section'} eq 'none') {
 3289:         $common_header = &mt('Assign Common Grade to Students in no Section');
 3290: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
 3291:     } else {
 3292:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3293:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
 3294: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
 3295:     }
 3296:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
 3297:     #radio buttons/text box for assigning points for a section or class.
 3298:     #handles different parts of a problem
 3299:     my $res_error;
 3300:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3301:     if ($res_error) {
 3302:         return &navmap_errormsg();
 3303:     }
 3304:     my %weight = ();
 3305:     my $ctsparts = 0;
 3306:     my %seen = ();
 3307:     my @part_response_id = &flatten_responseType($responseType);
 3308:     foreach my $part_response_id (@part_response_id) {
 3309:     	my ($partid,$respid) = @{ $part_response_id };
 3310: 	my $part_resp = join('_',@{ $part_response_id });
 3311: 	next if $seen{$partid};
 3312: 	$seen{$partid}++;
 3313: 	my $handgrade=$$handgrade{$part_resp};
 3314: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 3315: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 3316: 
 3317: 	my $display_part=&get_display_part($partid,$symb);
 3318: 	my $radio.='<table border="0"><tr>';  
 3319: 	my $ctr = 0;
 3320: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 3321: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 3322: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 3323: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 3324: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 3325: 	    $ctr++;
 3326: 	}
 3327: 	$radio.='</tr></table>';
 3328: 	my $line = '<input type="text" name="TEXTVAL_'.
 3329: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
 3330: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 3331: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 3332: 	$line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
 3333: 	    'onchange="javascript:writeRadText(\''.$partid.'\','.
 3334: 		$weight{$partid}.')"> '.
 3335: 	    '<option selected="selected"> </option>'.
 3336: 	    '<option value="excused">'.&mt('excused').'</option>'.
 3337: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 3338: 	    '</select></td>'.
 3339:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 3340: 	$line.='<input type="hidden" name="partid_'.
 3341: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 3342: 	$line.='<input type="hidden" name="weight_'.
 3343: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 3344: 
 3345: 	$result.=
 3346: 	    &Apache::loncommon::start_data_table_row()."\n".
 3347: 	    '<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>'.
 3348: 	    &Apache::loncommon::end_data_table_row()."\n";
 3349: 	$ctsparts++;
 3350:     }
 3351:     $result.=&Apache::loncommon::end_data_table()."\n".
 3352: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 3353:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 3354: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
 3355: 
 3356:     #table listing all the students in a section/class
 3357:     #header of table
 3358:     $result.= '<h3>'.$specific_header.'</h3>'.
 3359:               &Apache::loncommon::start_data_table().
 3360: 	      &Apache::loncommon::start_data_table_header_row().
 3361: 	      '<th>'.&mt('No.').'</th>'.
 3362: 	      '<th>'.&nameUserString('header')."</th>\n";
 3363:     my $partserror;
 3364:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3365:     if ($partserror) {
 3366:         return &navmap_errormsg();
 3367:     }
 3368:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 3369:     my @partids = ();
 3370:     foreach my $part (@parts) {
 3371: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3372:         my $narrowtext = &mt('Tries');
 3373: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 3374: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 3375: 	my ($partid) = &split_part_type($part);
 3376:         push(@partids,$partid);
 3377: 	my $display_part=&get_display_part($partid,$symb);
 3378: 	if ($display =~ /^Partial Credit Factor/) {
 3379: 	    $result.='<th>'.
 3380: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
 3381: 		    $display_part,$weight{$partid}).'</th>'."\n";
 3382: 	    next;
 3383: 	    
 3384: 	} else {
 3385: 	    if ($display =~ /Problem Status/) {
 3386: 		my $grade_status_mt = &mt('Grade Status');
 3387: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 3388: 	    }
 3389: 	    my $part_mt = &mt('Part:');
 3390: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 3391: 	}
 3392: 
 3393: 	$result.='<th>'.$display.'</th>'."\n";
 3394:     }
 3395:     $result.=&Apache::loncommon::end_data_table_header_row();
 3396: 
 3397:     my %last_resets = 
 3398: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 3399: 
 3400:     #get info for each student
 3401:     #list all the students - with points and grade status
 3402:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3403:     my $ctr = 0;
 3404:     foreach (sort 
 3405: 	     {
 3406: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3407: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3408: 		 }
 3409: 		 return $a cmp $b;
 3410: 	     } (keys(%$fullname))) {
 3411: 	$ctr++;
 3412: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 3413: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
 3414:     }
 3415:     $result.=&Apache::loncommon::end_data_table();
 3416:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 3417:     $result.='<input type="button" value="'.&mt('Save').'" '.
 3418: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
 3419:     if (scalar(%$fullname) eq 0) {
 3420: 	my $colspan=3+scalar(@parts);
 3421: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3422:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 3423: 	$result='<span class="LC_warning">'.
 3424: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 3425: 	        $section_display, $stu_status).
 3426: 	    '</span>';
 3427:     }
 3428:     return $result;
 3429: }
 3430: 
 3431: #--- call by previous routine to display each student
 3432: sub viewstudentgrade {
 3433:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 3434:     my ($uname,$udom) = split(/:/,$student);
 3435:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 3436:     my %aggregates = (); 
 3437:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 3438: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
 3439: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
 3440: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 3441: 	'\');" target="_self">'.$fullname.'</a> '.
 3442: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 3443:     $student=~s/:/_/; # colon doen't work in javascript for names
 3444:     foreach my $apart (@$parts) {
 3445: 	my ($part,$type) = &split_part_type($apart);
 3446: 	my $score=$record{"resource.$part.$type"};
 3447:         $result.='<td align="center">';
 3448:         my ($aggtries,$totaltries);
 3449:         unless (exists($aggregates{$part})) {
 3450: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 3451: 
 3452: 	    $aggtries = $totaltries;
 3453:             if ($$last_resets{$part}) {  
 3454:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 3455: 					   $part);
 3456:             }
 3457:             $result.='<input type="hidden" name="'.
 3458:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 3459:             $result.='<input type="hidden" name="'.
 3460:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 3461:             $aggregates{$part} = 1;
 3462:         }
 3463: 	if ($type eq 'awarded') {
 3464: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 3465: 	    $result.='<input type="hidden" name="'.
 3466: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 3467: 	    $result.='<input type="text" name="'.
 3468: 		'GD_'.$student.'_'.$part.'_awarded" '.
 3469:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
 3470: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 3471: 	} elsif ($type eq 'solved') {
 3472: 	    my ($status,$foo)=split(/_/,$score,2);
 3473: 	    $status = 'nothing' if ($status eq '');
 3474: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 3475: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 3476: 	    $result.='&nbsp;<select name="'.
 3477: 		'GD_'.$student.'_'.$part.'_solved" '.
 3478:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 3479: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 3480: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 3481: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 3482: 	    $result.="</select>&nbsp;</td>\n";
 3483: 	} else {
 3484: 	    $result.='<input type="hidden" name="'.
 3485: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 3486: 		    "\n";
 3487: 	    $result.='<input type="text" name="'.
 3488: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 3489: 		'value="'.$score.'" size="4" /></td>'."\n";
 3490: 	}
 3491:     }
 3492:     $result.=&Apache::loncommon::end_data_table_row();
 3493:     return $result;
 3494: }
 3495: 
 3496: #--- change scores for all the students in a section/class
 3497: #    record does not get update if unchanged
 3498: sub editgrades {
 3499:     my ($request,$symb) = @_;
 3500: 
 3501:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3502:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 3503:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
 3504: 
 3505:     my $result= &Apache::loncommon::start_data_table().
 3506: 	&Apache::loncommon::start_data_table_header_row().
 3507: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 3508: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 3509:     my %scoreptr = (
 3510: 		    'correct'  =>'correct_by_override',
 3511: 		    'incorrect'=>'incorrect_by_override',
 3512: 		    'excused'  =>'excused',
 3513: 		    'ungraded' =>'ungraded_attempted',
 3514:                     'credited' =>'credit_attempted',
 3515: 		    'nothing'  => '',
 3516: 		    );
 3517:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 3518: 
 3519:     my (@partid);
 3520:     my %weight = ();
 3521:     my %columns = ();
 3522:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 3523: 
 3524:     my $partserror;
 3525:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3526:     if ($partserror) {
 3527:         return &navmap_errormsg();
 3528:     }
 3529:     my $header;
 3530:     while ($ctr < $env{'form.totalparts'}) {
 3531: 	my $partid = $env{'form.partid_'.$ctr};
 3532: 	push(@partid,$partid);
 3533: 	$weight{$partid} = $env{'form.weight_'.$partid};
 3534: 	$ctr++;
 3535:     }
 3536:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3537:     foreach my $partid (@partid) {
 3538: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 3539: 	    '<th align="center">'.&mt('New Score').'</th>';
 3540: 	$columns{$partid}=2;
 3541: 	foreach my $stores (@parts) {
 3542: 	    my ($part,$type) = &split_part_type($stores);
 3543: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 3544: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 3545: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 3546: 	    $display =~ s/\[Part: \Q$part\E\]//;
 3547:             my $narrowtext = &mt('Tries');
 3548: 	    $display =~ s/Number of Attempts/$narrowtext/;
 3549: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 3550: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 3551: 	    $columns{$partid}+=2;
 3552: 	}
 3553:     }
 3554:     foreach my $partid (@partid) {
 3555: 	my $display_part=&get_display_part($partid,$symb);
 3556: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 3557: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 3558: 	    '</th>';
 3559: 
 3560:     }
 3561:     $result .= &Apache::loncommon::end_data_table_header_row().
 3562: 	&Apache::loncommon::start_data_table_header_row().
 3563: 	$header.
 3564: 	&Apache::loncommon::end_data_table_header_row();
 3565:     my @noupdate;
 3566:     my ($updateCtr,$noupdateCtr) = (1,1);
 3567:     for ($i=0; $i<$env{'form.total'}; $i++) {
 3568: 	my $line;
 3569: 	my $user = $env{'form.ctr'.$i};
 3570: 	my ($uname,$udom)=split(/:/,$user);
 3571: 	my %newrecord;
 3572: 	my $updateflag = 0;
 3573: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 3574: 	my $usec=$classlist->{"$uname:$udom"}[5];
 3575: 	if (!&canmodify($usec)) {
 3576: 	    my $numcols=scalar(@partid)*4+2;
 3577: 	    push(@noupdate,
 3578: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
 3579: 		 &mt('Not allowed to modify student')."</span></td></tr>");
 3580: 	    next;
 3581: 	}
 3582:         my %aggregate = ();
 3583:         my $aggregateflag = 0;
 3584: 	$user=~s/:/_/; # colon doen't work in javascript for names
 3585: 	foreach (@partid) {
 3586: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 3587: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 3588: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 3589: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3590: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 3591: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 3592: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 3593: 	    my $score;
 3594: 	    if ($partial eq '') {
 3595: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3596: 	    } elsif ($partial > 0) {
 3597: 		$score = 'correct_by_override';
 3598: 	    } elsif ($partial == 0) {
 3599: 		$score = 'incorrect_by_override';
 3600: 	    }
 3601: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 3602: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 3603: 
 3604: 	    $newrecord{'resource.'.$_.'.regrader'}=
 3605: 		"$env{'user.name'}:$env{'user.domain'}";
 3606: 	    if ($dropMenu eq 'reset status' &&
 3607: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 3608: 		$newrecord{'resource.'.$_.'.tries'} = '';
 3609: 		$newrecord{'resource.'.$_.'.solved'} = '';
 3610: 		$newrecord{'resource.'.$_.'.award'} = '';
 3611: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 3612: 		$updateflag = 1;
 3613:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 3614:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 3615:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 3616:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 3617:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3618:                     $aggregateflag = 1;
 3619:                 }
 3620: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 3621: 		$updateflag = 1;
 3622: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 3623: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 3624: 		$rec_update++;
 3625: 	    }
 3626: 
 3627: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3628: 		'<td align="center">'.$awarded.
 3629: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 3630: 
 3631: 
 3632: 	    my $partid=$_;
 3633: 	    foreach my $stores (@parts) {
 3634: 		my ($part,$type) = &split_part_type($stores);
 3635: 		if ($part !~ m/^\Q$partid\E/) { next;}
 3636: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 3637: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 3638: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 3639: 		if ($awarded ne '' && $awarded ne $old_aw) {
 3640: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 3641: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3642: 		    $updateflag=1;
 3643: 		}
 3644: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3645: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 3646: 	    }
 3647: 	}
 3648: 	$line.="\n";
 3649: 
 3650: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3651: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3652: 
 3653: 	if ($updateflag) {
 3654: 	    $count++;
 3655: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 3656: 				    $udom,$uname);
 3657: 
 3658: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 3659: 					      $cnum,$udom,$uname)) {
 3660: 		# need to figure out if should be in queue.
 3661: 		my %record =  
 3662: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 3663: 					     $udom,$uname);
 3664: 		my $all_graded = 1;
 3665: 		my $none_graded = 1;
 3666: 		foreach my $part (@parts) {
 3667: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 3668: 			$all_graded = 0;
 3669: 		    } else {
 3670: 			$none_graded = 0;
 3671: 		    }
 3672: 		}
 3673: 
 3674: 		if ($all_graded || $none_graded) {
 3675: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 3676: 							   $symb,$cdom,$cnum,
 3677: 							   $udom,$uname);
 3678: 		}
 3679: 	    }
 3680: 
 3681: 	    $result.=&Apache::loncommon::start_data_table_row().
 3682: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 3683: 		&Apache::loncommon::end_data_table_row();
 3684: 	    $updateCtr++;
 3685: 	} else {
 3686: 	    push(@noupdate,
 3687: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 3688: 	    $noupdateCtr++;
 3689: 	}
 3690:         if ($aggregateflag) {
 3691:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3692: 				  $cdom,$cnum);
 3693:         }
 3694:     }
 3695:     if (@noupdate) {
 3696: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
 3697: 	my $numcols=scalar(@partid)*4+2;
 3698: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 3699: 	    '<td align="center" colspan="'.$numcols.'">'.
 3700: 	    &mt('No Changes Occurred For the Students Below').
 3701: 	    '</td>'.
 3702: 	    &Apache::loncommon::end_data_table_row();
 3703: 	foreach my $line (@noupdate) {
 3704: 	    $result.=
 3705: 		&Apache::loncommon::start_data_table_row().
 3706: 		$line.
 3707: 		&Apache::loncommon::end_data_table_row();
 3708: 	}
 3709:     }
 3710:     $result .= &Apache::loncommon::end_data_table();
 3711:     my $msg = '<p><b>'.
 3712: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 3713: 	    $rec_update,$count).'</b><br />'.
 3714: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 3715: 	'</b></p>';
 3716:     return $title.$msg.$result;
 3717: }
 3718: 
 3719: sub split_part_type {
 3720:     my ($partstr) = @_;
 3721:     my ($temp,@allparts)=split(/_/,$partstr);
 3722:     my $type=pop(@allparts);
 3723:     my $part=join('_',@allparts);
 3724:     return ($part,$type);
 3725: }
 3726: 
 3727: #------------- end of section for handling grading by section/class ---------
 3728: #
 3729: #----------------------------------------------------------------------------
 3730: 
 3731: 
 3732: #----------------------------------------------------------------------------
 3733: #
 3734: #-------------------------- Next few routines handles grading by csv upload
 3735: #
 3736: #--- Javascript to handle csv upload
 3737: sub csvupload_javascript_reverse_associate {
 3738:     my $error1=&mt('You need to specify the username or the student/employee ID');
 3739:     my $error2=&mt('You need to specify at least one grading field');
 3740:   return(<<ENDPICK);
 3741:   function verify(vf) {
 3742:     var foundsomething=0;
 3743:     var founduname=0;
 3744:     var foundID=0;
 3745:     for (i=0;i<=vf.nfields.value;i++) {
 3746:       tw=eval('vf.f'+i+'.selectedIndex');
 3747:       if (i==0 && tw!=0) { foundID=1; }
 3748:       if (i==1 && tw!=0) { founduname=1; }
 3749:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 3750:     }
 3751:     if (founduname==0 && foundID==0) {
 3752: 	alert('$error1');
 3753: 	return;
 3754:     }
 3755:     if (foundsomething==0) {
 3756: 	alert('$error2');
 3757: 	return;
 3758:     }
 3759:     vf.submit();
 3760:   }
 3761:   function flip(vf,tf) {
 3762:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3763:     var i;
 3764:     for (i=0;i<=vf.nfields.value;i++) {
 3765:       //can not pick the same destination field for both name and domain
 3766:       if (((i ==0)||(i ==1)) && 
 3767:           ((tf==0)||(tf==1)) && 
 3768:           (i!=tf) &&
 3769:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3770:         eval('vf.f'+i+'.selectedIndex=0;')
 3771:       }
 3772:     }
 3773:   }
 3774: ENDPICK
 3775: }
 3776: 
 3777: sub csvupload_javascript_forward_associate {
 3778:     my $error1=&mt('You need to specify the username or the student/employee ID');
 3779:     my $error2=&mt('You need to specify at least one grading field');
 3780:   return(<<ENDPICK);
 3781:   function verify(vf) {
 3782:     var foundsomething=0;
 3783:     var founduname=0;
 3784:     var foundID=0;
 3785:     for (i=0;i<=vf.nfields.value;i++) {
 3786:       tw=eval('vf.f'+i+'.selectedIndex');
 3787:       if (tw==1) { foundID=1; }
 3788:       if (tw==2) { founduname=1; }
 3789:       if (tw>3) { foundsomething=1; }
 3790:     }
 3791:     if (founduname==0 && foundID==0) {
 3792: 	alert('$error1');
 3793: 	return;
 3794:     }
 3795:     if (foundsomething==0) {
 3796: 	alert('$error2');
 3797: 	return;
 3798:     }
 3799:     vf.submit();
 3800:   }
 3801:   function flip(vf,tf) {
 3802:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3803:     var i;
 3804:     //can not pick the same destination field twice
 3805:     for (i=0;i<=vf.nfields.value;i++) {
 3806:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3807:         eval('vf.f'+i+'.selectedIndex=0;')
 3808:       }
 3809:     }
 3810:   }
 3811: ENDPICK
 3812: }
 3813: 
 3814: sub csvuploadmap_header {
 3815:     my ($request,$symb,$datatoken,$distotal)= @_;
 3816:     my $javascript;
 3817:     if ($env{'form.upfile_associate'} eq 'reverse') {
 3818: 	$javascript=&csvupload_javascript_reverse_associate();
 3819:     } else {
 3820: 	$javascript=&csvupload_javascript_forward_associate();
 3821:     }
 3822: 
 3823:     my $result='';
 3824:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
 3825:     my $ignore=&mt('Ignore First Line');
 3826:     $symb = &Apache::lonenc::check_encrypt($symb);
 3827:     $request->print(<<ENDPICK);
 3828: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3829: <h3><span class="LC_info">Uploading Class Grades</span></h3>
 3830: $result
 3831: <hr />
 3832: <h3>Identify fields</h3>
 3833: Total number of records found in file: $distotal <hr />
 3834: Enter as many fields as you can. The system will inform you and bring you back
 3835: to this page if the data selected is insufficient to run your class.<hr />
 3836: <input type="button" value="Reverse Association" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 3837: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
 3838: <input type="hidden" name="associate"  value="" />
 3839: <input type="hidden" name="phase"      value="three" />
 3840: <input type="hidden" name="datatoken"  value="$datatoken" />
 3841: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 3842: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 3843: <input type="hidden" name="upfile_associate" 
 3844:                                        value="$env{'form.upfile_associate'}" />
 3845: <input type="hidden" name="symb"       value="$symb" />
 3846: <input type="hidden" name="command"    value="csvuploadoptions" />
 3847: <hr />
 3848: ENDPICK
 3849:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
 3850:     return '';
 3851: 
 3852: }
 3853: 
 3854: sub csvupload_fields {
 3855:     my ($symb,$errorref) = @_;
 3856:     my (@parts) = &getpartlist($symb,$errorref);
 3857:     if (ref($errorref)) {
 3858:         if ($$errorref) {
 3859:             return;
 3860:         }
 3861:     }
 3862: 
 3863:     my @fields=(['ID','Student/Employee ID'],
 3864: 		['username','Student Username'],
 3865: 		['domain','Student Domain']);
 3866:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3867:     foreach my $part (sort(@parts)) {
 3868: 	my @datum;
 3869: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3870: 	my $name=$part;
 3871: 	if  (!$display) { $display = $name; }
 3872: 	@datum=($name,$display);
 3873: 	if ($name=~/^stores_(.*)_awarded/) {
 3874: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 3875: 	}
 3876: 	push(@fields,\@datum);
 3877:     }
 3878:     return (@fields);
 3879: }
 3880: 
 3881: sub csvuploadmap_footer {
 3882:     my ($request,$i,$keyfields) =@_;
 3883:     $request->print(<<ENDPICK);
 3884: </table>
 3885: <input type="hidden" name="nfields" value="$i" />
 3886: <input type="hidden" name="keyfields" value="$keyfields" />
 3887: <input type="button" onclick="javascript:verify(this.form)" value="Assign Grades" /><br />
 3888: </form>
 3889: ENDPICK
 3890: }
 3891: 
 3892: sub checkforfile_js {
 3893:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 3894:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
 3895:     function checkUpload(formname) {
 3896: 	if (formname.upfile.value == "") {
 3897: 	    alert("$alertmsg");
 3898: 	    return false;
 3899: 	}
 3900: 	formname.submit();
 3901:     }
 3902: CSVFORMJS
 3903:     return $result;
 3904: }
 3905: 
 3906: sub upcsvScores_form {
 3907:     my ($request,$symb) = @_;
 3908:     if (!$symb) {return '';}
 3909:     my $result=&checkforfile_js();
 3910:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 3911:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 3912:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource.').
 3913: 	'</b></td></tr>'."\n";
 3914:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
 3915:     my $upload=&mt("Upload Scores");
 3916:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 3917:     my $ignore=&mt('Ignore First Line');
 3918:     $symb = &Apache::lonenc::check_encrypt($symb);
 3919:     $result.=<<ENDUPFORM;
 3920: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3921: <input type="hidden" name="symb" value="$symb" />
 3922: <input type="hidden" name="command" value="csvuploadmap" />
 3923: $upfile_select
 3924: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 3925: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
 3926: </form>
 3927: ENDUPFORM
 3928:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 3929:                            &mt("How do I create a CSV file from a spreadsheet"))
 3930:     .'</td></tr></table>'."\n";
 3931:     $result.='</td></tr></table><br /><br />'."\n";
 3932:     return $result;
 3933: }
 3934: 
 3935: 
 3936: sub csvuploadmap {
 3937:     my ($request,$symb)= @_;
 3938:     if (!$symb) {return '';}
 3939: 
 3940:     my $datatoken;
 3941:     if (!$env{'form.datatoken'}) {
 3942: 	$datatoken=&Apache::loncommon::upfile_store($request);
 3943:     } else {
 3944: 	$datatoken=$env{'form.datatoken'};
 3945: 	&Apache::loncommon::load_tmp_file($request);
 3946:     }
 3947:     my @records=&Apache::loncommon::upfile_record_sep();
 3948:     if ($env{'form.noFirstLine'}) { shift(@records); }
 3949:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 3950:     my ($i,$keyfields);
 3951:     if (@records) {
 3952:         my $fieldserror;
 3953: 	my @fields=&csvupload_fields($symb,\$fieldserror);
 3954:         if ($fieldserror) {
 3955:             $request->print(&navmap_errormsg());
 3956:             return;
 3957:         }
 3958: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 3959: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 3960: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 3961: 							  \@fields);
 3962: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 3963: 	    chop($keyfields);
 3964: 	} else {
 3965: 	    unshift(@fields,['none','']);
 3966: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 3967: 							    \@fields);
 3968:             foreach my $rec (@records) {
 3969:                 my %temp = &Apache::loncommon::record_sep($rec);
 3970:                 if (%temp) {
 3971:                     $keyfields=join(',',sort(keys(%temp)));
 3972:                     last;
 3973:                 }
 3974:             }
 3975: 	}
 3976:     }
 3977:     &csvuploadmap_footer($request,$i,$keyfields);
 3978: 
 3979:     return '';
 3980: }
 3981: 
 3982: sub csvuploadoptions {
 3983:     my ($request,$symb)= @_;
 3984:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
 3985:     my $ignore=&mt('Ignore First Line');
 3986:     $request->print(<<ENDPICK);
 3987: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3988: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
 3989: <input type="hidden" name="command"    value="csvuploadassign" />
 3990: <!--
 3991: <p>
 3992: <label>
 3993:    <input type="checkbox" name="show_full_results" />
 3994:    Show a table of all changes
 3995: </label>
 3996: </p>
 3997: -->
 3998: <p>
 3999: <label>
 4000:    <input type="checkbox" name="overwite_scores" checked="checked" />
 4001:    Overwrite any existing score
 4002: </label>
 4003: </p>
 4004: ENDPICK
 4005:     my %fields=&get_fields();
 4006:     if (!defined($fields{'domain'})) {
 4007: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 4008: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
 4009:     }
 4010:     foreach my $key (sort(keys(%env))) {
 4011: 	if ($key !~ /^form\.(.*)$/) { next; }
 4012: 	my $cleankey=$1;
 4013: 	if ($cleankey eq 'command') { next; }
 4014: 	$request->print('<input type="hidden" name="'.$cleankey.
 4015: 			'"  value="'.$env{$key}.'" />'."\n");
 4016:     }
 4017:     # FIXME do a check for any duplicated user ids...
 4018:     # FIXME do a check for any invalid user ids?...
 4019:     $request->print('<input type="submit" value="Assign Grades" /><br />
 4020: <hr /></form>'."\n");
 4021:     return '';
 4022: }
 4023: 
 4024: sub get_fields {
 4025:     my %fields;
 4026:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 4027:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 4028: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 4029: 	    if ($env{'form.f'.$i} ne 'none') {
 4030: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 4031: 	    }
 4032: 	} else {
 4033: 	    if ($env{'form.f'.$i} ne 'none') {
 4034: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 4035: 	    }
 4036: 	}
 4037:     }
 4038:     return %fields;
 4039: }
 4040: 
 4041: sub csvuploadassign {
 4042:     my ($request,$symb)= @_;
 4043:     if (!$symb) {return '';}
 4044:     my $error_msg = '';
 4045:     &Apache::loncommon::load_tmp_file($request);
 4046:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 4047:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
 4048:     my %fields=&get_fields();
 4049:     $request->print('<h3>Assigning Grades</h3>');
 4050:     my $courseid=$env{'request.course.id'};
 4051:     my ($classlist) = &getclasslist('all',0);
 4052:     my @notallowed;
 4053:     my @skipped;
 4054:     my $countdone=0;
 4055:     foreach my $grade (@gradedata) {
 4056: 	my %entries=&Apache::loncommon::record_sep($grade);
 4057: 	my $domain;
 4058: 	if ($entries{$fields{'domain'}}) {
 4059: 	    $domain=$entries{$fields{'domain'}};
 4060: 	} else {
 4061: 	    $domain=$env{'form.default_domain'};
 4062: 	}
 4063: 	$domain=~s/\s//g;
 4064: 	my $username=$entries{$fields{'username'}};
 4065: 	$username=~s/\s//g;
 4066: 	if (!$username) {
 4067: 	    my $id=$entries{$fields{'ID'}};
 4068: 	    $id=~s/\s//g;
 4069: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 4070: 	    $username=$ids{$id};
 4071: 	}
 4072: 	if (!exists($$classlist{"$username:$domain"})) {
 4073: 	    my $id=$entries{$fields{'ID'}};
 4074: 	    $id=~s/\s//g;
 4075: 	    if ($id) {
 4076: 		push(@skipped,"$id:$domain");
 4077: 	    } else {
 4078: 		push(@skipped,"$username:$domain");
 4079: 	    }
 4080: 	    next;
 4081: 	}
 4082: 	my $usec=$classlist->{"$username:$domain"}[5];
 4083: 	if (!&canmodify($usec)) {
 4084: 	    push(@notallowed,"$username:$domain");
 4085: 	    next;
 4086: 	}
 4087: 	my %points;
 4088: 	my %grades;
 4089: 	foreach my $dest (keys(%fields)) {
 4090: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 4091: 		$dest eq 'domain') { next; }
 4092: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 4093: 	    if ($dest=~/stores_(.*)_points/) {
 4094: 		my $part=$1;
 4095: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 4096: 					      $symb,$domain,$username);
 4097:                 if ($wgt) {
 4098:                     $entries{$fields{$dest}}=~s/\s//g;
 4099:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 4100:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 4101:                                           : 'correct_by_override';
 4102:                     $grades{"resource.$part.awarded"}=$pcr;
 4103:                     $grades{"resource.$part.solved"}=$award;
 4104:                     $points{$part}=1;
 4105:                 } else {
 4106:                     $error_msg = "<br />" .
 4107:                         &mt("Some point values were assigned"
 4108:                             ." for problems with a weight "
 4109:                             ."of zero. These values were "
 4110:                             ."ignored.");
 4111:                 }
 4112: 	    } else {
 4113: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 4114: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 4115: 		my $store_key=$dest;
 4116: 		$store_key=~s/^stores/resource/;
 4117: 		$store_key=~s/_/\./g;
 4118: 		$grades{$store_key}=$entries{$fields{$dest}};
 4119: 	    }
 4120: 	}
 4121: 	if (! %grades) { 
 4122:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 4123:         } else {
 4124: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 4125: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 4126: 					   $env{'request.course.id'},
 4127: 					   $domain,$username);
 4128: 	   if ($result eq 'ok') {
 4129: 	      $request->print('.');
 4130: 	   } else {
 4131: 	      $request->print("<p><span class=\"LC_error\">".
 4132:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 4133:                                   "$username:$domain",$result)."</span></p>");
 4134: 	   }
 4135: 	   $request->rflush();
 4136: 	   $countdone++;
 4137:         }
 4138:     }
 4139:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
 4140:     if (@skipped) {
 4141: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
 4142:         $request->print(join(', ',@skipped));
 4143:     }
 4144:     if (@notallowed) {
 4145: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
 4146: 	$request->print(join(', ',@notallowed));
 4147:     }
 4148:     $request->print("<br />\n");
 4149:     return $error_msg;
 4150: }
 4151: #------------- end of section for handling csv file upload ---------
 4152: #
 4153: #-------------------------------------------------------------------
 4154: #
 4155: #-------------- Next few routines handle grading by page/sequence
 4156: #
 4157: #--- Select a page/sequence and a student to grade
 4158: sub pickStudentPage {
 4159:     my ($request,$symb) = @_;
 4160: 
 4161:     my $alertmsg = &mt('Please select the student you wish to grade.');
 4162:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
 4163: 
 4164: function checkPickOne(formname) {
 4165:     if (radioSelection(formname.student) == null) {
 4166: 	alert("$alertmsg");
 4167: 	return;
 4168:     }
 4169:     ptr = pullDownSelection(formname.selectpage);
 4170:     formname.page.value = formname["page"+ptr].value;
 4171:     formname.title.value = formname["title"+ptr].value;
 4172:     formname.submit();
 4173: }
 4174: 
 4175: LISTJAVASCRIPT
 4176:     &commonJSfunctions($request);
 4177: 
 4178:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4179:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4180:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4181: 
 4182:     my $result='<h3><span class="LC_info">&nbsp;'.
 4183: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 4184: 
 4185:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 4186:     my $map_error;
 4187:     my ($titles,$symbx) = &getSymbMap($map_error);
 4188:     if ($map_error) {
 4189:         $request->print(&navmap_errormsg());
 4190:         return; 
 4191:     }
 4192:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 4193: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 4194: #    my $type=($curpage =~ /\.(page|sequence)/);
 4195:     my $select = '<select name="selectpage">'."\n";
 4196:     my $ctr=0;
 4197:     foreach (@$titles) {
 4198: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4199: 	$select.='<option value="'.$ctr.'" '.
 4200: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4201: 	    '>'.$showtitle.'</option>'."\n";
 4202: 	$ctr++;
 4203:     }
 4204:     $select.= '</select>';
 4205:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
 4206: 
 4207:     $ctr=0;
 4208:     foreach (@$titles) {
 4209: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4210: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 4211: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 4212: 	$ctr++;
 4213:     }
 4214:     $result.='<input type="hidden" name="page" />'."\n".
 4215: 	'<input type="hidden" name="title" />'."\n";
 4216: 
 4217:     my $options =
 4218: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
 4219: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
 4220:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
 4221: 
 4222:     $options =
 4223: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
 4224: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
 4225: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
 4226:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
 4227:     
 4228:     $result.=&build_section_inputs();
 4229:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4230:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 4231: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 4232: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."<br />\n";
 4233: 
 4234:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
 4235: 
 4236:     $result.='&nbsp;<input type="button" '.
 4237:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 4238: 
 4239:     $request->print($result);
 4240: 
 4241:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 4242: 	&Apache::loncommon::start_data_table().
 4243: 	&Apache::loncommon::start_data_table_header_row().
 4244: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4245: 	'<th>'.&nameUserString('header').'</th>'.
 4246: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4247: 	'<th>'.&nameUserString('header').'</th>'.
 4248: 	&Apache::loncommon::end_data_table_header_row();
 4249:  
 4250:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 4251:     my $ptr = 1;
 4252:     foreach my $student (sort 
 4253: 			 {
 4254: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4255: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4256: 			     }
 4257: 			     return $a cmp $b;
 4258: 			 } (keys(%$fullname))) {
 4259: 	my ($uname,$udom) = split(/:/,$student);
 4260: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 4261:                                   : '</td>');
 4262: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 4263: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 4264: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 4265: 	$studentTable.=
 4266: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 4267:                          : '');
 4268: 	$ptr++;
 4269:     }
 4270:     if ($ptr%2 == 0) {
 4271: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 4272: 	    &Apache::loncommon::end_data_table_row();
 4273:     }
 4274:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 4275:     $studentTable.='<input type="button" '.
 4276:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 4277: 
 4278:     $request->print($studentTable);
 4279: 
 4280:     return '';
 4281: }
 4282: 
 4283: sub getSymbMap {
 4284:     my ($map_error) = @_;
 4285:     my $navmap = Apache::lonnavmaps::navmap->new();
 4286:     unless (ref($navmap)) {
 4287:         if (ref($map_error)) {
 4288:             $$map_error = 'navmap';
 4289:         }
 4290:         return;
 4291:     }
 4292:     my %symbx = ();
 4293:     my @titles = ();
 4294:     my $minder = 0;
 4295: 
 4296:     # Gather every sequence that has problems.
 4297:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 4298: 					       1,0,1);
 4299:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 4300: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 4301: 	    my $title = $minder.'.'.
 4302: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 4303: 	    push(@titles, $title); # minder in case two titles are identical
 4304: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 4305: 	    $minder++;
 4306: 	}
 4307:     }
 4308:     return \@titles,\%symbx;
 4309: }
 4310: 
 4311: #
 4312: #--- Displays a page/sequence w/wo problems, w/wo submissions
 4313: sub displayPage {
 4314:     my ($request,$symb) = @_;
 4315:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4316:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4317:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4318:     my $pageTitle = $env{'form.page'};
 4319:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4320:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4321:     my $usec=$classlist->{$env{'form.student'}}[5];
 4322: 
 4323:     #need to make sure we have the correct data for later EXT calls, 
 4324:     #thus invalidate the cache
 4325:     &Apache::lonnet::devalidatecourseresdata(
 4326:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 4327:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 4328:     &Apache::lonnet::clear_EXT_cache_status();
 4329: 
 4330:     if (!&canview($usec)) {
 4331: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
 4332: 	return;
 4333:     }
 4334:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4335:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 4336: 	'</h3>'."\n";
 4337:     $env{'form.CODE'} = uc($env{'form.CODE'});
 4338:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 4339: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 4340:     } else {
 4341: 	delete($env{'form.CODE'});
 4342:     }
 4343:     &sub_page_js($request);
 4344:     $request->print($result);
 4345: 
 4346:     my $navmap = Apache::lonnavmaps::navmap->new();
 4347:     unless (ref($navmap)) {
 4348:         $request->print(&navmap_errormsg());
 4349:         return;
 4350:     }
 4351:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 4352:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4353:     if (!$map) {
 4354: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 4355: 	return; 
 4356:     }
 4357:     my $iterator = $navmap->getIterator($map->map_start(),
 4358: 					$map->map_finish());
 4359: 
 4360:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 4361: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 4362: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 4363: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 4364: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 4365: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 4366: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4367: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
 4368: 
 4369:     if (defined($env{'form.CODE'})) {
 4370: 	$studentTable.=
 4371: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 4372:     }
 4373:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 4374: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 4375: 
 4376:     $studentTable.='&nbsp;<span class="LC_info">'.
 4377:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
 4378:         '</span>'."\n".
 4379: 	&Apache::loncommon::start_data_table().
 4380: 	&Apache::loncommon::start_data_table_header_row().
 4381: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
 4382: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 4383: 	&Apache::loncommon::end_data_table_header_row();
 4384: 
 4385:     &Apache::lonxml::clear_problem_counter();
 4386:     my ($depth,$question,$prob) = (1,1,1);
 4387:     $iterator->next(); # skip the first BEGIN_MAP
 4388:     my $curRes = $iterator->next(); # for "current resource"
 4389:     while ($depth > 0) {
 4390:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4391:         if($curRes == $iterator->END_MAP) { $depth--; }
 4392: 
 4393:         if (ref($curRes) && $curRes->is_problem()) {
 4394: 	    my $parts = $curRes->parts();
 4395:             my $title = $curRes->compTitle();
 4396: 	    my $symbx = $curRes->symb();
 4397: 	    $studentTable.=
 4398: 		&Apache::loncommon::start_data_table_row().
 4399: 		'<td align="center" valign="top" >'.$prob.
 4400: 		(scalar(@{$parts}) == 1 ? '' 
 4401: 		                        : '<br />('.&mt('[_1]&nbsp;parts)',
 4402: 							scalar(@{$parts}))
 4403: 		 ).
 4404: 		 '</td>';
 4405: 	    $studentTable.='<td valign="top">';
 4406: 	    my %form = ('CODE' => $env{'form.CODE'},);
 4407: 	    if ($env{'form.vProb'} eq 'yes' ) {
 4408: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 4409: 					     undef,'both',\%form);
 4410: 	    } else {
 4411: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 4412: 		$companswer =~ s|<form(.*?)>||g;
 4413: 		$companswer =~ s|</form>||g;
 4414: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 4415: #		    $companswer =~ s/$1/ /ms;
 4416: #		    $request->print('match='.$1."<br />\n");
 4417: #		}
 4418: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 4419: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 4420: 	    }
 4421: 
 4422: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 4423: 
 4424: 	    if ($env{'form.lastSub'} eq 'datesub') {
 4425: 		if ($record{'version'} eq '') {
 4426: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
 4427: 		} else {
 4428: 		    my %responseType = ();
 4429: 		    foreach my $partid (@{$parts}) {
 4430: 			my @responseIds =$curRes->responseIds($partid);
 4431: 			my @responseType =$curRes->responseType($partid);
 4432: 			my %responseIds;
 4433: 			for (my $i=0;$i<=$#responseIds;$i++) {
 4434: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 4435: 			}
 4436: 			$responseType{$partid} = \%responseIds;
 4437: 		    }
 4438: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 4439: 
 4440: 		}
 4441: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 4442: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 4443: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 4444: 									$env{'request.course.id'},
 4445: 									'','.submission');
 4446:  
 4447: 	    }
 4448: 	    if (&canmodify($usec)) {
 4449:             $studentTable.=&gradeBox_start();
 4450: 		foreach my $partid (@{$parts}) {
 4451: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 4452: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 4453: 		    $question++;
 4454: 		}
 4455:             $studentTable.=&gradeBox_end();
 4456: 		$prob++;
 4457: 	    }
 4458: 	    $studentTable.='</td></tr>';
 4459: 
 4460: 	}
 4461:         $curRes = $iterator->next();
 4462:     }
 4463: 
 4464:     $studentTable.=
 4465:         '</table>'."\n".
 4466:         '<input type="button" value="'.&mt('Save').'" '.
 4467:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 4468:         '</form>'."\n";
 4469:     $request->print($studentTable);
 4470: 
 4471:     return '';
 4472: }
 4473: 
 4474: sub displaySubByDates {
 4475:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 4476:     my $isCODE=0;
 4477:     my $isTask = ($symb =~/\.task$/);
 4478:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 4479:     my $studentTable=&Apache::loncommon::start_data_table().
 4480: 	&Apache::loncommon::start_data_table_header_row().
 4481: 	'<th>'.&mt('Date/Time').'</th>'.
 4482: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 4483: 	'<th>'.&mt('Submission').'</th>'.
 4484: 	'<th>'.&mt('Status').'</th>'.
 4485: 	&Apache::loncommon::end_data_table_header_row();
 4486:     my ($version);
 4487:     my %mark;
 4488:     my %orders;
 4489:     $mark{'correct_by_student'} = $checkIcon;
 4490:     if (!exists($$record{'1:timestamp'})) {
 4491: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 4492:     }
 4493: 
 4494:     my $interaction;
 4495:     my $no_increment = 1;
 4496:     for ($version=1;$version<=$$record{'version'};$version++) {
 4497: 	my $timestamp = 
 4498: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 4499: 	if (exists($$record{$version.':resource.0.version'})) {
 4500: 	    $interaction = $$record{$version.':resource.0.version'};
 4501: 	}
 4502: 
 4503: 	my $where = ($isTask ? "$version:resource.$interaction"
 4504: 		             : "$version:resource");
 4505: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 4506: 	    '<td>'.$timestamp.'</td>';
 4507: 	if ($isCODE) {
 4508: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 4509: 	}
 4510: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 4511: 	my @displaySub = ();
 4512: 	foreach my $partid (@{$parts}) {
 4513:             my $hidden;
 4514:             if (($$record{$version.':resource.'.$partid.'.type'} eq 'anonsurvey') ||
 4515:                 ($$record{$version.':resource.'.$partid.'.type'} eq 'anonsurveycred')) {
 4516:                 $hidden = 1;
 4517:             }
 4518: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
 4519: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 4520: 	    
 4521: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 4522: 	    my $display_part=&get_display_part($partid,$symb);
 4523: 	    foreach my $matchKey (@matchKey) {
 4524: 		if (exists($$record{$version.':'.$matchKey}) &&
 4525: 		    $$record{$version.':'.$matchKey} ne '') {
 4526:                     
 4527: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 4528: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 4529:                     $displaySub[0].='<span class="LC_nobreak"';
 4530:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
 4531:                                    .' <span class="LC_internal_info">'
 4532:                                    .'('.&mt('Part ID: [_1]',$responseId).')'
 4533:                                    .'</span>'
 4534:                                    .' <b>';
 4535:                     if ($hidden) {
 4536:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
 4537:                     } else {
 4538: 		        if ($$record{"$where.$partid.tries"} eq '') {
 4539: 			    $displaySub[0].=&mt('Trial not counted');
 4540: 		        } else {
 4541: 			    $displaySub[0].=&mt('Trial: [_1]',
 4542: 					    $$record{"$where.$partid.tries"});
 4543: 		        }
 4544: 		        my $responseType=($isTask ? 'Task'
 4545:                                               : $responseType->{$partid}->{$responseId});
 4546: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
 4547: 		        if (!exists($orders{$partid}->{$responseId})) {
 4548: 			    $orders{$partid}->{$responseId}=
 4549: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
 4550:                                            $no_increment);
 4551: 		        }
 4552: 		        $displaySub[0].='</b></span>'; # /nobreak
 4553: 		        $displaySub[0].='&nbsp; '.
 4554: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
 4555:                     }
 4556: 		}
 4557: 	    }
 4558: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 4559: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 4560: 				    $$record{"$where.$partid.checkedin"},
 4561: 				    $$record{"$where.$partid.checkedin.slot"}).
 4562: 					'<br />';
 4563: 	    }
 4564: 	    if (exists $$record{"$where.$partid.award"}) {
 4565: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 4566: 		    lc($$record{"$where.$partid.award"}).' '.
 4567: 		    $mark{$$record{"$where.$partid.solved"}}.
 4568: 		    '<br />';
 4569: 	    }
 4570: 	    if (exists $$record{"$where.$partid.regrader"}) {
 4571: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 4572: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4573: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 4574: 		$displaySub[2].=
 4575: 		    $$record{"$version:resource.$partid.regrader"}.
 4576: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4577: 	    }
 4578: 	}
 4579: 	# needed because old essay regrader has not parts info
 4580: 	if (exists $$record{"$version:resource.regrader"}) {
 4581: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 4582: 	}
 4583: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 4584: 	if ($displaySub[2]) {
 4585: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 4586: 	}
 4587: 	$studentTable.='&nbsp;</td>'.
 4588: 	    &Apache::loncommon::end_data_table_row();
 4589:     }
 4590:     $studentTable.=&Apache::loncommon::end_data_table();
 4591:     return $studentTable;
 4592: }
 4593: 
 4594: sub updateGradeByPage {
 4595:     my ($request,$symb) = @_;
 4596: 
 4597:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4598:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4599:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4600:     my $pageTitle = $env{'form.page'};
 4601:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4602:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4603:     my $usec=$classlist->{$env{'form.student'}}[5];
 4604:     if (!&canmodify($usec)) {
 4605: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 4606: 	return;
 4607:     }
 4608:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4609:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 4610: 	'</h3>'."\n";
 4611: 
 4612:     $request->print($result);
 4613: 
 4614: 
 4615:     my $navmap = Apache::lonnavmaps::navmap->new();
 4616:     unless (ref($navmap)) {
 4617:         $request->print(&navmap_errormsg());
 4618:         return;
 4619:     }
 4620:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 4621:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4622:     if (!$map) {
 4623: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 4624: 	return; 
 4625:     }
 4626:     my $iterator = $navmap->getIterator($map->map_start(),
 4627: 					$map->map_finish());
 4628: 
 4629:     my $studentTable=
 4630: 	&Apache::loncommon::start_data_table().
 4631: 	&Apache::loncommon::start_data_table_header_row().
 4632: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 4633: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 4634: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 4635: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 4636: 	&Apache::loncommon::end_data_table_header_row();
 4637: 
 4638:     $iterator->next(); # skip the first BEGIN_MAP
 4639:     my $curRes = $iterator->next(); # for "current resource"
 4640:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
 4641:     while ($depth > 0) {
 4642:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4643:         if($curRes == $iterator->END_MAP) { $depth--; }
 4644: 
 4645:         if (ref($curRes) && $curRes->is_problem()) {
 4646: 	    my $parts = $curRes->parts();
 4647:             my $title = $curRes->compTitle();
 4648: 	    my $symbx = $curRes->symb();
 4649: 	    $studentTable.=
 4650: 		&Apache::loncommon::start_data_table_row().
 4651: 		'<td align="center" valign="top" >'.$prob.
 4652: 		(scalar(@{$parts}) == 1 ? '' 
 4653:                                         : '<br />('.&mt('[quant,_1,&nbsp;part]',scalar(@{$parts}))
 4654: 		.')').'</td>';
 4655: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 4656: 
 4657: 	    my %newrecord=();
 4658: 	    my @displayPts=();
 4659:             my %aggregate = ();
 4660:             my $aggregateflag = 0;
 4661: 	    foreach my $partid (@{$parts}) {
 4662: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 4663: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 4664: 
 4665: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 4666: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 4667: 		my $partial = $newpts/$wgt;
 4668: 		my $score;
 4669: 		if ($partial > 0) {
 4670: 		    $score = 'correct_by_override';
 4671: 		} elsif ($newpts ne '') { #empty is taken as 0
 4672: 		    $score = 'incorrect_by_override';
 4673: 		}
 4674: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 4675: 		if ($dropMenu eq 'excused') {
 4676: 		    $partial = '';
 4677: 		    $score = 'excused';
 4678: 		} elsif ($dropMenu eq 'reset status'
 4679: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 4680: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 4681: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 4682: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 4683: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 4684: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 4685: 		    $changeflag++;
 4686: 		    $newpts = '';
 4687:                     
 4688:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 4689:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 4690:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 4691:                     if ($aggtries > 0) {
 4692:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4693:                         $aggregateflag = 1;
 4694:                     }
 4695: 		}
 4696: 		my $display_part=&get_display_part($partid,$curRes->symb());
 4697: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 4698: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4699: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 4700: 		    '&nbsp;<br />';
 4701: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4702: 		     (($score eq 'excused') ? 'excused' : $newpts).
 4703: 		    '&nbsp;<br />';
 4704: 		$question++;
 4705: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 4706: 
 4707: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 4708: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 4709: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 4710: 		    if (scalar(keys(%newrecord)) > 0);
 4711: 
 4712: 		$changeflag++;
 4713: 	    }
 4714: 	    if (scalar(keys(%newrecord)) > 0) {
 4715: 		my %record = 
 4716: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 4717: 					     $udom,$uname);
 4718: 
 4719: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 4720: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 4721: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 4722: 		    $newrecord{'resource.CODE'} = '';
 4723: 		}
 4724: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 4725: 					$udom,$uname);
 4726: 		%record = &Apache::lonnet::restore($symbx,
 4727: 						   $env{'request.course.id'},
 4728: 						   $udom,$uname);
 4729: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 4730: 					     $cdom,$cnum,$udom,$uname);
 4731: 	    }
 4732: 	    
 4733:             if ($aggregateflag) {
 4734:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4735:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 4736:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 4737:             }
 4738: 
 4739: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 4740: 		'<td valign="top">'.$displayPts[1].'</td>'.
 4741: 		&Apache::loncommon::end_data_table_row();
 4742: 
 4743: 	    $prob++;
 4744: 	}
 4745:         $curRes = $iterator->next();
 4746:     }
 4747: 
 4748:     $studentTable.=&Apache::loncommon::end_data_table();
 4749:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 4750: 		  &mt('The scores were changed for [quant,_1,problem].',
 4751: 		  $changeflag));
 4752:     $request->print($grademsg.$studentTable);
 4753: 
 4754:     return '';
 4755: }
 4756: 
 4757: #-------- end of section for handling grading by page/sequence ---------
 4758: #
 4759: #-------------------------------------------------------------------
 4760: 
 4761: #-------------------- Bubblesheet (Scantron) Grading -------------------
 4762: #
 4763: #------ start of section for handling grading by page/sequence ---------
 4764: 
 4765: =pod
 4766: 
 4767: =head1 Bubble sheet grading routines
 4768: 
 4769:   For this documentation:
 4770: 
 4771:    'scanline' refers to the full line of characters
 4772:    from the file that we are parsing that represents one entire sheet
 4773: 
 4774:    'bubble line' refers to the data
 4775:    representing the line of bubbles that are on the physical bubble sheet
 4776: 
 4777: 
 4778: The overall process is that a scanned in bubble sheet data is uploaded
 4779: into a course. When a user wants to grade, they select a
 4780: sequence/folder of resources, a file of bubble sheet info, and pick
 4781: one of the predefined configurations for what each scanline looks
 4782: like.
 4783: 
 4784: Next each scanline is checked for any errors of either 'missing
 4785: bubbles' (it's an error because it may have been mis-scanned
 4786: because too light bubbling), 'double bubble' (each bubble line should
 4787: have no more that one letter picked), invalid or duplicated CODE,
 4788: invalid student/employee ID
 4789: 
 4790: If the CODE option is used that determines the randomization of the
 4791: homework problems, either way the student/employee ID is looked up into a
 4792: username:domain.
 4793: 
 4794: During the validation phase the instructor can choose to skip scanlines. 
 4795: 
 4796: After the validation phase, there are now 3 bubble sheet files
 4797: 
 4798:   scantron_original_filename (unmodified original file)
 4799:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 4800:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 4801: 
 4802: Also there is a separate hash nohist_scantrondata that contains extra
 4803: correction information that isn't representable in the bubble sheet
 4804: file (see &scantron_getfile() for more information)
 4805: 
 4806: After all scanlines are either valid, marked as valid or skipped, then
 4807: foreach line foreach problem in the picked sequence, an ssi request is
 4808: made that simulates a user submitting their selected letter(s) against
 4809: the homework problem.
 4810: 
 4811: =over 4
 4812: 
 4813: 
 4814: 
 4815: =item defaultFormData
 4816: 
 4817:   Returns html hidden inputs used to hold context/default values.
 4818: 
 4819:  Arguments:
 4820:   $symb - $symb of the current resource 
 4821: 
 4822: =cut
 4823: 
 4824: sub defaultFormData {
 4825:     my ($symb)=@_;
 4826:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />';
 4827: }
 4828: 
 4829: 
 4830: =pod 
 4831: 
 4832: =item getSequenceDropDown
 4833: 
 4834:    Return html dropdown of possible sequences to grade
 4835:  
 4836:  Arguments:
 4837:    $symb - $symb of the current resource
 4838:    $map_error - ref to scalar which will container error if
 4839:                 $navmap object is unavailable in &getSymbMap().
 4840: 
 4841: =cut
 4842: 
 4843: sub getSequenceDropDown {
 4844:     my ($symb,$map_error)=@_;
 4845:     my $result='<select name="selectpage">'."\n";
 4846:     my ($titles,$symbx) = &getSymbMap($map_error);
 4847:     if (ref($map_error)) {
 4848:         return if ($$map_error);
 4849:     }
 4850:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 4851:     my $ctr=0;
 4852:     foreach (@$titles) {
 4853: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4854: 	$result.='<option value="'.$$symbx{$_}.'" '.
 4855: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4856: 	    '>'.$showtitle.'</option>'."\n";
 4857: 	$ctr++;
 4858:     }
 4859:     $result.= '</select>';
 4860:     return $result;
 4861: }
 4862: 
 4863: my %bubble_lines_per_response;     # no. bubble lines for each response.
 4864:                                    # key is zero-based index - 0, 1, 2 ...
 4865: 
 4866: my %first_bubble_line;             # First bubble line no. for each bubble.
 4867: 
 4868: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 4869:                                    # matchresponse or rankresponse, where 
 4870:                                    # an individual response can have multiple 
 4871:                                    # lines
 4872: 
 4873: my %responsetype_per_response;     # responsetype for each response
 4874: 
 4875: # Save and restore the bubble lines array to the form env.
 4876: 
 4877: 
 4878: sub save_bubble_lines {
 4879:     foreach my $line (keys(%bubble_lines_per_response)) {
 4880: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 4881: 	$env{"form.scantron.first_bubble_line.$line"} =
 4882: 	    $first_bubble_line{$line};
 4883:         $env{"form.scantron.sub_bubblelines.$line"} = 
 4884:             $subdivided_bubble_lines{$line};
 4885:         $env{"form.scantron.responsetype.$line"} =
 4886:             $responsetype_per_response{$line};
 4887:     }
 4888: }
 4889: 
 4890: 
 4891: sub restore_bubble_lines {
 4892:     my $line = 0;
 4893:     %bubble_lines_per_response = ();
 4894:     while ($env{"form.scantron.bubblelines.$line"}) {
 4895: 	my $value = $env{"form.scantron.bubblelines.$line"};
 4896: 	$bubble_lines_per_response{$line} = $value;
 4897: 	$first_bubble_line{$line}  =
 4898: 	    $env{"form.scantron.first_bubble_line.$line"};
 4899:         $subdivided_bubble_lines{$line} =
 4900:             $env{"form.scantron.sub_bubblelines.$line"};
 4901:         $responsetype_per_response{$line} =
 4902:             $env{"form.scantron.responsetype.$line"};
 4903: 	$line++;
 4904:     }
 4905: }
 4906: 
 4907: #  Given the parsed scanline, get the response for 
 4908: #  'answer' number n:
 4909: 
 4910: sub get_response_bubbles {
 4911:     my ($parsed_line, $response)  = @_;
 4912: 
 4913:     my $bubble_line = $first_bubble_line{$response-1} +1;
 4914:     my $bubble_lines= $bubble_lines_per_response{$response-1};
 4915:     
 4916:     my $selected = "";
 4917: 
 4918:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
 4919: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
 4920: 	$bubble_line++;
 4921:     }
 4922:     return $selected;
 4923: }
 4924: 
 4925: =pod 
 4926: 
 4927: =item scantron_filenames
 4928: 
 4929:    Returns a list of the scantron files in the current course 
 4930: 
 4931: =cut
 4932: 
 4933: sub scantron_filenames {
 4934:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4935:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4936:     my $getpropath = 1;
 4937:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
 4938:                                        $getpropath);
 4939:     my @possiblenames;
 4940:     foreach my $filename (sort(@files)) {
 4941: 	($filename)=split(/&/,$filename);
 4942: 	if ($filename!~/^scantron_orig_/) { next ; }
 4943: 	$filename=~s/^scantron_orig_//;
 4944: 	push(@possiblenames,$filename);
 4945:     }
 4946:     return @possiblenames;
 4947: }
 4948: 
 4949: =pod 
 4950: 
 4951: =item scantron_uploads
 4952: 
 4953:    Returns  html drop-down list of scantron files in current course.
 4954: 
 4955:  Arguments:
 4956:    $file2grade - filename to set as selected in the dropdown
 4957: 
 4958: =cut
 4959: 
 4960: sub scantron_uploads {
 4961:     my ($file2grade) = @_;
 4962:     my $result=	'<select name="scantron_selectfile">';
 4963:     $result.="<option></option>";
 4964:     foreach my $filename (sort(&scantron_filenames())) {
 4965: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 4966:     }
 4967:     $result.="</select>";
 4968:     return $result;
 4969: }
 4970: 
 4971: =pod 
 4972: 
 4973: =item scantron_scantab
 4974: 
 4975:   Returns html drop down of the scantron formats in the scantronformat.tab
 4976:   file.
 4977: 
 4978: =cut
 4979: 
 4980: sub scantron_scantab {
 4981:     my $result='<select name="scantron_format">'."\n";
 4982:     $result.='<option></option>'."\n";
 4983:     my @lines = &get_scantronformat_file();
 4984:     if (@lines > 0) {
 4985:         foreach my $line (@lines) {
 4986:             next if (($line =~ /^\#/) || ($line eq ''));
 4987: 	    my ($name,$descrip)=split(/:/,$line);
 4988: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 4989:         }
 4990:     }
 4991:     $result.='</select>'."\n";
 4992:     return $result;
 4993: }
 4994: 
 4995: =pod
 4996: 
 4997: =item get_scantronformat_file
 4998: 
 4999:   Returns an array containing lines from the scantron format file for
 5000:   the domain of the course.
 5001: 
 5002:   If a url for a custom.tab file is listed in domain's configuration.db, 
 5003:   lines are from this file.
 5004: 
 5005:   Otherwise, if a default.tab has been published in RES space by the 
 5006:   domainconfig user, lines are from this file.
 5007: 
 5008:   Otherwise, fall back to getting lines from the legacy file on the
 5009:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
 5010: 
 5011: =cut
 5012: 
 5013: sub get_scantronformat_file {
 5014:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5015:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
 5016:     my $gottab = 0;
 5017:     my @lines;
 5018:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 5019:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 5020:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 5021:             if ($formatfile ne '-1') {
 5022:                 @lines = split("\n",$formatfile,-1);
 5023:                 $gottab = 1;
 5024:             }
 5025:         }
 5026:     }
 5027:     if (!$gottab) {
 5028:         my $confname = $cdom.'-domainconfig';
 5029:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 5030:         my $formatfile =  &Apache::lonnet::getfile($default);
 5031:         if ($formatfile ne '-1') {
 5032:             @lines = split("\n",$formatfile,-1);
 5033:             $gottab = 1;
 5034:         }
 5035:     }
 5036:     if (!$gottab) {
 5037:         my @domains = &Apache::lonnet::current_machine_domains();
 5038:         if (grep(/^\Q$cdom\E$/,@domains)) {
 5039:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 5040:             @lines = <$fh>;
 5041:             close($fh);
 5042:         } else {
 5043:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
 5044:             @lines = <$fh>;
 5045:             close($fh);
 5046:         }
 5047:     }
 5048:     return @lines;
 5049: }
 5050: 
 5051: =pod 
 5052: 
 5053: =item scantron_CODElist
 5054: 
 5055:   Returns html drop down of the saved CODE lists from current course,
 5056:   generated from earlier printings.
 5057: 
 5058: =cut
 5059: 
 5060: sub scantron_CODElist {
 5061:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5062:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5063:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 5064:     my $namechoice='<option></option>';
 5065:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 5066: 	if ($name =~ /^error: 2 /) { next; }
 5067: 	if ($name =~ /^type\0/) { next; }
 5068: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 5069:     }
 5070:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 5071:     return $namechoice;
 5072: }
 5073: 
 5074: =pod 
 5075: 
 5076: =item scantron_CODEunique
 5077: 
 5078:   Returns the html for "Each CODE to be used once" radio.
 5079: 
 5080: =cut
 5081: 
 5082: sub scantron_CODEunique {
 5083:     my $result='<span class="LC_nobreak">
 5084:                  <label><input type="radio" name="scantron_CODEunique"
 5085:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 5086:                 </span>
 5087:                 <span class="LC_nobreak">
 5088:                  <label><input type="radio" name="scantron_CODEunique"
 5089:                         value="no" />'.&mt('No').' </label>
 5090:                 </span>';
 5091:     return $result;
 5092: }
 5093: 
 5094: =pod 
 5095: 
 5096: =item scantron_selectphase
 5097: 
 5098:   Generates the initial screen to start the bubble sheet process.
 5099:   Allows for - starting a grading run.
 5100:              - downloading existing scan data (original, corrected
 5101:                                                 or skipped info)
 5102: 
 5103:              - uploading new scan data
 5104: 
 5105:  Arguments:
 5106:   $r          - The Apache request object
 5107:   $file2grade - name of the file that contain the scanned data to score
 5108: 
 5109: =cut
 5110: 
 5111: sub scantron_selectphase {
 5112:     my ($r,$file2grade,$symb) = @_;
 5113:     if (!$symb) {return '';}
 5114:     my $map_error;
 5115:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
 5116:     if ($map_error) {
 5117:         $r->print('<br />'.&navmap_errormsg().'<br />');
 5118:         return;
 5119:     }
 5120:     my $default_form_data=&defaultFormData($symb);
 5121:     my $file_selector=&scantron_uploads($file2grade);
 5122:     my $format_selector=&scantron_scantab();
 5123:     my $CODE_selector=&scantron_CODElist();
 5124:     my $CODE_unique=&scantron_CODEunique();
 5125:     my $result;
 5126: 
 5127:     $ssi_error = 0;
 5128: 
 5129:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 5130:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 5131: 
 5132: 	# Chunk of form to prompt for a scantron file upload.
 5133: 
 5134:         $r->print('
 5135:     <br />
 5136:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5137:        '.&Apache::loncommon::start_data_table_header_row().'
 5138:             <th>
 5139:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
 5140:             </th>
 5141:        '.&Apache::loncommon::end_data_table_header_row().'
 5142:        '.&Apache::loncommon::start_data_table_row().'
 5143:             <td>
 5144: ');
 5145:     my $default_form_data=&defaultFormData($symb);
 5146:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5147:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 5148:     $r->print(&Apache::lonhtmlcommon::scripttag('
 5149:     function checkUpload(formname) {
 5150: 	if (formname.upfile.value == "") {
 5151: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
 5152: 	    return false;
 5153: 	}
 5154: 	formname.submit();
 5155:     }'));
 5156:     $r->print('
 5157:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 5158:                 '.$default_form_data.'
 5159:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 5160:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 5161:                 <input name="command" value="scantronupload_save" type="hidden" />
 5162:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
 5163:                 <br />
 5164:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 5165:               </form>
 5166: ');
 5167: 
 5168:         $r->print('
 5169:             </td>
 5170:        '.&Apache::loncommon::end_data_table_row().'
 5171:        '.&Apache::loncommon::end_data_table().'
 5172: ');
 5173:     }
 5174: 
 5175:     # Chunk of form to prompt for a file to grade and how:
 5176: 
 5177:     $result.= '
 5178:     <br />
 5179:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 5180:     <input type="hidden" name="command" value="scantron_warning" />
 5181:     '.$default_form_data.'
 5182:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5183:        '.&Apache::loncommon::start_data_table_header_row().'
 5184:             <th colspan="2">
 5185:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 5186:             </th>
 5187:        '.&Apache::loncommon::end_data_table_header_row().'
 5188:        '.&Apache::loncommon::start_data_table_row().'
 5189:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 5190:        '.&Apache::loncommon::end_data_table_row().'
 5191:        '.&Apache::loncommon::start_data_table_row().'
 5192:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
 5193:        '.&Apache::loncommon::end_data_table_row().'
 5194:        '.&Apache::loncommon::start_data_table_row().'
 5195:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
 5196:        '.&Apache::loncommon::end_data_table_row().'
 5197:        '.&Apache::loncommon::start_data_table_row().'
 5198:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 5199:        '.&Apache::loncommon::end_data_table_row().'
 5200:        '.&Apache::loncommon::start_data_table_row().'
 5201:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 5202:        '.&Apache::loncommon::end_data_table_row().'
 5203:        '.&Apache::loncommon::start_data_table_row().'
 5204: 	    <td> '.&mt('Options:').' </td>
 5205:             <td>
 5206: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 5207:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 5208:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 5209: 	    </td>
 5210:        '.&Apache::loncommon::end_data_table_row().'
 5211:        '.&Apache::loncommon::start_data_table_row().'
 5212:             <td colspan="2">
 5213:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
 5214:             </td>
 5215:        '.&Apache::loncommon::end_data_table_row().'
 5216:     '.&Apache::loncommon::end_data_table().'
 5217:     </form>
 5218: ';
 5219:    
 5220:     $r->print($result);
 5221: 
 5222: 
 5223: 
 5224:     # Chunk of the form that prompts to view a scoring office file,
 5225:     # corrected file, skipped records in a file.
 5226: 
 5227:     $r->print('
 5228:    <br />
 5229:    <form action="/adm/grades" name="scantron_download">
 5230:      '.$default_form_data.'
 5231:      <input type="hidden" name="command" value="scantron_download" />
 5232:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5233:        '.&Apache::loncommon::start_data_table_header_row().'
 5234:               <th>
 5235:                 &nbsp;'.&mt('Download a scoring office file').'
 5236:               </th>
 5237:        '.&Apache::loncommon::end_data_table_header_row().'
 5238:        '.&Apache::loncommon::start_data_table_row().'
 5239:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 5240:                 <br />
 5241:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 5242:        '.&Apache::loncommon::end_data_table_row().'
 5243:      '.&Apache::loncommon::end_data_table().'
 5244:    </form>
 5245:    <br />
 5246: ');
 5247: 
 5248:     &Apache::lonpickcode::code_list($r,2);
 5249: 
 5250:     $r->print('<br /><form method="post" name="checkscantron">'.
 5251:              $default_form_data."\n".
 5252:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 5253:              &Apache::loncommon::start_data_table_header_row()."\n".
 5254:              '<th colspan="2">
 5255:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
 5256:              '</th>'."\n".
 5257:               &Apache::loncommon::end_data_table_header_row()."\n".
 5258:               &Apache::loncommon::start_data_table_row()."\n".
 5259:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 5260:               '<td> '.$sequence_selector.' </td>'.
 5261:               &Apache::loncommon::end_data_table_row()."\n".
 5262:               &Apache::loncommon::start_data_table_row()."\n".
 5263:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 5264:               '<td> '.$file_selector.' </td>'."\n".
 5265:               &Apache::loncommon::end_data_table_row()."\n".
 5266:               &Apache::loncommon::start_data_table_row()."\n".
 5267:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 5268:               '<td> '.$format_selector.' </td>'."\n".
 5269:               &Apache::loncommon::end_data_table_row()."\n".
 5270:               &Apache::loncommon::start_data_table_row()."\n".
 5271:               '<td> '.&mt('Options').' </td>'."\n".
 5272:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
 5273:               &Apache::loncommon::end_data_table_row()."\n".
 5274:               &Apache::loncommon::start_data_table_row()."\n".
 5275:               '<td colspan="2">'."\n".
 5276:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 5277:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
 5278:               '</td>'."\n".
 5279:               &Apache::loncommon::end_data_table_row()."\n".
 5280:               &Apache::loncommon::end_data_table()."\n".
 5281:               '</form><br />');
 5282:     return;
 5283: }
 5284: 
 5285: =pod
 5286: 
 5287: =item get_scantron_config
 5288: 
 5289:    Parse and return the scantron configuration line selected as a
 5290:    hash of configuration file fields.
 5291: 
 5292:  Arguments:
 5293:     which - the name of the configuration to parse from the file.
 5294: 
 5295: 
 5296:  Returns:
 5297:             If the named configuration is not in the file, an empty
 5298:             hash is returned.
 5299:     a hash with the fields
 5300:       name         - internal name for the this configuration setup
 5301:       description  - text to display to operator that describes this config
 5302:       CODElocation - if 0 or the string 'none'
 5303:                           - no CODE exists for this config
 5304:                      if -1 || the string 'letter'
 5305:                           - a CODE exists for this config and is
 5306:                             a string of letters
 5307:                      Unsupported value (but planned for future support)
 5308:                           if a positive integer
 5309:                                - The CODE exists as the first n items from
 5310:                                  the question section of the form
 5311:                           if the string 'number'
 5312:                                - The CODE exists for this config and is
 5313:                                  a string of numbers
 5314:       CODEstart   - (only matter if a CODE exists) column in the line where
 5315:                      the CODE starts
 5316:       CODElength  - length of the CODE
 5317:       IDstart     - column where the student/employee ID starts
 5318:       IDlength    - length of the student/employee ID info
 5319:       Qstart      - column where the information from the bubbled
 5320:                     'questions' start
 5321:       Qlength     - number of columns comprising a single bubble line from
 5322:                     the sheet. (usually either 1 or 10)
 5323:       Qon         - either a single character representing the character used
 5324:                     to signal a bubble was chosen in the positional setup, or
 5325:                     the string 'letter' if the letter of the chosen bubble is
 5326:                     in the final, or 'number' if a number representing the
 5327:                     chosen bubble is in the file (1->A 0->J)
 5328:       Qoff        - the character used to represent that a bubble was
 5329:                     left blank
 5330:       PaperID     - if the scanning process generates a unique number for each
 5331:                     sheet scanned the column that this ID number starts in
 5332:       PaperIDlength - number of columns that comprise the unique ID number
 5333:                       for the sheet of paper
 5334:       FirstName   - column that the first name starts in
 5335:       FirstNameLength - number of columns that the first name spans
 5336:  
 5337:       LastName    - column that the last name starts in
 5338:       LastNameLength - number of columns that the last name spans
 5339: 
 5340: =cut
 5341: 
 5342: sub get_scantron_config {
 5343:     my ($which) = @_;
 5344:     my @lines = &get_scantronformat_file();
 5345:     my %config;
 5346:     #FIXME probably should move to XML it has already gotten a bit much now
 5347:     foreach my $line (@lines) {
 5348: 	my ($name,$descrip)=split(/:/,$line);
 5349: 	if ($name ne $which ) { next; }
 5350: 	chomp($line);
 5351: 	my @config=split(/:/,$line);
 5352: 	$config{'name'}=$config[0];
 5353: 	$config{'description'}=$config[1];
 5354: 	$config{'CODElocation'}=$config[2];
 5355: 	$config{'CODEstart'}=$config[3];
 5356: 	$config{'CODElength'}=$config[4];
 5357: 	$config{'IDstart'}=$config[5];
 5358: 	$config{'IDlength'}=$config[6];
 5359: 	$config{'Qstart'}=$config[7];
 5360:  	$config{'Qlength'}=$config[8];
 5361: 	$config{'Qoff'}=$config[9];
 5362: 	$config{'Qon'}=$config[10];
 5363: 	$config{'PaperID'}=$config[11];
 5364: 	$config{'PaperIDlength'}=$config[12];
 5365: 	$config{'FirstName'}=$config[13];
 5366: 	$config{'FirstNamelength'}=$config[14];
 5367: 	$config{'LastName'}=$config[15];
 5368: 	$config{'LastNamelength'}=$config[16];
 5369: 	last;
 5370:     }
 5371:     return %config;
 5372: }
 5373: 
 5374: =pod 
 5375: 
 5376: =item username_to_idmap
 5377: 
 5378:     creates a hash keyed by student/employee ID with values of the corresponding
 5379:     student username:domain.
 5380: 
 5381:   Arguments:
 5382: 
 5383:     $classlist - reference to the class list hash. This is a hash
 5384:                  keyed by student name:domain  whose elements are references
 5385:                  to arrays containing various chunks of information
 5386:                  about the student. (See loncoursedata for more info).
 5387: 
 5388:   Returns
 5389:     %idmap - the constructed hash
 5390: 
 5391: =cut
 5392: 
 5393: sub username_to_idmap {
 5394:     my ($classlist)= @_;
 5395:     my %idmap;
 5396:     foreach my $student (keys(%$classlist)) {
 5397: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
 5398: 	    $student;
 5399:     }
 5400:     return %idmap;
 5401: }
 5402: 
 5403: =pod
 5404: 
 5405: =item scantron_fixup_scanline
 5406: 
 5407:    Process a requested correction to a scanline.
 5408: 
 5409:   Arguments:
 5410:     $scantron_config   - hash from &get_scantron_config()
 5411:     $scan_data         - hash of correction information 
 5412:                           (see &scantron_getfile())
 5413:     $line              - existing scanline
 5414:     $whichline         - line number of the passed in scanline
 5415:     $field             - type of change to process 
 5416:                          (either 
 5417:                           'ID'     -> correct the student/employee ID
 5418:                           'CODE'   -> correct the CODE
 5419:                           'answer' -> fixup the submitted answers)
 5420:     
 5421:    $args               - hash of additional info,
 5422:                           - 'ID' 
 5423:                                'newid' -> studentID to use in replacement
 5424:                                           of existing one
 5425:                           - 'CODE' 
 5426:                                'CODE_ignore_dup' - set to true if duplicates
 5427:                                                    should be ignored.
 5428: 	                       'CODE' - is new code or 'use_unfound'
 5429:                                         if the existing unfound code should
 5430:                                         be used as is
 5431:                           - 'answer'
 5432:                                'response' - new answer or 'none' if blank
 5433:                                'question' - the bubble line to change
 5434:                                'questionnum' - the question identifier,
 5435:                                                may include subquestion. 
 5436: 
 5437:   Returns:
 5438:     $line - the modified scanline
 5439: 
 5440:   Side effects: 
 5441:     $scan_data - may be updated
 5442: 
 5443: =cut
 5444: 
 5445: 
 5446: sub scantron_fixup_scanline {
 5447:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 5448:     if ($field eq 'ID') {
 5449: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 5450: 	    return ($line,1,'New value too large');
 5451: 	}
 5452: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 5453: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 5454: 				     $args->{'newid'});
 5455: 	}
 5456: 	substr($line,$$scantron_config{'IDstart'}-1,
 5457: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 5458: 	if ($args->{'newid'}=~/^\s*$/) {
 5459: 	    &scan_data($scan_data,"$whichline.user",
 5460: 		       $args->{'username'}.':'.$args->{'domain'});
 5461: 	}
 5462:     } elsif ($field eq 'CODE') {
 5463: 	if ($args->{'CODE_ignore_dup'}) {
 5464: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 5465: 	}
 5466: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 5467: 	if ($args->{'CODE'} ne 'use_unfound') {
 5468: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 5469: 		return ($line,1,'New CODE value too large');
 5470: 	    }
 5471: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 5472: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 5473: 	    }
 5474: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 5475: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 5476: 	}
 5477:     } elsif ($field eq 'answer') {
 5478: 	my $length=$scantron_config->{'Qlength'};
 5479: 	my $off=$scantron_config->{'Qoff'};
 5480: 	my $on=$scantron_config->{'Qon'};
 5481: 	my $answer=${off}x$length;
 5482: 	if ($args->{'response'} eq 'none') {
 5483: 	    &scan_data($scan_data,
 5484: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 5485: 	} else {
 5486: 	    if ($on eq 'letter') {
 5487: 		my @alphabet=('A'..'Z');
 5488: 		$answer=$alphabet[$args->{'response'}];
 5489: 	    } elsif ($on eq 'number') {
 5490: 		$answer=$args->{'response'}+1;
 5491: 		if ($answer == 10) { $answer = '0'; }
 5492: 	    } else {
 5493: 		substr($answer,$args->{'response'},1)=$on;
 5494: 	    }
 5495: 	    &scan_data($scan_data,
 5496: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 5497: 	}
 5498: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 5499: 	substr($line,$where-1,$length)=$answer;
 5500:     }
 5501:     return $line;
 5502: }
 5503: 
 5504: =pod
 5505: 
 5506: =item scan_data
 5507: 
 5508:     Edit or look up  an item in the scan_data hash.
 5509: 
 5510:   Arguments:
 5511:     $scan_data  - The hash (see scantron_getfile)
 5512:     $key        - shorthand of the key to edit (actual key is
 5513:                   scantronfilename_key).
 5514:     $data        - New value of the hash entry.
 5515:     $delete      - If true, the entry is removed from the hash.
 5516: 
 5517:   Returns:
 5518:     The new value of the hash table field (undefined if deleted).
 5519: 
 5520: =cut
 5521: 
 5522: 
 5523: sub scan_data {
 5524:     my ($scan_data,$key,$value,$delete)=@_;
 5525:     my $filename=$env{'form.scantron_selectfile'};
 5526:     if (defined($value)) {
 5527: 	$scan_data->{$filename.'_'.$key} = $value;
 5528:     }
 5529:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 5530:     return $scan_data->{$filename.'_'.$key};
 5531: }
 5532: 
 5533: # ----- These first few routines are general use routines.----
 5534: 
 5535: # Return the number of occurences of a pattern in a string.
 5536: 
 5537: sub occurence_count {
 5538:     my ($string, $pattern) = @_;
 5539: 
 5540:     my @matches = ($string =~ /$pattern/g);
 5541: 
 5542:     return scalar(@matches);
 5543: }
 5544: 
 5545: 
 5546: # Take a string known to have digits and convert all the
 5547: # digits into letters in the range J,A..I.
 5548: 
 5549: sub digits_to_letters {
 5550:     my ($input) = @_;
 5551: 
 5552:     my @alphabet = ('J', 'A'..'I');
 5553: 
 5554:     my @input    = split(//, $input);
 5555:     my $output ='';
 5556:     for (my $i = 0; $i < scalar(@input); $i++) {
 5557: 	if ($input[$i] =~ /\d/) {
 5558: 	    $output .= $alphabet[$input[$i]];
 5559: 	} else {
 5560: 	    $output .= $input[$i];
 5561: 	}
 5562:     }
 5563:     return $output;
 5564: }
 5565: 
 5566: =pod 
 5567: 
 5568: =item scantron_parse_scanline
 5569: 
 5570:   Decodes a scanline from the selected scantron file
 5571: 
 5572:  Arguments:
 5573:     line             - The text of the scantron file line to process
 5574:     whichline        - Line number
 5575:     scantron_config  - Hash describing the format of the scantron lines.
 5576:     scan_data        - Hash of extra information about the scanline
 5577:                        (see scantron_getfile for more information)
 5578:     just_header      - True if should not process question answers but only
 5579:                        the stuff to the left of the answers.
 5580:  Returns:
 5581:    Hash containing the result of parsing the scanline
 5582: 
 5583:    Keys are all proceeded by the string 'scantron.'
 5584: 
 5585:        CODE    - the CODE in use for this scanline
 5586:        useCODE - 1 if the CODE is invalid but it usage has been forced
 5587:                  by the operator
 5588:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 5589:                             CODEs were selected, but the usage has been
 5590:                             forced by the operator
 5591:        ID  - student/employee ID
 5592:        PaperID - if used, the ID number printed on the sheet when the 
 5593:                  paper was scanned
 5594:        FirstName - first name from the sheet
 5595:        LastName  - last name from the sheet
 5596: 
 5597:      if just_header was not true these key may also exist
 5598: 
 5599:        missingerror - a list of bubble ranges that are considered to be answers
 5600:                       to a single question that don't have any bubbles filled in.
 5601:                       Of the form questionnumber:firstbubblenumber:count.
 5602:        doubleerror  - a list of bubble ranges that are considered to be answers
 5603:                       to a single question that have more than one bubble filled in.
 5604:                       Of the form questionnumber::firstbubblenumber:count
 5605:    
 5606:                 In the above, count is the number of bubble responses in the
 5607:                 input line needed to represent the possible answers to the question.
 5608:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 5609:                 per line would have count = 2.
 5610: 
 5611:        maxquest     - the number of the last bubble line that was parsed
 5612: 
 5613:        (<number> starts at 1)
 5614:        <number>.answer - zero or more letters representing the selected
 5615:                          letters from the scanline for the bubble line 
 5616:                          <number>.
 5617:                          if blank there was either no bubble or there where
 5618:                          multiple bubbles, (consult the keys missingerror and
 5619:                          doubleerror if this is an error condition)
 5620: 
 5621: =cut
 5622: 
 5623: sub scantron_parse_scanline {
 5624:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
 5625: 
 5626:     my %record;
 5627:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 5628:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 5629:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
 5630:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 5631: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 5632: 	if ($$scantron_config{'CODElocation'} < 0 ||
 5633: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 5634: 	    $$scantron_config{'CODElocation'} eq 'number') {
 5635: 	    $record{'scantron.CODE'}=substr($data,
 5636: 					    $$scantron_config{'CODEstart'}-1,
 5637: 					    $$scantron_config{'CODElength'});
 5638: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 5639: 		$record{'scantron.useCODE'}=1;
 5640: 	    }
 5641: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 5642: 		$record{'scantron.CODE_ignore_dup'}=1;
 5643: 	    }
 5644: 	} else {
 5645: 	    #FIXME interpret first N questions
 5646: 	}
 5647:     }
 5648:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 5649: 				  $$scantron_config{'IDlength'});
 5650:     $record{'scantron.PaperID'}=
 5651: 	substr($data,$$scantron_config{'PaperID'}-1,
 5652: 	       $$scantron_config{'PaperIDlength'});
 5653:     $record{'scantron.FirstName'}=
 5654: 	substr($data,$$scantron_config{'FirstName'}-1,
 5655: 	       $$scantron_config{'FirstNamelength'});
 5656:     $record{'scantron.LastName'}=
 5657: 	substr($data,$$scantron_config{'LastName'}-1,
 5658: 	       $$scantron_config{'LastNamelength'});
 5659:     if ($just_header) { return \%record; }
 5660: 
 5661:     my @alphabet=('A'..'Z');
 5662:     my $questnum=0;
 5663:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 5664: 
 5665:     chomp($questions);		# Get rid of any trailing \n.
 5666:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 5667:     while (length($questions)) {
 5668: 	my $answers_needed = $bubble_lines_per_response{$questnum};
 5669:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 5670:                              || 1;
 5671:         $questnum++;
 5672:         my $quest_id = $questnum;
 5673:         my $currentquest = substr($questions,0,$answer_length);
 5674:         $questions       = substr($questions,$answer_length);
 5675:         if (length($currentquest) < $answer_length) { next; }
 5676: 
 5677:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
 5678:             my $subquestnum = 1;
 5679:             my $subquestions = $currentquest;
 5680:             my @subanswers_needed = 
 5681:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
 5682:             foreach my $subans (@subanswers_needed) {
 5683:                 my $subans_length =
 5684:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 5685:                 my $currsubquest = substr($subquestions,0,$subans_length);
 5686:                 $subquestions   = substr($subquestions,$subans_length);
 5687:                 $quest_id = "$questnum.$subquestnum";
 5688:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 5689:                     ($$scantron_config{'Qon'} eq 'number')) {
 5690:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 5691:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 5692:                         \@alphabet,\%record,$scantron_config,$scan_data);
 5693:                 } else {
 5694:                     $ansnum = &scantron_validator_positional($ansnum,
 5695:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
 5696:                 }
 5697:                 $subquestnum ++;
 5698:             }
 5699:         } else {
 5700:             if (($$scantron_config{'Qon'} eq 'letter') ||
 5701:                 ($$scantron_config{'Qon'} eq 'number')) {
 5702:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 5703:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5704:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5705:             } else {
 5706:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 5707:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5708:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5709:             }
 5710:         }
 5711:     }
 5712:     $record{'scantron.maxquest'}=$questnum;
 5713:     return \%record;
 5714: }
 5715: 
 5716: sub scantron_validator_lettnum {
 5717:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 5718:         $alphabet,$record,$scantron_config,$scan_data) = @_;
 5719: 
 5720:     # Qon 'letter' implies for each slot in currquest we have:
 5721:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 5722:     #    about anything else (esp. a value of Qoff) for missing
 5723:     #    bubbles.
 5724:     #
 5725:     # Qon 'number' implies each slot gives a digit that indexes the
 5726:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 5727:     #    and * or ? for double bubbles on a single line.
 5728:     #
 5729: 
 5730:     my $matchon;
 5731:     if ($$scantron_config{'Qon'} eq 'letter') {
 5732:         $matchon = '[A-Z]';
 5733:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 5734:         $matchon = '\d';
 5735:     }
 5736:     my $occurrences = 0;
 5737:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5738:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5739:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5740:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5741:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5742:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5743:         my @singlelines = split('',$currquest);
 5744:         foreach my $entry (@singlelines) {
 5745:             $occurrences = &occurence_count($entry,$matchon);
 5746:             if ($occurrences > 1) {
 5747:                 last;
 5748:             }
 5749:         } 
 5750:     } else {
 5751:         $occurrences = &occurence_count($currquest,$matchon); 
 5752:     }
 5753:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 5754:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5755:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5756:             my $bubble = substr($currquest,$ans,1);
 5757:             if ($bubble =~ /$matchon/ ) {
 5758:                 if ($$scantron_config{'Qon'} eq 'number') {
 5759:                     if ($bubble == 0) {
 5760:                         $bubble = 10; 
 5761:                     }
 5762:                     $record->{"scantron.$ansnum.answer"} = 
 5763:                         $alphabet->[$bubble-1];
 5764:                 } else {
 5765:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 5766:                 }
 5767:             } else {
 5768:                 $record->{"scantron.$ansnum.answer"}='';
 5769:             }
 5770:             $ansnum++;
 5771:         }
 5772:     } elsif (!defined($currquest)
 5773:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 5774:             || (&occurence_count($currquest,$matchon) == 0)) {
 5775:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5776:             $record->{"scantron.$ansnum.answer"}='';
 5777:             $ansnum++;
 5778:         }
 5779:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5780:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 5781:         }
 5782:     } else {
 5783:         if ($$scantron_config{'Qon'} eq 'number') {
 5784:             $currquest = &digits_to_letters($currquest);            
 5785:         }
 5786:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5787:             my $bubble = substr($currquest,$ans,1);
 5788:             $record->{"scantron.$ansnum.answer"} = $bubble;
 5789:             $ansnum++;
 5790:         }
 5791:     }
 5792:     return $ansnum;
 5793: }
 5794: 
 5795: sub scantron_validator_positional {
 5796:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 5797:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
 5798: 
 5799:     # Otherwise there's a positional notation;
 5800:     # each bubble line requires Qlength items, and there are filled in
 5801:     # bubbles for each case where there 'Qon' characters.
 5802:     #
 5803: 
 5804:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 5805: 
 5806:     # If the split only gives us one element.. the full length of the
 5807:     # answer string, no bubbles are filled in:
 5808: 
 5809:     if ($answers_needed eq '') {
 5810:         return;
 5811:     }
 5812: 
 5813:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 5814:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5815:             $record->{"scantron.$ansnum.answer"}='';
 5816:             $ansnum++;
 5817:         }
 5818:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5819:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 5820:         }
 5821:     } elsif (scalar(@array) == 2) {
 5822:         my $location = length($array[0]);
 5823:         my $line_num = int($location / $$scantron_config{'Qlength'});
 5824:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 5825:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5826:             if ($ans eq $line_num) {
 5827:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 5828:             } else {
 5829:                 $record->{"scantron.$ansnum.answer"} = ' ';
 5830:             }
 5831:             $ansnum++;
 5832:          }
 5833:     } else {
 5834:         #  If there's more than one instance of a bubble character
 5835:         #  That's a double bubble; with positional notation we can
 5836:         #  record all the bubbles filled in as well as the
 5837:         #  fact this response consists of multiple bubbles.
 5838:         #
 5839:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5840:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5841:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5842:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5843:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5844:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5845:             my $doubleerror = 0;
 5846:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 5847:                    (!$doubleerror)) {
 5848:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 5849:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 5850:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 5851:                if (length(@currarray) > 2) {
 5852:                    $doubleerror = 1;
 5853:                } 
 5854:             }
 5855:             if ($doubleerror) {
 5856:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5857:             }
 5858:         } else {
 5859:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5860:         }
 5861:         my $item = $ansnum;
 5862:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5863:             $record->{"scantron.$item.answer"} = '';
 5864:             $item ++;
 5865:         }
 5866: 
 5867:         my @ans=@array;
 5868:         my $i=0;
 5869:         my $increment = 0;
 5870:         while ($#ans) {
 5871:             $i+=length($ans[0]) + $increment;
 5872:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 5873:             my $bubble = $i%$$scantron_config{'Qlength'};
 5874:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 5875:             shift(@ans);
 5876:             $increment = 1;
 5877:         }
 5878:         $ansnum += $answers_needed;
 5879:     }
 5880:     return $ansnum;
 5881: }
 5882: 
 5883: =pod
 5884: 
 5885: =item scantron_add_delay
 5886: 
 5887:    Adds an error message that occurred during the grading phase to a
 5888:    queue of messages to be shown after grading pass is complete
 5889: 
 5890:  Arguments:
 5891:    $delayqueue  - arrary ref of hash ref of error messages
 5892:    $scanline    - the scanline that caused the error
 5893:    $errormesage - the error message
 5894:    $errorcode   - a numeric code for the error
 5895: 
 5896:  Side Effects:
 5897:    updates the $delayqueue to have a new hash ref of the error
 5898: 
 5899: =cut
 5900: 
 5901: sub scantron_add_delay {
 5902:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 5903:     push(@$delayqueue,
 5904: 	 {'line' => $scanline, 'emsg' => $errormessage,
 5905: 	  'ecode' => $errorcode }
 5906: 	 );
 5907: }
 5908: 
 5909: =pod
 5910: 
 5911: =item scantron_find_student
 5912: 
 5913:    Finds the username for the current scanline
 5914: 
 5915:   Arguments:
 5916:    $scantron_record - hash result from scantron_parse_scanline
 5917:    $scan_data       - hash of correction information 
 5918:                       (see &scantron_getfile() form more information)
 5919:    $idmap           - hash from &username_to_idmap()
 5920:    $line            - number of current scanline
 5921:  
 5922:   Returns:
 5923:    Either 'username:domain' or undef if unknown
 5924: 
 5925: =cut
 5926: 
 5927: sub scantron_find_student {
 5928:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 5929:     my $scanID=$$scantron_record{'scantron.ID'};
 5930:     if ($scanID =~ /^\s*$/) {
 5931:  	return &scan_data($scan_data,"$line.user");
 5932:     }
 5933:     foreach my $id (keys(%$idmap)) {
 5934:  	if (lc($id) eq lc($scanID)) {
 5935:  	    return $$idmap{$id};
 5936:  	}
 5937:     }
 5938:     return undef;
 5939: }
 5940: 
 5941: =pod
 5942: 
 5943: =item scantron_filter
 5944: 
 5945:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 5946:    hidden resources was selected
 5947: 
 5948: =cut
 5949: 
 5950: sub scantron_filter {
 5951:     my ($curres)=@_;
 5952: 
 5953:     if (ref($curres) && $curres->is_problem()) {
 5954: 	# if the user has asked to not have either hidden
 5955: 	# or 'randomout' controlled resources to be graded
 5956: 	# don't include them
 5957: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 5958: 	    && $curres->randomout) {
 5959: 	    return 0;
 5960: 	}
 5961: 	return 1;
 5962:     }
 5963:     return 0;
 5964: }
 5965: 
 5966: =pod
 5967: 
 5968: =item scantron_process_corrections
 5969: 
 5970:    Gets correction information out of submitted form data and corrects
 5971:    the scanline
 5972: 
 5973: =cut
 5974: 
 5975: sub scantron_process_corrections {
 5976:     my ($r) = @_;
 5977:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 5978:     my ($scanlines,$scan_data)=&scantron_getfile();
 5979:     my $classlist=&Apache::loncoursedata::get_classlist();
 5980:     my $which=$env{'form.scantron_line'};
 5981:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 5982:     my ($skip,$err,$errmsg);
 5983:     if ($env{'form.scantron_skip_record'}) {
 5984: 	$skip=1;
 5985:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 5986: 	my $newstudent=$env{'form.scantron_username'}.':'.
 5987: 	    $env{'form.scantron_domain'};
 5988: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 5989: 	($line,$err,$errmsg)=
 5990: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 5991: 				     'ID',{'newid'=>$newid,
 5992: 				    'username'=>$env{'form.scantron_username'},
 5993: 				    'domain'=>$env{'form.scantron_domain'}});
 5994:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 5995: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 5996: 	my $newCODE;
 5997: 	my %args;
 5998: 	if      ($resolution eq 'use_unfound') {
 5999: 	    $newCODE='use_unfound';
 6000: 	} elsif ($resolution eq 'use_found') {
 6001: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 6002: 	} elsif ($resolution eq 'use_typed') {
 6003: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 6004: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 6005: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 6006: 	}
 6007: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 6008: 	    $args{'CODE_ignore_dup'}=1;
 6009: 	}
 6010: 	$args{'CODE'}=$newCODE;
 6011: 	($line,$err,$errmsg)=
 6012: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6013: 				     'CODE',\%args);
 6014:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 6015: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 6016: 	    ($line,$err,$errmsg)=
 6017: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 6018: 					 $which,'answer',
 6019: 					 { 'question'=>$question,
 6020: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 6021:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 6022: 	    if ($err) { last; }
 6023: 	}
 6024:     }
 6025:     if ($err) {
 6026: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
 6027:     } else {
 6028: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 6029: 	&scantron_putfile($scanlines,$scan_data);
 6030:     }
 6031: }
 6032: 
 6033: =pod
 6034: 
 6035: =item reset_skipping_status
 6036: 
 6037:    Forgets the current set of remember skipped scanlines (and thus
 6038:    reverts back to considering all lines in the
 6039:    scantron_skipped_<filename> file)
 6040: 
 6041: =cut
 6042: 
 6043: sub reset_skipping_status {
 6044:     my ($scanlines,$scan_data)=&scantron_getfile();
 6045:     &scan_data($scan_data,'remember_skipping',undef,1);
 6046:     &scantron_putfile(undef,$scan_data);
 6047: }
 6048: 
 6049: =pod
 6050: 
 6051: =item start_skipping
 6052: 
 6053:    Marks a scanline to be skipped. 
 6054: 
 6055: =cut
 6056: 
 6057: sub start_skipping {
 6058:     my ($scan_data,$i)=@_;
 6059:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6060:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 6061: 	$remembered{$i}=2;
 6062:     } else {
 6063: 	$remembered{$i}=1;
 6064:     }
 6065:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 6066: }
 6067: 
 6068: =pod
 6069: 
 6070: =item should_be_skipped
 6071: 
 6072:    Checks whether a scanline should be skipped.
 6073: 
 6074: =cut
 6075: 
 6076: sub should_be_skipped {
 6077:     my ($scanlines,$scan_data,$i)=@_;
 6078:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 6079: 	# not redoing old skips
 6080: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 6081: 	return 0;
 6082:     }
 6083:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6084: 
 6085:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 6086: 	return 0;
 6087:     }
 6088:     return 1;
 6089: }
 6090: 
 6091: =pod
 6092: 
 6093: =item remember_current_skipped
 6094: 
 6095:    Discovers what scanlines are in the scantron_skipped_<filename>
 6096:    file and remembers them into scan_data for later use.
 6097: 
 6098: =cut
 6099: 
 6100: sub remember_current_skipped {
 6101:     my ($scanlines,$scan_data)=&scantron_getfile();
 6102:     my %to_remember;
 6103:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6104: 	if ($scanlines->{'skipped'}[$i]) {
 6105: 	    $to_remember{$i}=1;
 6106: 	}
 6107:     }
 6108: 
 6109:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 6110:     &scantron_putfile(undef,$scan_data);
 6111: }
 6112: 
 6113: =pod
 6114: 
 6115: =item check_for_error
 6116: 
 6117:     Checks if there was an error when attempting to remove a specific
 6118:     scantron_.. bubble sheet data file. Prints out an error if
 6119:     something went wrong.
 6120: 
 6121: =cut
 6122: 
 6123: sub check_for_error {
 6124:     my ($r,$result)=@_;
 6125:     if ($result ne 'ok' && $result ne 'not_found' ) {
 6126: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 6127:     }
 6128: }
 6129: 
 6130: =pod
 6131: 
 6132: =item scantron_warning_screen
 6133: 
 6134:    Interstitial screen to make sure the operator has selected the
 6135:    correct options before we start the validation phase.
 6136: 
 6137: =cut
 6138: 
 6139: sub scantron_warning_screen {
 6140:     my ($button_text)=@_;
 6141:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 6142:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6143:     my $CODElist;
 6144:     if ($scantron_config{'CODElocation'} &&
 6145: 	$scantron_config{'CODEstart'} &&
 6146: 	$scantron_config{'CODElength'}) {
 6147: 	$CODElist=$env{'form.scantron_CODElist'};
 6148: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
 6149: 	$CODElist=
 6150: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 6151: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 6152:     }
 6153:     return ('
 6154: <p>
 6155: <span class="LC_warning">
 6156: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
 6157: </p>
 6158: <table>
 6159: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 6160: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 6161: '.$CODElist.'
 6162: </table>
 6163: <br />
 6164: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
 6165: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
 6166: 
 6167: <br />
 6168: ');
 6169: }
 6170: 
 6171: =pod
 6172: 
 6173: =item scantron_do_warning
 6174: 
 6175:    Check if the operator has picked something for all required
 6176:    fields. Error out if something is missing.
 6177: 
 6178: =cut
 6179: 
 6180: sub scantron_do_warning {
 6181:     my ($r,$symb)=@_;
 6182:     if (!$symb) {return '';}
 6183:     my $default_form_data=&defaultFormData($symb);
 6184:     $r->print(&scantron_form_start().$default_form_data);
 6185:     if ( $env{'form.selectpage'} eq '' ||
 6186: 	 $env{'form.scantron_selectfile'} eq '' ||
 6187: 	 $env{'form.scantron_format'} eq '' ) {
 6188: 	$r->print("<p>".&mt('You have forgetten to specify some information. Please go Back and try again.')."</p>");
 6189: 	if ( $env{'form.selectpage'} eq '') {
 6190: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 6191: 	} 
 6192: 	if ( $env{'form.scantron_selectfile'} eq '') {
 6193: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a file that contains the student\'s response data.').'</span></p>');
 6194: 	} 
 6195: 	if ( $env{'form.scantron_format'} eq '') {
 6196: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a the format of the student\'s response data.').'</span></p>');
 6197: 	} 
 6198:     } else {
 6199: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
 6200: 	$r->print('
 6201: '.$warning.'
 6202: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 6203: <input type="hidden" name="command" value="scantron_validate" />
 6204: ');
 6205:     }
 6206:     $r->print("</form><br />");
 6207:     return '';
 6208: }
 6209: 
 6210: =pod
 6211: 
 6212: =item scantron_form_start
 6213: 
 6214:     html hidden input for remembering all selected grading options
 6215: 
 6216: =cut
 6217: 
 6218: sub scantron_form_start {
 6219:     my ($max_bubble)=@_;
 6220:     my $result= <<SCANTRONFORM;
 6221: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 6222:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 6223:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 6224:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 6225:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 6226:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 6227:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 6228:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 6229:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 6230:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 6231: SCANTRONFORM
 6232: 
 6233:   my $line = 0;
 6234:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 6235:        my $chunk =
 6236: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 6237:        $chunk .=
 6238: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 6239:        $chunk .= 
 6240:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 6241:        $chunk .=
 6242:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 6243:        $result .= $chunk;
 6244:        $line++;
 6245:    }
 6246:     return $result;
 6247: }
 6248: 
 6249: =pod
 6250: 
 6251: =item scantron_validate_file
 6252: 
 6253:     Dispatch routine for doing validation of a bubble sheet data file.
 6254: 
 6255:     Also processes any necessary information resets that need to
 6256:     occur before validation begins (ignore previous corrections,
 6257:     restarting the skipped records processing)
 6258: 
 6259: =cut
 6260: 
 6261: sub scantron_validate_file {
 6262:     my ($r,$symb) = @_;
 6263:     if (!$symb) {return '';}
 6264:     my $default_form_data=&defaultFormData($symb);
 6265:     
 6266:     # do the detection of only doing skipped records first befroe we delete
 6267:     # them when doing the corrections reset
 6268:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 6269: 	&reset_skipping_status();
 6270:     }
 6271:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 6272: 	&remember_current_skipped();
 6273: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 6274:     }
 6275: 
 6276:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 6277: 	&check_for_error($r,&scantron_remove_file('corrected'));
 6278: 	&check_for_error($r,&scantron_remove_file('skipped'));
 6279: 	&check_for_error($r,&scantron_remove_scan_data());
 6280: 	$env{'form.scantron_options_ignore'}='done';
 6281:     }
 6282: 
 6283:     if ($env{'form.scantron_corrections'}) {
 6284: 	&scantron_process_corrections($r);
 6285:     }
 6286:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 6287:     #get the student pick code ready
 6288:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 6289:     my $nav_error;
 6290:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
 6291:     if ($nav_error) {
 6292:         $r->print(&navmap_errormsg());
 6293:         return '';
 6294:     }
 6295:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 6296:     $r->print($result);
 6297:     
 6298:     my @validate_phases=( 'sequence',
 6299: 			  'ID',
 6300: 			  'CODE',
 6301: 			  'doublebubble',
 6302: 			  'missingbubbles');
 6303:     if (!$env{'form.validatepass'}) {
 6304: 	$env{'form.validatepass'} = 0;
 6305:     }
 6306:     my $currentphase=$env{'form.validatepass'};
 6307: 
 6308: 
 6309:     my $stop=0;
 6310:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 6311: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 6312: 	$r->rflush();
 6313: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 6314: 	{
 6315: 	    no strict 'refs';
 6316: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 6317: 	}
 6318:     }
 6319:     if (!$stop) {
 6320: 	my $warning=&scantron_warning_screen('Start Grading');
 6321: 	$r->print(&mt('Validation process complete.').'<br />'.
 6322:                   $warning.
 6323:                   &mt('Perform verification for each student after storage of submissions?').
 6324:                   '&nbsp;<span class="LC_nobreak"><label>'.
 6325:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 6326:                   ('&nbsp;'x3).'<label>'.
 6327:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 6328:                   '</label></span><br />'.
 6329:                   &mt('Grading will take longer if you use verification.').'<br />'.
 6330:                   &mt("Alternatively, the 'Review bubblesheet data' utility (see grading menu) can be used for all students after grading is complete.").'<br /><br />'.
 6331:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 6332:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 6333:     } else {
 6334: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 6335: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 6336:     }
 6337:     if ($stop) {
 6338: 	if ($validate_phases[$currentphase] eq 'sequence') {
 6339: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 6340: 	    $r->print(' '.&mt('this error').' <br />');
 6341: 
 6342: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
 6343: 	} else {
 6344:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 6345: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 6346:             } else {
 6347:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 6348:             }
 6349: 	    $r->print(' '.&mt('using corrected info').' <br />');
 6350: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 6351: 	    $r->print(" ".&mt("this scanline saving it for later."));
 6352: 	}
 6353:     }
 6354:     $r->print(" </form><br />");
 6355:     return '';
 6356: }
 6357: 
 6358: 
 6359: =pod
 6360: 
 6361: =item scantron_remove_file
 6362: 
 6363:    Removes the requested bubble sheet data file, makes sure that
 6364:    scantron_original_<filename> is never removed
 6365: 
 6366: 
 6367: =cut
 6368: 
 6369: sub scantron_remove_file {
 6370:     my ($which)=@_;
 6371:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6372:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6373:     my $file='scantron_';
 6374:     if ($which eq 'corrected' || $which eq 'skipped') {
 6375: 	$file.=$which.'_';
 6376:     } else {
 6377: 	return 'refused';
 6378:     }
 6379:     $file.=$env{'form.scantron_selectfile'};
 6380:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 6381: }
 6382: 
 6383: 
 6384: =pod
 6385: 
 6386: =item scantron_remove_scan_data
 6387: 
 6388:    Removes all scan_data correction for the requested bubble sheet
 6389:    data file.  (In the case that both the are doing skipped records we need
 6390:    to remember the old skipped lines for the time being so that element
 6391:    persists for a while.)
 6392: 
 6393: =cut
 6394: 
 6395: sub scantron_remove_scan_data {
 6396:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6397:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6398:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 6399:     my @todelete;
 6400:     my $filename=$env{'form.scantron_selectfile'};
 6401:     foreach my $key (@keys) {
 6402: 	if ($key=~/^\Q$filename\E_/) {
 6403: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 6404: 		$key=~/remember_skipping/) {
 6405: 		next;
 6406: 	    }
 6407: 	    push(@todelete,$key);
 6408: 	}
 6409:     }
 6410:     my $result;
 6411:     if (@todelete) {
 6412: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 6413: 				       \@todelete,$cdom,$cname);
 6414:     } else {
 6415: 	$result = 'ok';
 6416:     }
 6417:     return $result;
 6418: }
 6419: 
 6420: 
 6421: =pod
 6422: 
 6423: =item scantron_getfile
 6424: 
 6425:     Fetches the requested bubble sheet data file (all 3 versions), and
 6426:     the scan_data hash
 6427:   
 6428:   Arguments:
 6429:     None
 6430: 
 6431:   Returns:
 6432:     2 hash references
 6433: 
 6434:      - first one has 
 6435:          orig      -
 6436:          corrected -
 6437:          skipped   -  each of which points to an array ref of the specified
 6438:                       file broken up into individual lines
 6439:          count     - number of scanlines
 6440:  
 6441:      - second is the scan_data hash possible keys are
 6442:        ($number refers to scanline numbered $number and thus the key affects
 6443:         only that scanline
 6444:         $bubline refers to the specific bubble line element and the aspects
 6445:         refers to that specific bubble line element)
 6446: 
 6447:        $number.user - username:domain to use
 6448:        $number.CODE_ignore_dup 
 6449:                     - ignore the duplicate CODE error 
 6450:        $number.useCODE
 6451:                     - use the CODE in the scanline as is
 6452:        $number.no_bubble.$bubline
 6453:                     - it is valid that there is no bubbled in bubble
 6454:                       at $number $bubline
 6455:        remember_skipping
 6456:                     - a frozen hash containing keys of $number and values
 6457:                       of either 
 6458:                         1 - we are on a 'do skipped records pass' and plan
 6459:                             on processing this line
 6460:                         2 - we are on a 'do skipped records pass' and this
 6461:                             scanline has been marked to skip yet again
 6462: 
 6463: =cut
 6464: 
 6465: sub scantron_getfile {
 6466:     #FIXME really would prefer a scantron directory
 6467:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6468:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6469:     my $lines;
 6470:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6471: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 6472:     my %scanlines;
 6473:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 6474:     my $temp=$scanlines{'orig'};
 6475:     $scanlines{'count'}=$#$temp;
 6476: 
 6477:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6478: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 6479:     if ($lines eq '-1') {
 6480: 	$scanlines{'corrected'}=[];
 6481:     } else {
 6482: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 6483:     }
 6484:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6485: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 6486:     if ($lines eq '-1') {
 6487: 	$scanlines{'skipped'}=[];
 6488:     } else {
 6489: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 6490:     }
 6491:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 6492:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 6493:     my %scan_data = @tmp;
 6494:     return (\%scanlines,\%scan_data);
 6495: }
 6496: 
 6497: =pod
 6498: 
 6499: =item lonnet_putfile
 6500: 
 6501:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 6502: 
 6503:  Arguments:
 6504:    $contents - data to store
 6505:    $filename - filename to store $contents into
 6506: 
 6507:  Returns:
 6508:    result value from &Apache::lonnet::finishuserfileupload
 6509: 
 6510: =cut
 6511: 
 6512: sub lonnet_putfile {
 6513:     my ($contents,$filename)=@_;
 6514:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6515:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6516:     $env{'form.sillywaytopassafilearound'}=$contents;
 6517:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 6518: 
 6519: }
 6520: 
 6521: =pod
 6522: 
 6523: =item scantron_putfile
 6524: 
 6525:     Stores the current version of the bubble sheet data files, and the
 6526:     scan_data hash. (Does not modify the original version only the
 6527:     corrected and skipped versions.
 6528: 
 6529:  Arguments:
 6530:     $scanlines - hash ref that looks like the first return value from
 6531:                  &scantron_getfile()
 6532:     $scan_data - hash ref that looks like the second return value from
 6533:                  &scantron_getfile()
 6534: 
 6535: =cut
 6536: 
 6537: sub scantron_putfile {
 6538:     my ($scanlines,$scan_data) = @_;
 6539:     #FIXME really would prefer a scantron directory
 6540:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6541:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6542:     if ($scanlines) {
 6543: 	my $prefix='scantron_';
 6544: # no need to update orig, shouldn't change
 6545: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 6546: #		    $env{'form.scantron_selectfile'});
 6547: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 6548: 			$prefix.'corrected_'.
 6549: 			$env{'form.scantron_selectfile'});
 6550: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 6551: 			$prefix.'skipped_'.
 6552: 			$env{'form.scantron_selectfile'});
 6553:     }
 6554:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 6555: }
 6556: 
 6557: =pod
 6558: 
 6559: =item scantron_get_line
 6560: 
 6561:    Returns the correct version of the scanline
 6562: 
 6563:  Arguments:
 6564:     $scanlines - hash ref that looks like the first return value from
 6565:                  &scantron_getfile()
 6566:     $scan_data - hash ref that looks like the second return value from
 6567:                  &scantron_getfile()
 6568:     $i         - number of the requested line (starts at 0)
 6569: 
 6570:  Returns:
 6571:    A scanline, (either the original or the corrected one if it
 6572:    exists), or undef if the requested scanline should be
 6573:    skipped. (Either because it's an skipped scanline, or it's an
 6574:    unskipped scanline and we are not doing a 'do skipped scanlines'
 6575:    pass.
 6576: 
 6577: =cut
 6578: 
 6579: sub scantron_get_line {
 6580:     my ($scanlines,$scan_data,$i)=@_;
 6581:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 6582:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 6583:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 6584:     return $scanlines->{'orig'}[$i]; 
 6585: }
 6586: 
 6587: =pod
 6588: 
 6589: =item scantron_todo_count
 6590: 
 6591:     Counts the number of scanlines that need processing.
 6592: 
 6593:  Arguments:
 6594:     $scanlines - hash ref that looks like the first return value from
 6595:                  &scantron_getfile()
 6596:     $scan_data - hash ref that looks like the second return value from
 6597:                  &scantron_getfile()
 6598: 
 6599:  Returns:
 6600:     $count - number of scanlines to process
 6601: 
 6602: =cut
 6603: 
 6604: sub get_todo_count {
 6605:     my ($scanlines,$scan_data)=@_;
 6606:     my $count=0;
 6607:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6608: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6609: 	if ($line=~/^[\s\cz]*$/) { next; }
 6610: 	$count++;
 6611:     }
 6612:     return $count;
 6613: }
 6614: 
 6615: =pod
 6616: 
 6617: =item scantron_put_line
 6618: 
 6619:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
 6620:     data file.
 6621: 
 6622:  Arguments:
 6623:     $scanlines - hash ref that looks like the first return value from
 6624:                  &scantron_getfile()
 6625:     $scan_data - hash ref that looks like the second return value from
 6626:                  &scantron_getfile()
 6627:     $i         - line number to update
 6628:     $newline   - contents of the updated scanline
 6629:     $skip      - if true make the line for skipping and update the
 6630:                  'skipped' file
 6631: 
 6632: =cut
 6633: 
 6634: sub scantron_put_line {
 6635:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 6636:     if ($skip) {
 6637: 	$scanlines->{'skipped'}[$i]=$newline;
 6638: 	&start_skipping($scan_data,$i);
 6639: 	return;
 6640:     }
 6641:     $scanlines->{'corrected'}[$i]=$newline;
 6642: }
 6643: 
 6644: =pod
 6645: 
 6646: =item scantron_clear_skip
 6647: 
 6648:    Remove a line from the 'skipped' file
 6649: 
 6650:  Arguments:
 6651:     $scanlines - hash ref that looks like the first return value from
 6652:                  &scantron_getfile()
 6653:     $scan_data - hash ref that looks like the second return value from
 6654:                  &scantron_getfile()
 6655:     $i         - line number to update
 6656: 
 6657: =cut
 6658: 
 6659: sub scantron_clear_skip {
 6660:     my ($scanlines,$scan_data,$i)=@_;
 6661:     if (exists($scanlines->{'skipped'}[$i])) {
 6662: 	undef($scanlines->{'skipped'}[$i]);
 6663: 	return 1;
 6664:     }
 6665:     return 0;
 6666: }
 6667: 
 6668: =pod
 6669: 
 6670: =item scantron_filter_not_exam
 6671: 
 6672:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 6673:    filter out resources that are not marked as 'exam' mode
 6674: 
 6675: =cut
 6676: 
 6677: sub scantron_filter_not_exam {
 6678:     my ($curres)=@_;
 6679:     
 6680:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 6681: 	# if the user has asked to not have either hidden
 6682: 	# or 'randomout' controlled resources to be graded
 6683: 	# don't include them
 6684: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6685: 	    && $curres->randomout) {
 6686: 	    return 0;
 6687: 	}
 6688: 	return 1;
 6689:     }
 6690:     return 0;
 6691: }
 6692: 
 6693: =pod
 6694: 
 6695: =item scantron_validate_sequence
 6696: 
 6697:     Validates the selected sequence, checking for resource that are
 6698:     not set to exam mode.
 6699: 
 6700: =cut
 6701: 
 6702: sub scantron_validate_sequence {
 6703:     my ($r,$currentphase) = @_;
 6704: 
 6705:     my $navmap=Apache::lonnavmaps::navmap->new();
 6706:     unless (ref($navmap)) {
 6707:         $r->print(&navmap_errormsg());
 6708:         return (1,$currentphase);
 6709:     }
 6710:     my (undef,undef,$sequence)=
 6711: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 6712: 
 6713:     my $map=$navmap->getResourceByUrl($sequence);
 6714: 
 6715:     $r->print('<input type="hidden" name="validate_sequence_exam"
 6716:                                     value="ignore" />');
 6717:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 6718: 	my @resources=
 6719: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 6720: 	if (@resources) {
 6721: 	    $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>");
 6722: 	    return (1,$currentphase);
 6723: 	}
 6724:     }
 6725: 
 6726:     return (0,$currentphase+1);
 6727: }
 6728: 
 6729: 
 6730: 
 6731: sub scantron_validate_ID {
 6732:     my ($r,$currentphase) = @_;
 6733:     
 6734:     #get student info
 6735:     my $classlist=&Apache::loncoursedata::get_classlist();
 6736:     my %idmap=&username_to_idmap($classlist);
 6737: 
 6738:     #get scantron line setup
 6739:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6740:     my ($scanlines,$scan_data)=&scantron_getfile();
 6741: 
 6742:     my $nav_error;
 6743:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble_lines.. array.
 6744:     if ($nav_error) {
 6745:         $r->print(&navmap_errormsg());
 6746:         return(1,$currentphase);
 6747:     }
 6748: 
 6749:     my %found=('ids'=>{},'usernames'=>{});
 6750:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6751: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6752: 	if ($line=~/^[\s\cz]*$/) { next; }
 6753: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 6754: 						 $scan_data);
 6755: 	my $id=$$scan_record{'scantron.ID'};
 6756: 	my $found;
 6757: 	foreach my $checkid (keys(%idmap)) {
 6758: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 6759: 	}
 6760: 	if ($found) {
 6761: 	    my $username=$idmap{$found};
 6762: 	    if ($found{'ids'}{$found}) {
 6763: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6764: 					 $line,'duplicateID',$found);
 6765: 		return(1,$currentphase);
 6766: 	    } elsif ($found{'usernames'}{$username}) {
 6767: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6768: 					 $line,'duplicateID',$username);
 6769: 		return(1,$currentphase);
 6770: 	    }
 6771: 	    #FIXME store away line we previously saw the ID on to use above
 6772: 	    $found{'ids'}{$found}++;
 6773: 	    $found{'usernames'}{$username}++;
 6774: 	} else {
 6775: 	    if ($id =~ /^\s*$/) {
 6776: 		my $username=&scan_data($scan_data,"$i.user");
 6777: 		if (defined($username) && $found{'usernames'}{$username}) {
 6778: 		    &scantron_get_correction($r,$i,$scan_record,
 6779: 					     \%scantron_config,
 6780: 					     $line,'duplicateID',$username);
 6781: 		    return(1,$currentphase);
 6782: 		} elsif (!defined($username)) {
 6783: 		    &scantron_get_correction($r,$i,$scan_record,
 6784: 					     \%scantron_config,
 6785: 					     $line,'incorrectID');
 6786: 		    return(1,$currentphase);
 6787: 		}
 6788: 		$found{'usernames'}{$username}++;
 6789: 	    } else {
 6790: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6791: 					 $line,'incorrectID');
 6792: 		return(1,$currentphase);
 6793: 	    }
 6794: 	}
 6795:     }
 6796: 
 6797:     return (0,$currentphase+1);
 6798: }
 6799: 
 6800: 
 6801: sub scantron_get_correction {
 6802:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
 6803: #FIXME in the case of a duplicated ID the previous line, probably need
 6804: #to show both the current line and the previous one and allow skipping
 6805: #the previous one or the current one
 6806: 
 6807:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 6808: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6809: 			    " for PaperID <tt>[_1]</tt>",
 6810: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
 6811:     } else {
 6812: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6813: 			    " in scanline [_1] <pre>[_2]</pre>",
 6814: 			    $i,$line)."</p> \n");
 6815:     }
 6816:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
 6817: 			  "The name on the paper is [_2],[_3]",
 6818: 			  $$scan_record{'scantron.ID'},
 6819: 			  $$scan_record{'scantron.LastName'},
 6820: 			  $$scan_record{'scantron.FirstName'})."</p>";
 6821: 
 6822:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 6823:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 6824:                            # Array populated for doublebubble or
 6825:     my @lines_to_correct;  # missingbubble errors to build javascript
 6826:                            # to validate radio button checking   
 6827: 
 6828:     if ($error =~ /ID$/) {
 6829: 	if ($error eq 'incorrectID') {
 6830: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
 6831: 		      "</p>\n");
 6832: 	} elsif ($error eq 'duplicateID') {
 6833: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 6834: 	}
 6835: 	$r->print($message);
 6836: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6837: 	$r->print("\n<ul><li> ");
 6838: 	#FIXME it would be nice if this sent back the user ID and
 6839: 	#could do partial userID matches
 6840: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 6841: 				       'scantron_username','scantron_domain'));
 6842: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 6843: 	$r->print("\n@".
 6844: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 6845: 
 6846: 	$r->print('</li>');
 6847:     } elsif ($error =~ /CODE$/) {
 6848: 	if ($error eq 'incorrectCODE') {
 6849: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 6850: 	} elsif ($error eq 'duplicateCODE') {
 6851: 	    $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");
 6852: 	}
 6853: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
 6854: 			    $$scan_record{'scantron.CODE'})."<br />\n");
 6855: 	$r->print($message);
 6856: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6857: 	$r->print("\n<br /> ");
 6858: 	my $i=0;
 6859: 	if ($error eq 'incorrectCODE' 
 6860: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 6861: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 6862: 	    if ($closest > 0) {
 6863: 		foreach my $testcode (@{$closest}) {
 6864: 		    my $checked='';
 6865: 		    if (!$i) { $checked=' checked="checked"'; }
 6866: 		    $r->print("
 6867:    <label>
 6868:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
 6869:        ".&mt("Use the similar CODE [_1] instead.",
 6870: 	    "<b><tt>".$testcode."</tt></b>")."
 6871:     </label>
 6872:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 6873: 		    $r->print("\n<br />");
 6874: 		    $i++;
 6875: 		}
 6876: 	    }
 6877: 	}
 6878: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 6879: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
 6880: 	    $r->print("
 6881:     <label>
 6882:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
 6883:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
 6884: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 6885:     </label>");
 6886: 	    $r->print("\n<br />");
 6887: 	}
 6888: 
 6889: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
 6890: function change_radio(field) {
 6891:     var slct=document.scantronupload.scantron_CODE_resolution;
 6892:     var i;
 6893:     for (i=0;i<slct.length;i++) {
 6894:         if (slct[i].value==field) { slct[i].checked=true; }
 6895:     }
 6896: }
 6897: ENDSCRIPT
 6898: 	my $href="/adm/pickcode?".
 6899: 	   "form=".&escape("scantronupload").
 6900: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 6901: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 6902: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 6903: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 6904: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 6905: 	    $r->print("
 6906:     <label>
 6907:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 6908:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 6909: 	     "<a target='_blank' href='$href'>","</a>")."
 6910:     </label> 
 6911:     ".&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\')" />'));
 6912: 	    $r->print("\n<br />");
 6913: 	}
 6914: 	$r->print("
 6915:     <label>
 6916:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 6917:        ".&mt("Use [_1] as the CODE.",
 6918: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 6919: 	$r->print("\n<br /><br />");
 6920:     } elsif ($error eq 'doublebubble') {
 6921: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 6922: 
 6923: 	# The form field scantron_questions is acutally a list of line numbers.
 6924: 	# represented by this form so:
 6925: 
 6926: 	my $line_list = &questions_to_line_list($arg);
 6927: 
 6928: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 6929: 		  $line_list.'" />');
 6930: 	$r->print($message);
 6931: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 6932: 	foreach my $question (@{$arg}) {
 6933: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 6934:                                                    $scan_record, $error);
 6935:             push(@lines_to_correct,@linenums);
 6936: 	}
 6937:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 6938:     } elsif ($error eq 'missingbubble') {
 6939: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
 6940: 	$r->print($message);
 6941: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 6942: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 6943: 
 6944: 	# The form field scantron_questions is actually a list of line numbers not
 6945: 	# a list of question numbers. Therefore:
 6946: 	#
 6947: 	
 6948: 	my $line_list = &questions_to_line_list($arg);
 6949: 
 6950: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 6951: 		  $line_list.'" />');
 6952: 	foreach my $question (@{$arg}) {
 6953: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 6954:                                                    $scan_record, $error);
 6955:             push(@lines_to_correct,@linenums);
 6956: 	}
 6957:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 6958:     } else {
 6959: 	$r->print("\n<ul>");
 6960:     }
 6961:     $r->print("\n</li></ul>");
 6962: }
 6963: 
 6964: sub verify_bubbles_checked {
 6965:     my (@ansnums) = @_;
 6966:     my $ansnumstr = join('","',@ansnums);
 6967:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 6968:     my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
 6969: function verify_bubble_radio(form) {
 6970:     var ansnumArray = new Array ("$ansnumstr");
 6971:     var need_bubble_count = 0;
 6972:     for (var i=0; i<ansnumArray.length; i++) {
 6973:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 6974:             var bubble_picked = 0; 
 6975:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 6976:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 6977:                     bubble_picked = 1;
 6978:                 }
 6979:             }
 6980:             if (bubble_picked == 0) {
 6981:                 need_bubble_count ++;
 6982:             }
 6983:         }
 6984:     }
 6985:     if (need_bubble_count) {
 6986:         alert("$warning");
 6987:         return;
 6988:     }
 6989:     form.submit(); 
 6990: }
 6991: ENDSCRIPT
 6992:     return $output;
 6993: }
 6994: 
 6995: =pod
 6996: 
 6997: =item  questions_to_line_list
 6998: 
 6999: Converts a list of questions into a string of comma separated
 7000: line numbers in the answer sheet used by the questions.  This is
 7001: used to fill in the scantron_questions form field.
 7002: 
 7003:   Arguments:
 7004:      questions    - Reference to an array of questions.
 7005: 
 7006: =cut
 7007: 
 7008: 
 7009: sub questions_to_line_list {
 7010:     my ($questions) = @_;
 7011:     my @lines;
 7012: 
 7013:     foreach my $item (@{$questions}) {
 7014:         my $question = $item;
 7015:         my ($first,$count,$last);
 7016:         if ($item =~ /^(\d+)\.(\d+)$/) {
 7017:             $question = $1;
 7018:             my $subquestion = $2;
 7019:             $first = $first_bubble_line{$question-1} + 1;
 7020:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7021:             my $subcount = 1;
 7022:             while ($subcount<$subquestion) {
 7023:                 $first += $subans[$subcount-1];
 7024:                 $subcount ++;
 7025:             }
 7026:             $count = $subans[$subquestion-1];
 7027:         } else {
 7028: 	    $first   = $first_bubble_line{$question-1} + 1;
 7029: 	    $count   = $bubble_lines_per_response{$question-1};
 7030:         }
 7031:         $last = $first+$count-1;
 7032:         push(@lines, ($first..$last));
 7033:     }
 7034:     return join(',', @lines);
 7035: }
 7036: 
 7037: =pod 
 7038: 
 7039: =item prompt_for_corrections
 7040: 
 7041: Prompts for a potentially multiline correction to the
 7042: user's bubbling (factors out common code from scantron_get_correction
 7043: for multi and missing bubble cases).
 7044: 
 7045:  Arguments:
 7046:    $r           - Apache request object.
 7047:    $question    - The question number to prompt for.
 7048:    $scan_config - The scantron file configuration hash.
 7049:    $scan_record - Reference to the hash that has the the parsed scanlines.
 7050:    $error       - Type of error
 7051: 
 7052:  Implicit inputs:
 7053:    %bubble_lines_per_response   - Starting line numbers for each question.
 7054:                                   Numbered from 0 (but question numbers are from
 7055:                                   1.
 7056:    %first_bubble_line           - Starting bubble line for each question.
 7057:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 7058:                                   type problems render as separate sub-questions, 
 7059:                                   in exam mode. This hash contains a 
 7060:                                   comma-separated list of the lines per 
 7061:                                   sub-question.
 7062:    %responsetype_per_response   - essayresponse, formularesponse,
 7063:                                   stringresponse, imageresponse, reactionresponse,
 7064:                                   and organicresponse type problem parts can have
 7065:                                   multiple lines per response if the weight
 7066:                                   assigned exceeds 10.  In this case, only
 7067:                                   one bubble per line is permitted, but more 
 7068:                                   than one line might contain bubbles, e.g.
 7069:                                   bubbling of: line 1 - J, line 2 - J, 
 7070:                                   line 3 - B would assign 22 points.  
 7071: 
 7072: =cut
 7073: 
 7074: sub prompt_for_corrections {
 7075:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
 7076:     my ($current_line,$lines);
 7077:     my @linenums;
 7078:     my $questionnum = $question;
 7079:     if ($question =~ /^(\d+)\.(\d+)$/) {
 7080:         $question = $1;
 7081:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7082:         my $subquestion = $2;
 7083:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7084:         my $subcount = 1;
 7085:         while ($subcount<$subquestion) {
 7086:             $current_line += $subans[$subcount-1];
 7087:             $subcount ++;
 7088:         }
 7089:         $lines = $subans[$subquestion-1];
 7090:     } else {
 7091:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7092:         $lines        = $bubble_lines_per_response{$question-1};
 7093:     }
 7094:     if ($lines > 1) {
 7095:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 7096:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
 7097:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
 7098:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
 7099:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
 7100:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
 7101:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
 7102:             $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 />');
 7103:         } else {
 7104:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 7105:         }
 7106:     }
 7107:     for (my $i =0; $i < $lines; $i++) {
 7108:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 7109: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
 7110: 	        		  $questionnum,$error,split('', $selected));
 7111:         push(@linenums,$current_line);
 7112: 	$current_line++;
 7113:     }
 7114:     if ($lines > 1) {
 7115: 	$r->print("<hr /><br />");
 7116:     }
 7117:     return @linenums;
 7118: }
 7119: 
 7120: =pod
 7121: 
 7122: =item scantron_bubble_selector
 7123:   
 7124:    Generates the html radiobuttons to correct a single bubble line
 7125:    possibly showing the existing the selected bubbles if known
 7126: 
 7127:  Arguments:
 7128:     $r           - Apache request object
 7129:     $scan_config - hash from &get_scantron_config()
 7130:     $line        - Number of the line being displayed.
 7131:     $questionnum - Question number (may include subquestion)
 7132:     $error       - Type of error.
 7133:     @selected    - Array of bubbles picked on this line.
 7134: 
 7135: =cut
 7136: 
 7137: sub scantron_bubble_selector {
 7138:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 7139:     my $max=$$scan_config{'Qlength'};
 7140: 
 7141:     my $scmode=$$scan_config{'Qon'};
 7142:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
 7143: 
 7144:     my @alphabet=('A'..'Z');
 7145:     $r->print(&Apache::loncommon::start_data_table().
 7146:               &Apache::loncommon::start_data_table_row());
 7147:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 7148:     for (my $i=0;$i<$max+1;$i++) {
 7149: 	$r->print("\n".'<td align="center">');
 7150: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 7151: 	else { $r->print('&nbsp;'); }
 7152: 	$r->print('</td>');
 7153:     }
 7154:     $r->print(&Apache::loncommon::end_data_table_row().
 7155:               &Apache::loncommon::start_data_table_row());
 7156:     for (my $i=0;$i<$max;$i++) {
 7157: 	$r->print("\n".
 7158: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 7159: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 7160:     }
 7161:     my $nobub_checked = ' ';
 7162:     if ($error eq 'missingbubble') {
 7163:         $nobub_checked = ' checked = "checked" ';
 7164:     }
 7165:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 7166: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 7167:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 7168:               $line.'" value="'.$questionnum.'" /></td>');
 7169:     $r->print(&Apache::loncommon::end_data_table_row().
 7170:               &Apache::loncommon::end_data_table());
 7171: }
 7172: 
 7173: =pod
 7174: 
 7175: =item num_matches
 7176: 
 7177:    Counts the number of characters that are the same between the two arguments.
 7178: 
 7179:  Arguments:
 7180:    $orig - CODE from the scanline
 7181:    $code - CODE to match against
 7182: 
 7183:  Returns:
 7184:    $count - integer count of the number of same characters between the
 7185:             two arguments
 7186: 
 7187: =cut
 7188: 
 7189: sub num_matches {
 7190:     my ($orig,$code) = @_;
 7191:     my @code=split(//,$code);
 7192:     my @orig=split(//,$orig);
 7193:     my $same=0;
 7194:     for (my $i=0;$i<scalar(@code);$i++) {
 7195: 	if ($code[$i] eq $orig[$i]) { $same++; }
 7196:     }
 7197:     return $same;
 7198: }
 7199: 
 7200: =pod
 7201: 
 7202: =item scantron_get_closely_matching_CODEs
 7203: 
 7204:    Cycles through all CODEs and finds the set that has the greatest
 7205:    number of same characters as the provided CODE
 7206: 
 7207:  Arguments:
 7208:    $allcodes - hash ref returned by &get_codes()
 7209:    $CODE     - CODE from the current scanline
 7210: 
 7211:  Returns:
 7212:    2 element list
 7213:     - first elements is number of how closely matching the best fit is 
 7214:       (5 means best set has 5 matching characters)
 7215:     - second element is an arrary ref containing the set of valid CODEs
 7216:       that best fit the passed in CODE
 7217: 
 7218: =cut
 7219: 
 7220: sub scantron_get_closely_matching_CODEs {
 7221:     my ($allcodes,$CODE)=@_;
 7222:     my @CODEs;
 7223:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 7224: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 7225:     }
 7226: 
 7227:     return ($#CODEs,$CODEs[-1]);
 7228: }
 7229: 
 7230: =pod
 7231: 
 7232: =item get_codes
 7233: 
 7234:    Builds a hash which has keys of all of the valid CODEs from the selected
 7235:    set of remembered CODEs.
 7236: 
 7237:  Arguments:
 7238:   $old_name - name of the set of remembered CODEs
 7239:   $cdom     - domain of the course
 7240:   $cnum     - internal course name
 7241: 
 7242:  Returns:
 7243:   %allcodes - keys are the valid CODEs, values are all 1
 7244: 
 7245: =cut
 7246: 
 7247: sub get_codes {
 7248:     my ($old_name, $cdom, $cnum) = @_;
 7249:     if (!$old_name) {
 7250: 	$old_name=$env{'form.scantron_CODElist'};
 7251:     }
 7252:     if (!$cdom) {
 7253: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 7254:     }
 7255:     if (!$cnum) {
 7256: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 7257:     }
 7258:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 7259: 				    $cdom,$cnum);
 7260:     my %allcodes;
 7261:     if ($result{"type\0$old_name"} eq 'number') {
 7262: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 7263:     } else {
 7264: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 7265:     }
 7266:     return %allcodes;
 7267: }
 7268: 
 7269: =pod
 7270: 
 7271: =item scantron_validate_CODE
 7272: 
 7273:    Validates all scanlines in the selected file to not have any
 7274:    invalid or underspecified CODEs and that none of the codes are
 7275:    duplicated if this was requested.
 7276: 
 7277: =cut
 7278: 
 7279: sub scantron_validate_CODE {
 7280:     my ($r,$currentphase) = @_;
 7281:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7282:     if ($scantron_config{'CODElocation'} &&
 7283: 	$scantron_config{'CODEstart'} &&
 7284: 	$scantron_config{'CODElength'}) {
 7285: 	if (!defined($env{'form.scantron_CODElist'})) {
 7286: 	    &FIXME_blow_up()
 7287: 	}
 7288:     } else {
 7289: 	return (0,$currentphase+1);
 7290:     }
 7291:     
 7292:     my %usedCODEs;
 7293: 
 7294:     my %allcodes=&get_codes();
 7295: 
 7296:     my $nav_error;
 7297:     &scantron_get_maxbubble(\$nav_error); # parse needs the lines per response array.
 7298:     if ($nav_error) {
 7299:         $r->print(&navmap_errormsg());
 7300:         return(1,$currentphase);
 7301:     }
 7302: 
 7303:     my ($scanlines,$scan_data)=&scantron_getfile();
 7304:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7305: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7306: 	if ($line=~/^[\s\cz]*$/) { next; }
 7307: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7308: 						 $scan_data);
 7309: 	my $CODE=$$scan_record{'scantron.CODE'};
 7310: 	my $error=0;
 7311: 	if (!&Apache::lonnet::validCODE($CODE)) {
 7312: 	    &scantron_get_correction($r,$i,$scan_record,
 7313: 				     \%scantron_config,
 7314: 				     $line,'incorrectCODE',\%allcodes);
 7315: 	    return(1,$currentphase);
 7316: 	}
 7317: 	if (%allcodes && !exists($allcodes{$CODE}) 
 7318: 	    && !$$scan_record{'scantron.useCODE'}) {
 7319: 	    &scantron_get_correction($r,$i,$scan_record,
 7320: 				     \%scantron_config,
 7321: 				     $line,'incorrectCODE',\%allcodes);
 7322: 	    return(1,$currentphase);
 7323: 	}
 7324: 	if (exists($usedCODEs{$CODE}) 
 7325: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 7326: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 7327: 	    &scantron_get_correction($r,$i,$scan_record,
 7328: 				     \%scantron_config,
 7329: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 7330: 	    return(1,$currentphase);
 7331: 	}
 7332: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 7333:     }
 7334:     return (0,$currentphase+1);
 7335: }
 7336: 
 7337: =pod
 7338: 
 7339: =item scantron_validate_doublebubble
 7340: 
 7341:    Validates all scanlines in the selected file to not have any
 7342:    bubble lines with multiple bubbles marked.
 7343: 
 7344: =cut
 7345: 
 7346: sub scantron_validate_doublebubble {
 7347:     my ($r,$currentphase) = @_;
 7348:     #get student info
 7349:     my $classlist=&Apache::loncoursedata::get_classlist();
 7350:     my %idmap=&username_to_idmap($classlist);
 7351: 
 7352:     #get scantron line setup
 7353:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7354:     my ($scanlines,$scan_data)=&scantron_getfile();
 7355:     my $nav_error;
 7356:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble line array.
 7357:     if ($nav_error) {
 7358:         $r->print(&navmap_errormsg());
 7359:         return(1,$currentphase);
 7360:     }
 7361: 
 7362:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7363: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7364: 	if ($line=~/^[\s\cz]*$/) { next; }
 7365: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7366: 						 $scan_data);
 7367: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 7368: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 7369: 				 'doublebubble',
 7370: 				 $$scan_record{'scantron.doubleerror'});
 7371:     	return (1,$currentphase);
 7372:     }
 7373:     return (0,$currentphase+1);
 7374: }
 7375: 
 7376: 
 7377: sub scantron_get_maxbubble {
 7378:     my ($nav_error) = @_;
 7379:     if (defined($env{'form.scantron_maxbubble'}) &&
 7380: 	$env{'form.scantron_maxbubble'}) {
 7381: 	&restore_bubble_lines();
 7382: 	return $env{'form.scantron_maxbubble'};
 7383:     }
 7384: 
 7385:     my (undef, undef, $sequence) =
 7386: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7387: 
 7388:     my $navmap=Apache::lonnavmaps::navmap->new();
 7389:     unless (ref($navmap)) {
 7390:         if (ref($nav_error)) {
 7391:             $$nav_error = 1;
 7392:         }
 7393:         return;
 7394:     }
 7395:     my $map=$navmap->getResourceByUrl($sequence);
 7396:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7397: 
 7398:     &Apache::lonxml::clear_problem_counter();
 7399: 
 7400:     my $uname       = $env{'user.name'};
 7401:     my $udom        = $env{'user.domain'};
 7402:     my $cid         = $env{'request.course.id'};
 7403:     my $total_lines = 0;
 7404:     %bubble_lines_per_response = ();
 7405:     %first_bubble_line         = ();
 7406:     %subdivided_bubble_lines   = ();
 7407:     %responsetype_per_response = ();
 7408: 
 7409:     my $response_number = 0;
 7410:     my $bubble_line     = 0;
 7411:     foreach my $resource (@resources) {
 7412:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom);
 7413:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 7414: 	    foreach my $part_id (@{$parts}) {
 7415:                 my $lines;
 7416: 
 7417: 	        # TODO - make this a persistent hash not an array.
 7418: 
 7419:                 # optionresponse, matchresponse and rankresponse type items 
 7420:                 # render as separate sub-questions in exam mode.
 7421:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 7422:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 7423:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 7424:                     my ($numbub,$numshown);
 7425:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 7426:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 7427:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 7428:                         }
 7429:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 7430:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 7431:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 7432:                         }
 7433:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 7434:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 7435:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 7436:                         }
 7437:                     }
 7438:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 7439:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 7440:                     }
 7441:                     my $bubbles_per_line = 10;
 7442:                     my $inner_bubble_lines = int($numbub/$bubbles_per_line);
 7443:                     if (($numbub % $bubbles_per_line) != 0) {
 7444:                         $inner_bubble_lines++;
 7445:                     }
 7446:                     for (my $i=0; $i<$numshown; $i++) {
 7447:                         $subdivided_bubble_lines{$response_number} .= 
 7448:                             $inner_bubble_lines.',';
 7449:                     }
 7450:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 7451:                     $lines = $numshown * $inner_bubble_lines;
 7452:                 } else {
 7453:                     $lines = $analysis->{"$part_id.bubble_lines"};
 7454:                 } 
 7455: 
 7456:                 $first_bubble_line{$response_number} = $bubble_line;
 7457: 	        $bubble_lines_per_response{$response_number} = $lines;
 7458:                 $responsetype_per_response{$response_number} = 
 7459:                     $analysis->{$part_id.'.type'};
 7460: 	        $response_number++;
 7461: 
 7462: 	        $bubble_line +=  $lines;
 7463: 	        $total_lines +=  $lines;
 7464: 	    }
 7465:         }
 7466:     }
 7467:     &Apache::lonnet::delenv('scantron.');
 7468: 
 7469:     &save_bubble_lines();
 7470:     $env{'form.scantron_maxbubble'} =
 7471: 	$total_lines;
 7472:     return $env{'form.scantron_maxbubble'};
 7473: }
 7474: 
 7475: sub scantron_validate_missingbubbles {
 7476:     my ($r,$currentphase) = @_;
 7477:     #get student info
 7478:     my $classlist=&Apache::loncoursedata::get_classlist();
 7479:     my %idmap=&username_to_idmap($classlist);
 7480: 
 7481:     #get scantron line setup
 7482:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7483:     my ($scanlines,$scan_data)=&scantron_getfile();
 7484:     my $nav_error;
 7485:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
 7486:     if ($nav_error) {
 7487:         return(1,$currentphase);
 7488:     }
 7489:     if (!$max_bubble) { $max_bubble=2**31; }
 7490:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7491: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7492: 	if ($line=~/^[\s\cz]*$/) { next; }
 7493: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7494: 						 $scan_data);
 7495: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 7496: 	my @to_correct;
 7497: 	
 7498: 	# Probably here's where the error is...
 7499: 
 7500: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 7501:             my $lastbubble;
 7502:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 7503:                my $question = $1;
 7504:                my $subquestion = $2;
 7505:                if (!defined($first_bubble_line{$question -1})) { next; }
 7506:                my $first = $first_bubble_line{$question-1};
 7507:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7508:                my $subcount = 1;
 7509:                while ($subcount<$subquestion) {
 7510:                    $first += $subans[$subcount-1];
 7511:                    $subcount ++;
 7512:                }
 7513:                my $count = $subans[$subquestion-1];
 7514:                $lastbubble = $first + $count;
 7515:             } else {
 7516:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
 7517:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
 7518:             }
 7519:             if ($lastbubble > $max_bubble) { next; }
 7520: 	    push(@to_correct,$missing);
 7521: 	}
 7522: 	if (@to_correct) {
 7523: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7524: 				     $line,'missingbubble',\@to_correct);
 7525: 	    return (1,$currentphase);
 7526: 	}
 7527: 
 7528:     }
 7529:     return (0,$currentphase+1);
 7530: }
 7531: 
 7532: 
 7533: sub scantron_process_students {
 7534:     my ($r,$symb) = @_;
 7535: 
 7536:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7537:     if (!$symb) {
 7538: 	return '';
 7539:     }
 7540:     my $default_form_data=&defaultFormData($symb);
 7541: 
 7542:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7543:     my ($scanlines,$scan_data)=&scantron_getfile();
 7544:     my $classlist=&Apache::loncoursedata::get_classlist();
 7545:     my %idmap=&username_to_idmap($classlist);
 7546:     my $navmap=Apache::lonnavmaps::navmap->new();
 7547:     unless (ref($navmap)) {
 7548:         $r->print(&navmap_errormsg());
 7549:         return '';
 7550:     }  
 7551:     my $map=$navmap->getResourceByUrl($sequence);
 7552:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7553:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
 7554:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 7555:                             \%grader_randomlists_by_symb);
 7556:     my $resource_error;
 7557:     foreach my $resource (@resources) {
 7558:         my $ressymb;
 7559:         if (ref($resource)) {
 7560:             $ressymb = $resource->symb();
 7561:         } else {
 7562:             $resource_error = 1;
 7563:             last;
 7564:         }
 7565:         my ($analysis,$parts) =
 7566:             &scantron_partids_tograde($resource,$env{'request.course.id'},
 7567:                                       $env{'user.name'},$env{'user.domain'},1);
 7568:         $grader_partids_by_symb{$ressymb} = $parts;
 7569:         if (ref($analysis) eq 'HASH') {
 7570:             if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 7571:                 $grader_randomlists_by_symb{$ressymb} = 
 7572:                     $analysis->{'parts_withrandomlist'};
 7573:             }
 7574:         }
 7575:     }
 7576:     if ($resource_error) {
 7577:         $r->print(&navmap_errormsg());
 7578:         return '';
 7579:     }
 7580: 
 7581:     my ($uname,$udom);
 7582:     my $result= <<SCANTRONFORM;
 7583: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 7584:   <input type="hidden" name="command" value="scantron_configphase" />
 7585:   $default_form_data
 7586: SCANTRONFORM
 7587:     $r->print($result);
 7588: 
 7589:     my @delayqueue;
 7590:     my (%completedstudents,%scandata);
 7591:     
 7592:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 7593:     my $count=&get_todo_count($scanlines,$scan_data);
 7594:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet Status',
 7595:  				    'Bubblesheet Progress',$count,
 7596: 				    'inline',undef,'scantronupload');
 7597:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 7598: 					  'Processing first student');
 7599:     $r->print('<br />');
 7600:     my $start=&Time::HiRes::time();
 7601:     my $i=-1;
 7602:     my $started;
 7603: 
 7604:     my $nav_error;
 7605:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
 7606:     if ($nav_error) {
 7607:         $r->print(&navmap_errormsg());
 7608:         return '';
 7609:     }
 7610: 
 7611:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 7612:     # the user and return.
 7613: 
 7614:     if ($ssi_error) {
 7615: 	$r->print("</form>");
 7616: 	&ssi_print_error($r);
 7617:         &Apache::lonnet::remove_lock($lock);
 7618: 	return '';		# Dunno why the other returns return '' rather than just returning.
 7619:     }
 7620: 
 7621:     my %lettdig = &letter_to_digits();
 7622:     my $numletts = scalar(keys(%lettdig));
 7623: 
 7624:     while ($i<$scanlines->{'count'}) {
 7625:  	($uname,$udom)=('','');
 7626:  	$i++;
 7627:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7628:  	if ($line=~/^[\s\cz]*$/) { next; }
 7629: 	if ($started) {
 7630: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 7631: 						     'last student');
 7632: 	}
 7633: 	$started=1;
 7634:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7635:  						 $scan_data);
 7636:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 7637:  					      \%idmap,$i)) {
 7638:   	    &scantron_add_delay(\@delayqueue,$line,
 7639:  				'Unable to find a student that matches',1);
 7640:  	    next;
 7641:   	}
 7642:  	if (exists $completedstudents{$uname}) {
 7643:  	    &scantron_add_delay(\@delayqueue,$line,
 7644:  				'Student '.$uname.' has multiple sheets',2);
 7645:  	    next;
 7646:  	}
 7647:   	($uname,$udom)=split(/:/,$uname);
 7648: 
 7649:         my (%partids_by_symb,$res_error);
 7650:         foreach my $resource (@resources) {
 7651:             my $ressymb;
 7652:             if (ref($resource)) {
 7653:                 $ressymb = $resource->symb();
 7654:             } else {
 7655:                 $res_error = 1;
 7656:                 last;
 7657:             }
 7658:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 7659:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 7660:                 my ($analysis,$parts) =
 7661:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom);
 7662:                 $partids_by_symb{$ressymb} = $parts;
 7663:             } else {
 7664:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
 7665:             }
 7666:         }
 7667: 
 7668:         if ($res_error) {
 7669:             &scantron_add_delay(\@delayqueue,$line,
 7670:                                 'An error occurred while grading student '.$uname,2);
 7671:             next;
 7672:         }
 7673: 
 7674: 	&Apache::lonxml::clear_problem_counter();
 7675:   	&Apache::lonnet::appenv($scan_record);
 7676: 
 7677: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 7678: 	    &scantron_putfile($scanlines,$scan_data);
 7679: 	}
 7680: 	
 7681:         my $scancode;
 7682:         if ((exists($scan_record->{'scantron.CODE'})) &&
 7683:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 7684:             $scancode = $scan_record->{'scantron.CODE'};
 7685:         } else {
 7686:             $scancode = '';
 7687:         }
 7688: 
 7689:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 7690:                                    \@resources,\%partids_by_symb) eq 'ssi_error') {
 7691:             $ssi_error = 0; # So end of handler error message does not trigger.
 7692:             $r->print("</form>");
 7693:             &ssi_print_error($r);
 7694:             &Apache::lonnet::remove_lock($lock);
 7695:             return '';      # Why return ''?  Beats me.
 7696:         }
 7697: 
 7698: 	$completedstudents{$uname}={'line'=>$line};
 7699:         if ($env{'form.verifyrecord'}) {
 7700:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 7701:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 7702:             chomp($studentdata);
 7703:             $studentdata =~ s/\r$//;
 7704:             my $studentrecord = '';
 7705:             my $counter = -1;
 7706:             foreach my $resource (@resources) {
 7707:                 my $ressymb = $resource->symb();
 7708:                 ($counter,my $recording) =
 7709:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 7710:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
 7711:                                              \%scantron_config,\%lettdig,$numletts);
 7712:                 $studentrecord .= $recording;
 7713:             }
 7714:             if ($studentrecord ne $studentdata) {
 7715:                 &Apache::lonxml::clear_problem_counter();
 7716:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 7717:                                            \@resources,\%partids_by_symb) eq 'ssi_error') {
 7718:                     $ssi_error = 0; # So end of handler error message does not trigger.
 7719:                     $r->print("</form>");
 7720:                     &ssi_print_error($r);
 7721:                     &Apache::lonnet::remove_lock($lock);
 7722:                     delete($completedstudents{$uname});
 7723:                     return '';
 7724:                 }
 7725:                 $counter = -1;
 7726:                 $studentrecord = '';
 7727:                 foreach my $resource (@resources) {
 7728:                     my $ressymb = $resource->symb();
 7729:                     ($counter,my $recording) =
 7730:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 7731:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 7732:                                                  \%scantron_config,\%lettdig,$numletts);
 7733:                     $studentrecord .= $recording;
 7734:                 }
 7735:                 if ($studentrecord ne $studentdata) {
 7736:                     $r->print('<p><span class="LC_error">');
 7737:                     if ($scancode eq '') {
 7738:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2].',
 7739:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 7740:                     } else {
 7741:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2] and CODE: [_3].',
 7742:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 7743:                     }
 7744:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 7745:                               &Apache::loncommon::start_data_table_header_row()."\n".
 7746:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 7747:                               &Apache::loncommon::end_data_table_header_row()."\n".
 7748:                               &Apache::loncommon::start_data_table_row().
 7749:                               '<td>'.&mt('Bubble Sheet').'</td>'.
 7750:                               '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
 7751:                               &Apache::loncommon::end_data_table_row().
 7752:                               &Apache::loncommon::start_data_table_row().
 7753:                               '<td>Stored submissions</td>'.
 7754:                               '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
 7755:                               &Apache::loncommon::end_data_table_row().
 7756:                               &Apache::loncommon::end_data_table().'</p>');
 7757:                 } else {
 7758:                     $r->print('<br /><span class="LC_warning">'.
 7759:                              &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 />'.
 7760:                              &mt("As a consequence, this user's submission history records two tries.").
 7761:                                  '</span><br />');
 7762:                 }
 7763:             }
 7764:         }
 7765:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 7766:     } continue {
 7767: 	&Apache::lonxml::clear_problem_counter();
 7768: 	&Apache::lonnet::delenv('scantron.');
 7769:     }
 7770:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 7771:     &Apache::lonnet::remove_lock($lock);
 7772: #    my $lasttime = &Time::HiRes::time()-$start;
 7773: #    $r->print("<p>took $lasttime</p>");
 7774: 
 7775:     $r->print("</form>");
 7776:     return '';
 7777: }
 7778: 
 7779: sub graders_resources_pass {
 7780:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb) = @_;
 7781:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
 7782:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
 7783:         foreach my $resource (@{$resources}) {
 7784:             my $ressymb = $resource->symb();
 7785:             my ($analysis,$parts) =
 7786:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
 7787:                                           $env{'user.name'},$env{'user.domain'},1);
 7788:             $grader_partids_by_symb->{$ressymb} = $parts;
 7789:             if (ref($analysis) eq 'HASH') {
 7790:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 7791:                     $grader_randomlists_by_symb->{$ressymb} =
 7792:                         $analysis->{'parts_withrandomlist'};
 7793:                 }
 7794:             }
 7795:         }
 7796:     }
 7797:     return;
 7798: }
 7799: 
 7800: sub grade_student_bubbles {
 7801:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts) = @_;
 7802:     if (ref($resources) eq 'ARRAY') {
 7803:         my $count = 0;
 7804:         foreach my $resource (@{$resources}) {
 7805:             my $ressymb = $resource->symb();
 7806:             my %form = ('submitted'      => 'scantron',
 7807:                         'grade_target'   => 'grade',
 7808:                         'grade_username' => $uname,
 7809:                         'grade_domain'   => $udom,
 7810:                         'grade_courseid' => $env{'request.course.id'},
 7811:                         'grade_symb'     => $ressymb,
 7812:                         'CODE'           => $scancode
 7813:                        );
 7814:             if (ref($parts) eq 'HASH') {
 7815:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 7816:                     foreach my $part (@{$parts->{$ressymb}}) {
 7817:                         $form{'scantron_questnum_start.'.$part} =
 7818:                             1+$env{'form.scantron.first_bubble_line.'.$count};
 7819:                         $count++;
 7820:                     }
 7821:                 }
 7822:             }
 7823:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 7824:             return 'ssi_error' if ($ssi_error);
 7825:             last if (&Apache::loncommon::connection_aborted($r));
 7826:         }
 7827:     }
 7828:     return;
 7829: }
 7830: 
 7831: sub scantron_upload_scantron_data {
 7832:     my ($r,$symb)=@_;
 7833:     my $dom = $env{'request.role.domain'};
 7834:     my $domdesc = &Apache::lonnet::domain($dom,'description');
 7835:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
 7836:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 7837: 							  'domainid',
 7838: 							  'coursename',$dom);
 7839:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
 7840:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
 7841:     my $default_form_data=&defaultFormData($symb);
 7842:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
 7843:     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.");
 7844:     $r->print(&Apache::lonhtmlcommon::scripttag('
 7845:     function checkUpload(formname) {
 7846: 	if (formname.upfile.value == "") {
 7847: 	    alert("'.$nofile_alert.'");
 7848: 	    return false;
 7849: 	}
 7850:         if (formname.courseid.value == "") {
 7851:             alert("'.$nocourseid_alert.'");
 7852:             return false;
 7853:         }
 7854: 	formname.submit();
 7855:     }
 7856: 
 7857:     function ToSyllabus() {
 7858:         var cdom = '."'$dom'".';
 7859:         var cnum = document.rules.courseid.value;
 7860:         if (cdom == "" || cdom == null) {
 7861:             return;
 7862:         }
 7863:         if (cnum == "" || cnum == null) {
 7864:            return;
 7865:         }
 7866:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
 7867:                             "height=350,width=350,scrollbars=yes,menubar=no");
 7868:         return;
 7869:     }
 7870: 
 7871: '));
 7872:     $r->print('
 7873: <h3>'.&mt('Send scanned bubblesheet data to a course').'</h3>
 7874: 
 7875: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 7876: '.$default_form_data.
 7877:   &Apache::lonhtmlcommon::start_pick_box().
 7878:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
 7879:   '<input name="courseid" type="text" size="30" />'.$select_link.
 7880:   &Apache::lonhtmlcommon::row_closure().
 7881:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
 7882:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
 7883:   &Apache::lonhtmlcommon::row_closure().
 7884:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
 7885:   '<input name="domainid" type="hidden" />'.$domdesc.
 7886:   &Apache::lonhtmlcommon::row_closure().
 7887:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
 7888:   '<input type="file" name="upfile" size="50" />'.
 7889:   &Apache::lonhtmlcommon::row_closure(1).
 7890:   &Apache::lonhtmlcommon::end_pick_box().'<br />
 7891: 
 7892: <input name="command" value="scantronupload_save" type="hidden" />
 7893: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 7894: </form>
 7895: ');
 7896:     return '';
 7897: }
 7898: 
 7899: 
 7900: sub scantron_upload_scantron_data_save {
 7901:     my($r,$symb)=@_;
 7902:     my $doanotherupload=
 7903: 	'<br /><form action="/adm/grades" method="post">'."\n".
 7904: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 7905: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 7906: 	'</form>'."\n";
 7907:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 7908: 	!&Apache::lonnet::allowed('usc',
 7909: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 7910: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
 7911: 	unless ($symb) {
 7912: 	    $r->print($doanotherupload);
 7913: 	}
 7914: 	return '';
 7915:     }
 7916:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 7917:     my $uploadedfile;
 7918:     $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
 7919:     if (length($env{'form.upfile'}) < 2) {
 7920:         $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>'));
 7921:     } else {
 7922:         my $result = 
 7923:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
 7924:                                             $env{'form.courseid'},$env{'form.domainid'});
 7925: 	if ($result =~ m{^/uploaded/}) {
 7926: 	    $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
 7927:                           '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
 7928: 			  '<span class="LC_filename">'.$result.'</span>'));
 7929:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
 7930:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
 7931:                                                        $env{'form.courseid'},$uploadedfile));
 7932: 	} else {
 7933: 	    $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
 7934:                           '<span class="LC_error">','</span>',$result,
 7935: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 7936: 	}
 7937:     }
 7938:     if ($symb) {
 7939: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
 7940:     } else {
 7941: 	$r->print($doanotherupload);
 7942:     }
 7943:     return '';
 7944: }
 7945: 
 7946: sub validate_uploaded_scantron_file {
 7947:     my ($cdom,$cname,$fname) = @_;
 7948:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
 7949:     my @lines;
 7950:     if ($scanlines ne '-1') {
 7951:         @lines=split("\n",$scanlines,-1);
 7952:     }
 7953:     my $output;
 7954:     if (@lines) {
 7955:         my (%counts,$max_match_format);
 7956:         my ($max_match_count,$max_match_pct) = (0,0);
 7957:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
 7958:         my %idmap = &username_to_idmap($classlist);
 7959:         foreach my $key (keys(%idmap)) {
 7960:             my $lckey = lc($key);
 7961:             $idmap{$lckey} = $idmap{$key};
 7962:         }
 7963:         my %unique_formats;
 7964:         my @formatlines = &get_scantronformat_file();
 7965:         foreach my $line (@formatlines) {
 7966:             chomp($line);
 7967:             my @config = split(/:/,$line);
 7968:             my $idstart = $config[5];
 7969:             my $idlength = $config[6];
 7970:             if (($idstart ne '') && ($idlength > 0)) {
 7971:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
 7972:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
 7973:                 } else {
 7974:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
 7975:                 }
 7976:             }
 7977:         }
 7978:         foreach my $key (keys(%unique_formats)) {
 7979:             my ($idstart,$idlength) = split(':',$key);
 7980:             %{$counts{$key}} = (
 7981:                                'found'   => 0,
 7982:                                'total'   => 0,
 7983:                               );
 7984:             foreach my $line (@lines) {
 7985:                 next if ($line =~ /^#/);
 7986:                 next if ($line =~ /^[\s\cz]*$/);
 7987:                 my $id = substr($line,$idstart-1,$idlength);
 7988:                 $id = lc($id);
 7989:                 if (exists($idmap{$id})) {
 7990:                     $counts{$key}{'found'} ++;
 7991:                 }
 7992:                 $counts{$key}{'total'} ++;
 7993:             }
 7994:             if ($counts{$key}{'total'}) {
 7995:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
 7996:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
 7997:                     $max_match_pct = $percent_match;
 7998:                     $max_match_format = $key;
 7999:                     $max_match_count = $counts{$key}{'total'};
 8000:                 }
 8001:             }
 8002:         }
 8003:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
 8004:             my $format_descs;
 8005:             my $numwithformat = @{$unique_formats{$max_match_format}};
 8006:             for (my $i=0; $i<$numwithformat; $i++) {
 8007:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
 8008:                 if ($i<$numwithformat-2) {
 8009:                     $format_descs .= '"<i>'.$desc.'</i>", ';
 8010:                 } elsif ($i==$numwithformat-2) {
 8011:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
 8012:                 } elsif ($i==$numwithformat-1) {
 8013:                     $format_descs .= '"<i>'.$desc.'</i>"';
 8014:                 }
 8015:             }
 8016:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
 8017:             $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).
 8018:                        '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
 8019:                        '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
 8020:                        '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
 8021:                                   '<i>'.$cdom.'</i>').'</li>'.
 8022:                        '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
 8023:                        '<li>'.&mt('The course roster is not up to date').'</li>'.
 8024:                        '</ul>';
 8025:         }
 8026:     } else {
 8027:         $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
 8028:     }
 8029:     return $output;
 8030: }
 8031: 
 8032: sub valid_file {
 8033:     my ($requested_file)=@_;
 8034:     foreach my $filename (sort(&scantron_filenames())) {
 8035: 	if ($requested_file eq $filename) { return 1; }
 8036:     }
 8037:     return 0;
 8038: }
 8039: 
 8040: sub scantron_download_scantron_data {
 8041:     my ($r,$symb)=@_;
 8042:     my $default_form_data=&defaultFormData($symb);
 8043:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 8044:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8045:     my $file=$env{'form.scantron_selectfile'};
 8046:     if (! &valid_file($file)) {
 8047: 	$r->print('
 8048: 	<p>
 8049: 	    '.&mt('The requested file name was invalid.').'
 8050:         </p>
 8051: ');
 8052: 	return;
 8053:     }
 8054:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 8055:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 8056:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 8057:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 8058:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 8059:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 8060:     $r->print('
 8061:     <p>
 8062: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
 8063: 	      '<a href="'.$orig.'">','</a>').'
 8064:     </p>
 8065:     <p>
 8066: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 8067: 	      '<a href="'.$corrected.'">','</a>').'
 8068:     </p>
 8069:     <p>
 8070: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 8071: 	      '<a href="'.$skipped.'">','</a>').'
 8072:     </p>
 8073: ');
 8074:     return '';
 8075: }
 8076: 
 8077: sub checkscantron_results {
 8078:     my ($r,$symb) = @_;
 8079:     if (!$symb) {return '';}
 8080:     my $cid = $env{'request.course.id'};
 8081:     my %lettdig = &letter_to_digits();
 8082:     my $numletts = scalar(keys(%lettdig));
 8083:     my $cnum = $env{'course.'.$cid.'.num'};
 8084:     my $cdom = $env{'course.'.$cid.'.domain'};
 8085:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8086:     my %record;
 8087:     my %scantron_config =
 8088:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
 8089:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
 8090:     my $classlist=&Apache::loncoursedata::get_classlist();
 8091:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 8092:     my $navmap=Apache::lonnavmaps::navmap->new();
 8093:     unless (ref($navmap)) {
 8094:         $r->print(&navmap_errormsg());
 8095:         return '';
 8096:     }
 8097:     my $map=$navmap->getResourceByUrl($sequence);
 8098:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8099:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
 8100:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,                             \%grader_randomlists_by_symb);
 8101: 
 8102:     my ($uname,$udom);
 8103:     my (%scandata,%lastname,%bylast);
 8104:     $r->print('
 8105: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 8106: 
 8107:     my @delayqueue;
 8108:     my %completedstudents;
 8109: 
 8110:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
 8111:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet/Submissions Comparison Status',
 8112:                                     'Progress of Bubblesheet Data/Submission Records Comparison',$count,
 8113:                                     'inline',undef,'checkscantron');
 8114:     my ($username,$domain,$started);
 8115:     my $nav_error;
 8116:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
 8117:     if ($nav_error) {
 8118:         $r->print(&navmap_errormsg());
 8119:         return '';
 8120:     }
 8121: 
 8122:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 8123:                                           'Processing first student');
 8124:     my $start=&Time::HiRes::time();
 8125:     my $i=-1;
 8126: 
 8127:     while ($i<$scanlines->{'count'}) {
 8128:         ($username,$domain,$uname)=('','','');
 8129:         $i++;
 8130:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 8131:         if ($line=~/^[\s\cz]*$/) { next; }
 8132:         if ($started) {
 8133:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 8134:                                                      'last student');
 8135:         }
 8136:         $started=1;
 8137:         my $scan_record=
 8138:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 8139:                                                      $scan_data);
 8140:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
 8141:                                                               \%idmap,$i)) {
 8142:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 8143:                                 'Unable to find a student that matches',1);
 8144:             next;
 8145:         }
 8146:         if (exists $completedstudents{$uname}) {
 8147:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 8148:                                 'Student '.$uname.' has multiple sheets',2);
 8149:             next;
 8150:         }
 8151:         my $pid = $scan_record->{'scantron.ID'};
 8152:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 8153:         push(@{$bylast{$lastname{$pid}}},$pid);
 8154:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 8155:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 8156:         chomp($scandata{$pid});
 8157:         $scandata{$pid} =~ s/\r$//;
 8158:         ($username,$domain)=split(/:/,$uname);
 8159:         my $counter = -1;
 8160:         foreach my $resource (@resources) {
 8161:             my $parts;
 8162:             my $ressymb = $resource->symb();
 8163:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 8164:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 8165:                 (my $analysis,$parts) =
 8166:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$username,$domain);
 8167:             } else {
 8168:                 $parts = $grader_partids_by_symb{$ressymb};
 8169:             }
 8170:             ($counter,my $recording) =
 8171:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
 8172:                                          $scandata{$pid},$parts,
 8173:                                          \%scantron_config,\%lettdig,$numletts);
 8174:             $record{$pid} .= $recording;
 8175:         }
 8176:     }
 8177:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 8178:     $r->print('<br />');
 8179:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 8180:     $passed = 0;
 8181:     $failed = 0;
 8182:     $numstudents = 0;
 8183:     foreach my $last (sort(keys(%bylast))) {
 8184:         if (ref($bylast{$last}) eq 'ARRAY') {
 8185:             foreach my $pid (sort(@{$bylast{$last}})) {
 8186:                 my $showscandata = $scandata{$pid};
 8187:                 my $showrecord = $record{$pid};
 8188:                 $showscandata =~ s/\s/&nbsp;/g;
 8189:                 $showrecord =~ s/\s/&nbsp;/g;
 8190:                 if ($scandata{$pid} eq $record{$pid}) {
 8191:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 8192:                     $okstudents .= '<tr class="'.$css_class.'">'.
 8193: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 8194: '</tr>'."\n".
 8195: '<tr class="'.$css_class.'">'."\n".
 8196: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
 8197:                     $passed ++;
 8198:                 } else {
 8199:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
 8200:                     $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".
 8201: '</tr>'."\n".
 8202: '<tr class="'.$css_class.'">'."\n".
 8203: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
 8204: '</tr>'."\n";
 8205:                     $failed ++;
 8206:                 }
 8207:                 $numstudents ++;
 8208:             }
 8209:         }
 8210:     }
 8211:     $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>');
 8212:     $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>');
 8213:     if ($passed) {
 8214:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
 8215:         $r->print(&Apache::loncommon::start_data_table()."\n".
 8216:                  &Apache::loncommon::start_data_table_header_row()."\n".
 8217:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 8218:                  &Apache::loncommon::end_data_table_header_row()."\n".
 8219:                  $okstudents."\n".
 8220:                  &Apache::loncommon::end_data_table().'<br />');
 8221:     }
 8222:     if ($failed) {
 8223:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
 8224:         $r->print(&Apache::loncommon::start_data_table()."\n".
 8225:                  &Apache::loncommon::start_data_table_header_row()."\n".
 8226:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 8227:                  &Apache::loncommon::end_data_table_header_row()."\n".
 8228:                  $badstudents."\n".
 8229:                  &Apache::loncommon::end_data_table()).'<br />'.
 8230:                  &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.');  
 8231:     }
 8232:     $r->print('</form><br />');
 8233:     return;
 8234: }
 8235: 
 8236: sub verify_scantron_grading {
 8237:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
 8238:         $scantron_config,$lettdig,$numletts) = @_;
 8239:     my ($record,%expected,%startpos);
 8240:     return ($counter,$record) if (!ref($resource));
 8241:     return ($counter,$record) if (!$resource->is_problem());
 8242:     my $symb = $resource->symb();
 8243:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
 8244:     foreach my $part_id (@{$partids}) {
 8245:         $counter ++;
 8246:         $expected{$part_id} = 0;
 8247:         if ($env{"form.scantron.sub_bubblelines.$counter"}) {
 8248:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
 8249:             foreach my $item (@sub_lines) {
 8250:                 $expected{$part_id} += $item;
 8251:             }
 8252:         } else {
 8253:             $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
 8254:         }
 8255:         $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
 8256:     }
 8257:     if ($symb) {
 8258:         my %recorded;
 8259:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
 8260:         if ($returnhash{'version'}) {
 8261:             my %lasthash=();
 8262:             my $version;
 8263:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 8264:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 8265:                     $lasthash{$key}=$returnhash{$version.':'.$key};
 8266:                 }
 8267:             }
 8268:             foreach my $key (keys(%lasthash)) {
 8269:                 if ($key =~ /\.scantron$/) {
 8270:                     my $value = &unescape($lasthash{$key});
 8271:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
 8272:                     if ($value eq '') {
 8273:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
 8274:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
 8275:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8276:                             }
 8277:                         }
 8278:                     } else {
 8279:                         my @tocheck;
 8280:                         my @items = split(//,$value);
 8281:                         if (($scantron_config->{'Qon'} eq 'letter') ||
 8282:                             ($scantron_config->{'Qon'} eq 'number')) {
 8283:                             if (@items < $expected{$part_id}) {
 8284:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
 8285:                                 my @singles = split(//,$fragment);
 8286:                                 foreach my $pos (@singles) {
 8287:                                     if ($pos eq ' ') {
 8288:                                         push(@tocheck,$pos);
 8289:                                     } else {
 8290:                                         my $next = shift(@items);
 8291:                                         push(@tocheck,$next);
 8292:                                     }
 8293:                                 }
 8294:                             } else {
 8295:                                 @tocheck = @items;
 8296:                             }
 8297:                             foreach my $letter (@tocheck) {
 8298:                                 if ($scantron_config->{'Qon'} eq 'letter') {
 8299:                                     if ($letter !~ /^[A-J]$/) {
 8300:                                         $letter = $scantron_config->{'Qoff'};
 8301:                                     }
 8302:                                     $recorded{$part_id} .= $letter;
 8303:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
 8304:                                     my $digit;
 8305:                                     if ($letter !~ /^[A-J]$/) {
 8306:                                         $digit = $scantron_config->{'Qoff'};
 8307:                                     } else {
 8308:                                         $digit = $lettdig->{$letter};
 8309:                                     }
 8310:                                     $recorded{$part_id} .= $digit;
 8311:                                 }
 8312:                             }
 8313:                         } else {
 8314:                             @tocheck = @items;
 8315:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
 8316:                                 my $curr_sub = shift(@tocheck);
 8317:                                 my $digit;
 8318:                                 if ($curr_sub =~ /^[A-J]$/) {
 8319:                                     $digit = $lettdig->{$curr_sub}-1;
 8320:                                 }
 8321:                                 if ($curr_sub eq 'J') {
 8322:                                     $digit += scalar($numletts);
 8323:                                 }
 8324:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 8325:                                     if ($j == $digit) {
 8326:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
 8327:                                     } else {
 8328:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8329:                                     }
 8330:                                 }
 8331:                             }
 8332:                         }
 8333:                     }
 8334:                 }
 8335:             }
 8336:         }
 8337:         foreach my $part_id (@{$partids}) {
 8338:             if ($recorded{$part_id} eq '') {
 8339:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
 8340:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 8341:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8342:                     }
 8343:                 }
 8344:             }
 8345:             $record .= $recorded{$part_id};
 8346:         }
 8347:     }
 8348:     return ($counter,$record);
 8349: }
 8350: 
 8351: sub letter_to_digits { 
 8352:     my %lettdig = (
 8353:                     A => 1,
 8354:                     B => 2,
 8355:                     C => 3,
 8356:                     D => 4,
 8357:                     E => 5,
 8358:                     F => 6,
 8359:                     G => 7,
 8360:                     H => 8,
 8361:                     I => 9,
 8362:                     J => 0,
 8363:                   );
 8364:     return %lettdig;
 8365: }
 8366: 
 8367: 
 8368: #-------- end of section for handling grading scantron forms -------
 8369: #
 8370: #-------------------------------------------------------------------
 8371: 
 8372: #-------------------------- Menu interface -------------------------
 8373: #
 8374: #--- Href with symb and command ---
 8375: 
 8376: sub href_symb_cmd {
 8377:     my ($symb,$cmd)=@_;
 8378:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&command='.$cmd;
 8379: }
 8380: 
 8381: sub grading_menu {
 8382:     my ($request,$symb) = @_;
 8383:     if (!$symb) {return '';}
 8384: 
 8385:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 8386:                   'command'=>'individual');
 8387:     
 8388:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8389: 
 8390:     $fields{'command'}='ungraded';
 8391:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8392: 
 8393:     $fields{'command'}='table';
 8394:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8395: 
 8396:     $fields{'command'}='all_for_one';
 8397:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8398: 
 8399:     $fields{'command'}='downloadfilesselect';
 8400:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8401: 
 8402:     $fields{'command'} = 'csvform';
 8403:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8404:     
 8405:     $fields{'command'} = 'processclicker';
 8406:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8407:     
 8408:     $fields{'command'} = 'scantron_selectphase';
 8409:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8410: 
 8411:     $fields{'command'} = 'initialverifyreceipt';
 8412:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8413:     
 8414:     my @menu = ({	categorytitle=>'Hand Grading',
 8415:             items =>[
 8416:                         {	linktext => 'Select individual students to grade',
 8417:                     		url => $url1a,
 8418:                     		permission => 'F',
 8419:                     		icon => 'edit-find-replace.png',
 8420:                     		linktitle => 'Grade current resource for a selection of students.'
 8421:                         }, 
 8422:                         {       linktext => 'Grade ungraded submissions.',
 8423:                                 url => $url1b,
 8424:                                 permission => 'F',
 8425:                                 icon => 'edit-find-replace.png',
 8426:                                 linktitle => 'Grade all submissions that have not been graded yet.'
 8427:                         },
 8428: 
 8429:                         {       linktext => 'Grading table',
 8430:                                 url => $url1c,
 8431:                                 permission => 'F',
 8432:                                 icon => 'edit-find-replace.png',
 8433:                                 linktitle => 'Grade current resource for all students.'
 8434:                         },
 8435:                         {       linktext => 'Grade page/folder for one student',
 8436:                                 url => $url1d,
 8437:                                 permission => 'F',
 8438:                                 icon => 'edit-find-replace.png',
 8439:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
 8440:                         },
 8441:                         {       linktext => 'Download submissions',
 8442:                                 url => $url1e,
 8443:                                 permission => 'F',
 8444:                                 icon => 'edit-find-replace.png',
 8445:                                 linktitle => 'Download all students submissions.'
 8446:                         }]},
 8447:                          { categorytitle=>'Automated Grading',
 8448:                items =>[
 8449: 
 8450:                 	    {	linktext => 'Upload Scores',
 8451:                     		url => $url2,
 8452:                     		permission => 'F',
 8453:                     		icon => 'uploadscores.png',
 8454:                     		linktitle => 'Specify a file containing the class scores for current resource.'
 8455:                 	    },
 8456:                 	    {	linktext => 'Process Clicker',
 8457:                     		url => $url3,
 8458:                     		permission => 'F',
 8459:                     		icon => 'addClickerInfoFile.png',
 8460:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
 8461:                 	    },
 8462:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
 8463:                     		url => $url4,
 8464:                     		permission => 'F',
 8465:                     		icon => 'stat.png',
 8466:                     		linktitle => 'Grade scantron exams, upload/download scantron data files, and review previously graded scantron exams.'
 8467:                 	    },
 8468:                             {   linktext => 'Verify Receipt Number',
 8469:                                 url => $url5,
 8470:                                 permission => 'F',
 8471:                                 icon => 'edit-find-replace.png',
 8472:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
 8473:                             }
 8474: 
 8475:                     ]
 8476:             });
 8477: 
 8478:     # Create the menu
 8479:     my $Str;
 8480:     $Str .= '<form method="post" action="" name="gradingMenu">';
 8481:     $Str .= '<input type="hidden" name="command" value="" />'.
 8482:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 8483: 
 8484:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
 8485:     return $Str;    
 8486: }
 8487: 
 8488: 
 8489: sub ungraded {
 8490:     my ($request)=@_;
 8491:     &submit_options($request);
 8492: }
 8493: 
 8494: sub submit_options_sequence {
 8495:     my ($request,$symb) = @_;
 8496:     if (!$symb) {return '';}
 8497:     &commonJSfunctions($request);
 8498:     my $result;
 8499: 
 8500:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8501:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 8502:     $result.='
 8503: <h2>
 8504:   '.&mt('Grade page/folder for one student').'
 8505: </h2>'.
 8506:             &selectfield(0).
 8507:             '<input type="hidden" name="command" value="pickStudentPage" />
 8508:             <div>
 8509:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 8510:             </div>
 8511:         </div>
 8512:   </form>';
 8513:     return $result;
 8514: }
 8515: 
 8516: sub submit_options_table {
 8517:     my ($request,$symb) = @_;
 8518:     if (!$symb) {return '';}
 8519:     &commonJSfunctions($request);
 8520:     my $result;
 8521: 
 8522:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8523:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 8524: 
 8525:     $result.='
 8526: <h2>
 8527:   '.&mt('Grading table').'
 8528: </h2>'.
 8529:             &selectfield(0).
 8530:             '<input type="hidden" name="command" value="viewgrades" />
 8531:             <div>
 8532:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 8533:             </div>
 8534:         </div>
 8535:   </form>';
 8536:     return $result;
 8537: }
 8538: 
 8539: sub submit_options_download {
 8540:     my ($request,$symb) = @_;
 8541:     if (!$symb) {return '';}
 8542: 
 8543:     &commonJSfunctions($request);
 8544: 
 8545:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8546:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 8547:     $result.='
 8548: <h2>
 8549:   '.&mt('Select Students for Which to Download Submissions').'
 8550: </h2>'.&selectfield(1).'
 8551:                 <input type="hidden" name="command" value="downloadfileslink" /> 
 8552:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 8553:             </div>
 8554:           </div>
 8555: 
 8556: 
 8557:   </form>';
 8558:     return $result;
 8559: }
 8560: 
 8561: #--- Displays the submissions first page -------
 8562: sub submit_options {
 8563:     my ($request,$symb) = @_;
 8564:     if (!$symb) {return '';}
 8565: 
 8566:     &commonJSfunctions($request);
 8567:     my $result;
 8568: 
 8569:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8570: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 8571:     $result.='
 8572: <h2>
 8573:   '.&mt('Select individual students to grade').'
 8574: </h2>'.&selectfield(1).'
 8575:                 <input type="hidden" name="command" value="submission" /> 
 8576: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
 8577:             </div>
 8578:           </div>
 8579: 
 8580: 
 8581:   </form>';
 8582:     return $result;
 8583: }
 8584: 
 8585: sub selectfield {
 8586:    my ($full)=@_;
 8587:    my $result='<div class="LC_columnSection">
 8588:   
 8589:     <fieldset>
 8590:       <legend>
 8591:        '.&mt('Sections').'
 8592:       </legend>
 8593:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
 8594:     </fieldset>
 8595:   
 8596:     <fieldset>
 8597:       <legend>
 8598:         '.&mt('Groups').'
 8599:       </legend>
 8600:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
 8601:     </fieldset>
 8602:   
 8603:     <fieldset>
 8604:       <legend>
 8605:         '.&mt('Access Status').'
 8606:       </legend>
 8607:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
 8608:     </fieldset>';
 8609:     if ($full) {
 8610:        $result.='
 8611:     <fieldset>
 8612:       <legend>
 8613:         '.&mt('Submission Status').'
 8614:       </legend>'.
 8615:        &Apache::loncommon::select_form('all','submitonly',
 8616:           (&Apache::lonlocal::texthash(
 8617:              'yes'       => 'with submissions',
 8618:              'queued'    => 'in grading queue',
 8619:              'graded'    => 'with ungraded submissions',
 8620:              'incorrect' => 'with incorrect submissions',
 8621:              'all'       => 'with any status'),
 8622:              'select_form_order' => ['yes','queued','graded','incorrect','all'])).
 8623:    '</fieldset>';
 8624:     }
 8625:     $result.='</div><br />';
 8626:     return $result;
 8627: }
 8628: 
 8629: sub reset_perm {
 8630:     undef(%perm);
 8631: }
 8632: 
 8633: sub init_perm {
 8634:     &reset_perm();
 8635:     foreach my $test_perm ('vgr','mgr','opa') {
 8636: 
 8637: 	my $scope = $env{'request.course.id'};
 8638: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
 8639: 
 8640: 	    $scope .= '/'.$env{'request.course.sec'};
 8641: 	    if ( $perm{$test_perm}=
 8642: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
 8643: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
 8644: 	    } else {
 8645: 		delete($perm{$test_perm});
 8646: 	    }
 8647: 	}
 8648:     }
 8649: }
 8650: 
 8651: sub gather_clicker_ids {
 8652:     my %clicker_ids;
 8653: 
 8654:     my $classlist = &Apache::loncoursedata::get_classlist();
 8655: 
 8656:     # Set up a couple variables.
 8657:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
 8658:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
 8659:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
 8660: 
 8661:     foreach my $student (keys(%$classlist)) {
 8662:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
 8663:         my $username = $classlist->{$student}->[$username_idx];
 8664:         my $domain   = $classlist->{$student}->[$domain_idx];
 8665:         my $clickers =
 8666: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
 8667:         foreach my $id (split(/\,/,$clickers)) {
 8668:             $id=~s/^[\#0]+//;
 8669:             $id=~s/[\-\:]//g;
 8670:             if (exists($clicker_ids{$id})) {
 8671: 		$clicker_ids{$id}.=','.$username.':'.$domain;
 8672:             } else {
 8673: 		$clicker_ids{$id}=$username.':'.$domain;
 8674:             }
 8675:         }
 8676:     }
 8677:     return %clicker_ids;
 8678: }
 8679: 
 8680: sub gather_adv_clicker_ids {
 8681:     my %clicker_ids;
 8682:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 8683:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8684:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
 8685:     foreach my $element (sort(keys(%coursepersonnel))) {
 8686:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
 8687:             my ($puname,$pudom)=split(/\:/,$person);
 8688:             my $clickers =
 8689: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
 8690:             foreach my $id (split(/\,/,$clickers)) {
 8691: 		$id=~s/^[\#0]+//;
 8692:                 $id=~s/[\-\:]//g;
 8693: 		if (exists($clicker_ids{$id})) {
 8694: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
 8695: 		} else {
 8696: 		    $clicker_ids{$id}=$puname.':'.$pudom;
 8697: 		}
 8698:             }
 8699:         }
 8700:     }
 8701:     return %clicker_ids;
 8702: }
 8703: 
 8704: sub clicker_grading_parameters {
 8705:     return ('gradingmechanism' => 'scalar',
 8706:             'upfiletype' => 'scalar',
 8707:             'specificid' => 'scalar',
 8708:             'pcorrect' => 'scalar',
 8709:             'pincorrect' => 'scalar');
 8710: }
 8711: 
 8712: sub process_clicker {
 8713:     my ($r,$symb)=@_;
 8714:     if (!$symb) {return '';}
 8715:     my $result=&checkforfile_js();
 8716:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 8717:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 8718:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource.').
 8719:         '</b></td></tr>'."\n";
 8720:     $result.='<tr bgcolor="#ffffe6"><td>'."\n";
 8721: # Attempt to restore parameters from last session, set defaults if not present
 8722:     my %Saveable_Parameters=&clicker_grading_parameters();
 8723:     &Apache::loncommon::restore_course_settings('grades_clicker',
 8724:                                                  \%Saveable_Parameters);
 8725:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
 8726:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
 8727:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
 8728:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
 8729: 
 8730:     my %checked;
 8731:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
 8732:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
 8733:           $checked{$gradingmechanism}=' checked="checked"';
 8734:        }
 8735:     }
 8736: 
 8737:     my $upload=&mt("Upload File");
 8738:     my $type=&mt("Type");
 8739:     my $attendance=&mt("Award points just for participation");
 8740:     my $personnel=&mt("Correctness determined from response by course personnel");
 8741:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
 8742:     my $given=&mt("Correctness determined from given list of answers").' '.
 8743:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
 8744:     my $pcorrect=&mt("Percentage points for correct solution");
 8745:     my $pincorrect=&mt("Percentage points for incorrect solution");
 8746:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
 8747: 						   ('iclicker' => 'i>clicker',
 8748:                                                     'interwrite' => 'interwrite PRS'));
 8749:     $symb = &Apache::lonenc::check_encrypt($symb);
 8750:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
 8751: function sanitycheck() {
 8752: // Accept only integer percentages
 8753:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
 8754:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
 8755: // Find out grading choice
 8756:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8757:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
 8758:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
 8759:       }
 8760:    }
 8761: // By default, new choice equals user selection
 8762:    newgradingchoice=gradingchoice;
 8763: // Not good to give more points for false answers than correct ones
 8764:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
 8765:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
 8766:    }
 8767: // If new choice is attendance only, and old choice was correctness-based, restore defaults
 8768:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
 8769:       document.forms.gradesupload.pcorrect.value=100;
 8770:       document.forms.gradesupload.pincorrect.value=100;
 8771:    }
 8772: // If the values are different, cannot be attendance only
 8773:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
 8774:        (gradingchoice=='attendance')) {
 8775:        newgradingchoice='personnel';
 8776:    }
 8777: // Change grading choice to new one
 8778:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8779:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
 8780:          document.forms.gradesupload.gradingmechanism[i].checked=true;
 8781:       } else {
 8782:          document.forms.gradesupload.gradingmechanism[i].checked=false;
 8783:       }
 8784:    }
 8785: // Remember the old state
 8786:    document.forms.gradesupload.waschecked.value=newgradingchoice;
 8787: }
 8788: ENDUPFORM
 8789:     $result.= <<ENDUPFORM;
 8790: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 8791: <input type="hidden" name="symb" value="$symb" />
 8792: <input type="hidden" name="command" value="processclickerfile" />
 8793: <input type="file" name="upfile" size="50" />
 8794: <br /><label>$type: $selectform</label>
 8795: <br /><label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
 8796: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
 8797: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
 8798: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
 8799: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
 8800: <br />&nbsp;&nbsp;&nbsp;
 8801: <input type="text" name="givenanswer" size="50" />
 8802: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
 8803: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
 8804: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
 8805: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 8806: </form>'
 8807: ENDUPFORM
 8808:     $result.='</td></tr></table>'."\n".
 8809:              '</td></tr></table><br /><br />'."\n";
 8810:     return $result;
 8811: }
 8812: 
 8813: sub process_clicker_file {
 8814:     my ($r,$symb)=@_;
 8815:     if (!$symb) {return '';}
 8816: 
 8817:     my %Saveable_Parameters=&clicker_grading_parameters();
 8818:     &Apache::loncommon::store_course_settings('grades_clicker',
 8819:                                               \%Saveable_Parameters);
 8820:     my $result='';
 8821:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
 8822: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
 8823: 	return $result;
 8824:     }
 8825:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
 8826:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
 8827:         return $result;
 8828:     }
 8829:     my $foundgiven=0;
 8830:     if ($env{'form.gradingmechanism'} eq 'given') {
 8831:         $env{'form.givenanswer'}=~s/^\s*//gs;
 8832:         $env{'form.givenanswer'}=~s/\s*$//gs;
 8833:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-]+/\,/g;
 8834:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
 8835:         my @answers=split(/\,/,$env{'form.givenanswer'});
 8836:         $foundgiven=$#answers+1;
 8837:     }
 8838:     my %clicker_ids=&gather_clicker_ids();
 8839:     my %correct_ids;
 8840:     if ($env{'form.gradingmechanism'} eq 'personnel') {
 8841: 	%correct_ids=&gather_adv_clicker_ids();
 8842:     }
 8843:     if ($env{'form.gradingmechanism'} eq 'specific') {
 8844: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
 8845: 	   $correct_id=~tr/a-z/A-Z/;
 8846: 	   $correct_id=~s/\s//gs;
 8847: 	   $correct_id=~s/^[\#0]+//;
 8848:            $correct_id=~s/[\-\:]//g;
 8849:            if ($correct_id) {
 8850: 	      $correct_ids{$correct_id}='specified';
 8851:            }
 8852:         }
 8853:     }
 8854:     if ($env{'form.gradingmechanism'} eq 'attendance') {
 8855: 	$result.=&mt('Score based on attendance only');
 8856:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
 8857:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
 8858:     } else {
 8859: 	my $number=0;
 8860: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
 8861: 	foreach my $id (sort(keys(%correct_ids))) {
 8862: 	    $result.='<br /><tt>'.$id.'</tt> - ';
 8863: 	    if ($correct_ids{$id} eq 'specified') {
 8864: 		$result.=&mt('specified');
 8865: 	    } else {
 8866: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
 8867: 		$result.=&Apache::loncommon::plainname($uname,$udom);
 8868: 	    }
 8869: 	    $number++;
 8870: 	}
 8871:         $result.="</p>\n";
 8872: 	if ($number==0) {
 8873: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
 8874: 	    return $result;
 8875: 	}
 8876:     }
 8877:     if (length($env{'form.upfile'}) < 2) {
 8878:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
 8879: 		     '<span class="LC_error">',
 8880: 		     '</span>',
 8881: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
 8882:         return $result;
 8883:     }
 8884: 
 8885: # Were able to get all the info needed, now analyze the file
 8886: 
 8887:     $result.=&Apache::loncommon::studentbrowser_javascript();
 8888:     $symb = &Apache::lonenc::check_encrypt($symb);
 8889:     my $heading=&mt('Scanning clicker file');
 8890:     $result.=(<<ENDHEADER);
 8891: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 8892: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 8893: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 8894: <form method="post" action="/adm/grades" name="clickeranalysis">
 8895: <input type="hidden" name="symb" value="$symb" />
 8896: <input type="hidden" name="command" value="assignclickergrades" />
 8897: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
 8898: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
 8899: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
 8900: ENDHEADER
 8901:     if ($env{'form.gradingmechanism'} eq 'given') {
 8902:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
 8903:     } 
 8904:     my %responses;
 8905:     my @questiontitles;
 8906:     my $errormsg='';
 8907:     my $number=0;
 8908:     if ($env{'form.upfiletype'} eq 'iclicker') {
 8909: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
 8910:     }
 8911:     if ($env{'form.upfiletype'} eq 'interwrite') {
 8912:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
 8913:     }
 8914:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
 8915:              '<input type="hidden" name="number" value="'.$number.'" />'.
 8916:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
 8917:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
 8918:              '<br />';
 8919:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
 8920:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
 8921:        return $result;
 8922:     } 
 8923: # Remember Question Titles
 8924: # FIXME: Possibly need delimiter other than ":"
 8925:     for (my $i=0;$i<$number;$i++) {
 8926:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
 8927:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
 8928:     }
 8929:     my $correct_count=0;
 8930:     my $student_count=0;
 8931:     my $unknown_count=0;
 8932: # Match answers with usernames
 8933: # FIXME: Possibly need delimiter other than ":"
 8934:     foreach my $id (keys(%responses)) {
 8935:        if ($correct_ids{$id}) {
 8936:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
 8937:           $correct_count++;
 8938:        } elsif ($clicker_ids{$id}) {
 8939:           if ($clicker_ids{$id}=~/\,/) {
 8940: # More than one user with the same clicker!
 8941:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
 8942:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 8943:                            "<select name='multi".$id."'>";
 8944:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
 8945:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
 8946:              }
 8947:              $result.='</select>';
 8948:              $unknown_count++;
 8949:           } else {
 8950: # Good: found one and only one user with the right clicker
 8951:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
 8952:              $student_count++;
 8953:           }
 8954:        } else {
 8955:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
 8956:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 8957:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
 8958:                    "\n".&mt("Domain").": ".
 8959:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
 8960:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
 8961:           $unknown_count++;
 8962:        }
 8963:     }
 8964:     $result.='<hr />'.
 8965:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
 8966:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
 8967:        if ($correct_count==0) {
 8968:           $errormsg.="Found no correct answers answers for grading!";
 8969:        } elsif ($correct_count>1) {
 8970:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
 8971:        }
 8972:     }
 8973:     if ($number<1) {
 8974:        $errormsg.="Found no questions.";
 8975:     }
 8976:     if ($errormsg) {
 8977:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
 8978:     } else {
 8979:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
 8980:     }
 8981:     $result.='</form></td></tr></table>'."\n".
 8982:              '</td></tr></table><br /><br />'."\n";
 8983:     return $result;
 8984: }
 8985: 
 8986: sub iclicker_eval {
 8987:     my ($questiontitles,$responses)=@_;
 8988:     my $number=0;
 8989:     my $errormsg='';
 8990:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 8991:         my %components=&Apache::loncommon::record_sep($line);
 8992:         my @entries=map {$components{$_}} (sort(keys(%components)));
 8993: 	if ($entries[0] eq 'Question') {
 8994: 	    for (my $i=3;$i<$#entries;$i+=6) {
 8995: 		$$questiontitles[$number]=$entries[$i];
 8996: 		$number++;
 8997: 	    }
 8998: 	}
 8999: 	if ($entries[0]=~/^\#/) {
 9000: 	    my $id=$entries[0];
 9001: 	    my @idresponses;
 9002: 	    $id=~s/^[\#0]+//;
 9003: 	    for (my $i=0;$i<$number;$i++) {
 9004: 		my $idx=3+$i*6;
 9005: 		push(@idresponses,$entries[$idx]);
 9006: 	    }
 9007: 	    $$responses{$id}=join(',',@idresponses);
 9008: 	}
 9009:     }
 9010:     return ($errormsg,$number);
 9011: }
 9012: 
 9013: sub interwrite_eval {
 9014:     my ($questiontitles,$responses)=@_;
 9015:     my $number=0;
 9016:     my $errormsg='';
 9017:     my $skipline=1;
 9018:     my $questionnumber=0;
 9019:     my %idresponses=();
 9020:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 9021:         my %components=&Apache::loncommon::record_sep($line);
 9022:         my @entries=map {$components{$_}} (sort(keys(%components)));
 9023:         if ($entries[1] eq 'Time') { $skipline=0; next; }
 9024:         if ($entries[1] eq 'Response') { $skipline=1; }
 9025:         next if $skipline;
 9026:         if ($entries[0]!=$questionnumber) {
 9027:            $questionnumber=$entries[0];
 9028:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
 9029:            $number++;
 9030:         }
 9031:         my $id=$entries[4];
 9032:         $id=~s/^[\#0]+//;
 9033:         $id=~s/^v\d*\://i;
 9034:         $id=~s/[\-\:]//g;
 9035:         $idresponses{$id}[$number]=$entries[6];
 9036:     }
 9037:     foreach my $id (keys(%idresponses)) {
 9038:        $$responses{$id}=join(',',@{$idresponses{$id}});
 9039:        $$responses{$id}=~s/^\s*\,//;
 9040:     }
 9041:     return ($errormsg,$number);
 9042: }
 9043: 
 9044: sub assign_clicker_grades {
 9045:     my ($r,$symb)=@_;
 9046:     if (!$symb) {return '';}
 9047: # See which part we are saving to
 9048:     my $res_error;
 9049:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 9050:     if ($res_error) {
 9051:         return &navmap_errormsg();
 9052:     }
 9053: # FIXME: This should probably look for the first handgradeable part
 9054:     my $part=$$partlist[0];
 9055: # Start screen output
 9056:     my $result='';
 9057: 
 9058:     my $heading=&mt('Assigning grades based on clicker file');
 9059:     $result.=(<<ENDHEADER);
 9060: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 9061: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 9062: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 9063: ENDHEADER
 9064: # Get correct result
 9065: # FIXME: Possibly need delimiter other than ":"
 9066:     my @correct=();
 9067:     my $gradingmechanism=$env{'form.gradingmechanism'};
 9068:     my $number=$env{'form.number'};
 9069:     if ($gradingmechanism ne 'attendance') {
 9070:        foreach my $key (keys(%env)) {
 9071:           if ($key=~/^form\.correct\:/) {
 9072:              my @input=split(/\,/,$env{$key});
 9073:              for (my $i=0;$i<=$#input;$i++) {
 9074:                  if (($correct[$i]) && ($input[$i]) &&
 9075:                      ($correct[$i] ne $input[$i])) {
 9076:                     $result.='<br /><span class="LC_warning">'.
 9077:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
 9078:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
 9079:                  } elsif ($input[$i]) {
 9080:                     $correct[$i]=$input[$i];
 9081:                  }
 9082:              }
 9083:           }
 9084:        }
 9085:        for (my $i=0;$i<$number;$i++) {
 9086:           if (!$correct[$i]) {
 9087:              $result.='<br /><span class="LC_error">'.
 9088:                       &mt('No correct result given for question "[_1]"!',
 9089:                           $env{'form.question:'.$i}).'</span>';
 9090:           }
 9091:        }
 9092:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
 9093:     }
 9094: # Start grading
 9095:     my $pcorrect=$env{'form.pcorrect'};
 9096:     my $pincorrect=$env{'form.pincorrect'};
 9097:     my $storecount=0;
 9098:     foreach my $key (keys(%env)) {
 9099:        my $user='';
 9100:        if ($key=~/^form\.student\:(.*)$/) {
 9101:           $user=$1;
 9102:        }
 9103:        if ($key=~/^form\.unknown\:(.*)$/) {
 9104:           my $id=$1;
 9105:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
 9106:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
 9107:           } elsif ($env{'form.multi'.$id}) {
 9108:              $user=$env{'form.multi'.$id};
 9109:           }
 9110:        }
 9111:        if ($user) { 
 9112:           my @answer=split(/\,/,$env{$key});
 9113:           my $sum=0;
 9114:           my $realnumber=$number;
 9115:           for (my $i=0;$i<$number;$i++) {
 9116:              if  ($correct[$i] eq '-') {
 9117:                 $realnumber--;
 9118:              } elsif ($answer[$i]) {
 9119:                 if ($gradingmechanism eq 'attendance') {
 9120:                    $sum+=$pcorrect;
 9121:                 } elsif ($correct[$i] eq '*') {
 9122:                    $sum+=$pcorrect;
 9123:                 } else {
 9124:                    if ($answer[$i] eq $correct[$i]) {
 9125:                       $sum+=$pcorrect;
 9126:                    } else {
 9127:                       $sum+=$pincorrect;
 9128:                    }
 9129:                 }
 9130:              }
 9131:           }
 9132:           my $ave=$sum/(100*$realnumber);
 9133: # Store
 9134:           my ($username,$domain)=split(/\:/,$user);
 9135:           my %grades=();
 9136:           $grades{"resource.$part.solved"}='correct_by_override';
 9137:           $grades{"resource.$part.awarded"}=$ave;
 9138:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 9139:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
 9140:                                                  $env{'request.course.id'},
 9141:                                                  $domain,$username);
 9142:           if ($returncode ne 'ok') {
 9143:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
 9144:           } else {
 9145:              $storecount++;
 9146:           }
 9147:        }
 9148:     }
 9149: # We are done
 9150:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
 9151:              '</td></tr></table>'."\n".
 9152:              '</td></tr></table><br /><br />'."\n";
 9153:     return $result;
 9154: }
 9155: 
 9156: sub navmap_errormsg {
 9157:     return '<div class="LC_error">'.
 9158:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
 9159:            &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>').
 9160:            '</div>';
 9161: }
 9162: 
 9163: sub startpage {
 9164:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag) = @_;
 9165:     unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
 9166:     $r->print(&Apache::loncommon::start_page('Grading',undef,
 9167:                                           {'bread_crumbs' => $crumbs}));
 9168:     unless ($nodisplayflag) {
 9169:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag));
 9170:     }
 9171: }
 9172: 
 9173: sub select_problem {
 9174:     my ($r)=@_;
 9175:     $r->print('<h2>'.&mt('Select the problem you want to grade').'</h2><form action="/adm/grades">');
 9176:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1));
 9177:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
 9178:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
 9179: }
 9180: 
 9181: sub handler {
 9182:     my $request=$_[0];
 9183:     &reset_caches();
 9184:     if ($env{'browser.mathml'}) {
 9185: 	&Apache::loncommon::content_type($request,'text/xml');
 9186:     } else {
 9187: 	&Apache::loncommon::content_type($request,'text/html');
 9188:     }
 9189:     $request->send_http_header;
 9190:     return '' if $request->header_only;
 9191:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
 9192: 
 9193: # see what command we need to execute
 9194: 
 9195:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
 9196:     my $command=$commands[0];
 9197: 
 9198:     if ($#commands > 0) {
 9199: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
 9200:     }
 9201: 
 9202: # see what the symb is
 9203: 
 9204:     my $symb=$env{'form.symb'};
 9205:     unless ($symb) {
 9206:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
 9207:        $symb=&Apache::lonnet::symbread($url);
 9208:     }
 9209:     &Apache::lonenc::check_decrypt(\$symb);                             
 9210: 
 9211:     $ssi_error = 0;
 9212:     if ($symb eq '' || $command eq '') {
 9213: #
 9214: # Not called from a resource
 9215: #    
 9216:         &startpage($request,undef,[],1,1);
 9217:         &select_problem($request);
 9218:     } else {
 9219: 	&init_perm();
 9220: 	if ($command eq 'submission' && $perm{'vgr'}) {
 9221:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}]);
 9222: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
 9223: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
 9224:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
 9225:                                        {href=>'',text=>'Select student'}],1,1);
 9226: 	    &pickStudentPage($request,$symb);
 9227: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
 9228:             &startpage($request,$symb,
 9229:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
 9230:                                        {href=>'',text=>'Select student'},
 9231:                                        {href=>'',text=>'Grade student'}],1,1);
 9232: 	    &displayPage($request,$symb);
 9233: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
 9234:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
 9235:                                        {href=>'',text=>'Select student'},
 9236:                                        {href=>'',text=>'Grade student'},
 9237:                                        {href=>'',text=>'Store grades'}],1,1);
 9238: 	    &updateGradeByPage($request,$symb);
 9239: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
 9240:             &startpage($request,$symb,[{href=>'',text=>'...'},
 9241:                                        {href=>'',text=>'Modify grades'}]);
 9242: 	    &processGroup($request,$symb);
 9243: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
 9244:             &startpage($request,$symb);
 9245: 	    $request->print(&grading_menu($request,$symb));
 9246: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
 9247:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
 9248: 	    $request->print(&submit_options($request,$symb));
 9249:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
 9250:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}]);
 9251:             $request->print(&listStudents($request,$symb,'graded'));
 9252:         } elsif ($command eq 'table' && $perm{'vgr'}) {
 9253:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
 9254:             $request->print(&submit_options_table($request,$symb));
 9255:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
 9256:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
 9257:             $request->print(&submit_options_sequence($request,$symb));
 9258: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
 9259:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
 9260: 	    $request->print(&viewgrades($request,$symb));
 9261: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
 9262:             &startpage($request,$symb,[{href=>'',text=>'...'},
 9263:                                        {href=>'',text=>'Store grades'}]);
 9264: 	    $request->print(&processHandGrade($request,$symb));
 9265: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
 9266:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
 9267:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
 9268:                                                                              text=>"Modify grades"},
 9269:                                        {href=>'', text=>"Store grades"}]);
 9270: 	    $request->print(&editgrades($request,$symb));
 9271:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
 9272:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
 9273:             $request->print(&initialverifyreceipt($request,$symb));
 9274: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
 9275:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
 9276:                                        {href=>'',text=>'Verification Result'}]);
 9277: 	    $request->print(&verifyreceipt($request,$symb));
 9278:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
 9279:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
 9280:             $request->print(&process_clicker($request,$symb));
 9281:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
 9282:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
 9283:                                        {href=>'', text=>'Process clicker file'}]);
 9284:             $request->print(&process_clicker_file($request,$symb));
 9285:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
 9286:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
 9287:                                        {href=>'', text=>'Process clicker file'},
 9288:                                        {href=>'', text=>'Store grades'}]);
 9289:             $request->print(&assign_clicker_grades($request,$symb));
 9290: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
 9291:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9292: 	    $request->print(&upcsvScores_form($request,$symb));
 9293: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
 9294:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9295: 	    $request->print(&csvupload($request,$symb));
 9296: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
 9297:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9298: 	    $request->print(&csvuploadmap($request,$symb));
 9299: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
 9300: 	    if ($env{'form.associate'} ne 'Reverse Association') {
 9301:                 &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9302: 		$request->print(&csvuploadoptions($request,$symb));
 9303: 	    } else {
 9304: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
 9305: 		    $env{'form.upfile_associate'} = 'reverse';
 9306: 		} else {
 9307: 		    $env{'form.upfile_associate'} = 'forward';
 9308: 		}
 9309:                 &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9310: 		$request->print(&csvuploadmap($request,$symb));
 9311: 	    }
 9312: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
 9313:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9314: 	    $request->print(&csvuploadassign($request,$symb));
 9315: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
 9316:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9317: 	    $request->print(&scantron_selectphase($request,undef,$symb));
 9318:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
 9319:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9320:  	    $request->print(&scantron_do_warning($request,$symb));
 9321: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
 9322:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9323: 	    $request->print(&scantron_validate_file($request,$symb));
 9324: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
 9325:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9326: 	    $request->print(&scantron_process_students($request,$symb));
 9327:  	} elsif ($command eq 'scantronupload' && 
 9328:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9329: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9330:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9331:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
 9332:  	} elsif ($command eq 'scantronupload_save' &&
 9333:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9334: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9335:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9336:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
 9337:  	} elsif ($command eq 'scantron_download' &&
 9338: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 9339:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9340:  	    $request->print(&scantron_download_scantron_data($request,$symb));
 9341:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
 9342:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9343:             $request->print(&checkscantron_results($request,$symb));
 9344:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
 9345:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}]);
 9346:             $request->print(&submit_options_download($request,$symb));
 9347:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
 9348:             &startpage($request,$symb,
 9349:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
 9350:     {href=>'', text=>'Download submissions'}]);
 9351:             &submit_download_link($request,$symb);
 9352: 	} elsif ($command) {
 9353:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
 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>