File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.638: download - view: text, annotated - select for diffs
Fri Oct 22 15:29:57 2010 UTC (13 years, 6 months ago) by www
Branches: MAIN
CVS tags: HEAD
* Undoing 1.634
- was causing JavaScript error
- formulation different from the other alerts (need consistent message)
- what the button actually says depends on the browser
* Warning message if points>weight (caused a problem this week for an instructor)

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.638 2010/10/22 15:29:57 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: #--- Sets response_error pointer to "1" if navmaps object broken ---
  142: sub response_type {
  143:     my ($symb,$response_error) = @_;
  144: 
  145:     my $navmap = Apache::lonnavmaps::navmap->new();
  146:     unless (ref($navmap)) {
  147:         if (ref($response_error)) {
  148:             $$response_error = 1;
  149:         }
  150:         return;
  151:     }
  152:     my $res = $navmap->getBySymb($symb);
  153:     unless (ref($res)) {
  154:         $$response_error = 1;
  155:         return;
  156:     }
  157:     my $partlist = $res->parts();
  158:     my %vPart = 
  159: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
  160:     my (%response_types,%handgrade);
  161:     foreach my $part (@{ $partlist }) {
  162: 	next if (%vPart && !exists($vPart{$part}));
  163: 
  164: 	my @types = $res->responseType($part);
  165: 	my @ids = $res->responseIds($part);
  166: 	for (my $i=0; $i < scalar(@ids); $i++) {
  167: 	    $response_types{$part}{$ids[$i]} = $types[$i];
  168: 	    $handgrade{$part.'_'.$ids[$i]} = 
  169: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
  170: 				     '.handgrade',$symb);
  171: 	}
  172:     }
  173:     return ($partlist,\%handgrade,\%response_types);
  174: }
  175: 
  176: sub flatten_responseType {
  177:     my ($responseType) = @_;
  178:     my @part_response_id =
  179: 	map { 
  180: 	    my $part = $_;
  181: 	    map {
  182: 		[$part,$_]
  183: 		} sort(keys(%{ $responseType->{$part} }));
  184: 	} sort(keys(%$responseType));
  185:     return @part_response_id;
  186: }
  187: 
  188: sub get_display_part {
  189:     my ($partID,$symb)=@_;
  190:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
  191:     if (defined($display) and $display ne '') {
  192:         $display.= ' (<span class="LC_internal_info">'
  193:                   .&mt('Part ID: [_1]',$partID).'</span>)';
  194:     } else {
  195: 	$display=$partID;
  196:     }
  197:     return $display;
  198: }
  199: 
  200: sub reset_caches {
  201:     &reset_analyze_cache();
  202:     &reset_perm();
  203: }
  204: 
  205: {
  206:     my %analyze_cache;
  207:     my %analyze_cache_formkeys;
  208: 
  209:     sub reset_analyze_cache {
  210: 	undef(%analyze_cache);
  211:         undef(%analyze_cache_formkeys);
  212:     }
  213: 
  214:     sub get_analyze {
  215: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash)=@_;
  216: 	my $key = "$symb\0$uname\0$udom";
  217: 	if (exists($analyze_cache{$key})) {
  218:             my $getupdate = 0;
  219:             if (ref($add_to_hash) eq 'HASH') {
  220:                 foreach my $item (keys(%{$add_to_hash})) {
  221:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
  222:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
  223:                             $getupdate = 1;
  224:                             last;
  225:                         }
  226:                     } else {
  227:                         $getupdate = 1;
  228:                     }
  229:                 }
  230:             }
  231:             if (!$getupdate) {
  232:                 return $analyze_cache{$key};
  233:             }
  234:         }
  235: 
  236: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
  237: 	$url=&Apache::lonnet::clutter($url);
  238:         my %form = ('grade_target'      => 'analyze',
  239:                     'grade_domain'      => $udom,
  240:                     'grade_symb'        => $symb,
  241:                     'grade_courseid'    =>  $env{'request.course.id'},
  242:                     'grade_username'    => $uname,
  243:                     'grade_noincrement' => $no_increment);
  244:         if (ref($add_to_hash)) {
  245:             %form = (%form,%{$add_to_hash});
  246:         } 
  247: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
  248: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
  249: 	my %analyze=&Apache::lonnet::str2hash($subresult);
  250:         if (ref($add_to_hash) eq 'HASH') {
  251:             $analyze_cache_formkeys{$key} = $add_to_hash;
  252:         } else {
  253:             $analyze_cache_formkeys{$key} = {};
  254:         }
  255: 	return $analyze_cache{$key} = \%analyze;
  256:     }
  257: 
  258:     sub get_order {
  259: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment)=@_;
  260: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment);
  261: 	return $analyze->{"$partid.$respid.shown"};
  262:     }
  263: 
  264:     sub get_radiobutton_correct_foil {
  265: 	my ($partid,$respid,$symb,$uname,$udom)=@_;
  266: 	my $analyze = &get_analyze($symb,$uname,$udom);
  267:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom);
  268:         if (ref($foils) eq 'ARRAY') {
  269: 	    foreach my $foil (@{$foils}) {
  270: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
  271: 		    return $foil;
  272: 	        }
  273: 	    }
  274: 	}
  275:     }
  276: 
  277:     sub scantron_partids_tograde {
  278:         my ($resource,$cid,$uname,$udom,$check_for_randomlist) = @_;
  279:         my (%analysis,@parts);
  280:         if (ref($resource)) {
  281:             my $symb = $resource->symb();
  282:             my $add_to_form;
  283:             if ($check_for_randomlist) {
  284:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
  285:             }
  286:             my $analyze = &get_analyze($symb,$uname,$udom,undef,$add_to_form);
  287:             if (ref($analyze) eq 'HASH') {
  288:                 %analysis = %{$analyze};
  289:             }
  290:             if (ref($analysis{'parts'}) eq 'ARRAY') {
  291:                 foreach my $part (@{$analysis{'parts'}}) {
  292:                     my ($id,$respid) = split(/\./,$part);
  293:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
  294:                         push(@parts,$part);
  295:                     }
  296:                 }
  297:             }
  298:         }
  299:         return (\%analysis,\@parts);
  300:     }
  301: 
  302: }
  303: 
  304: #--- Clean response type for display
  305: #--- Currently filters option/rank/radiobutton/match/essay/Task
  306: #        response types only.
  307: sub cleanRecord {
  308:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
  309: 	$uname,$udom) = @_;
  310:     my $grayFont = '<span class="LC_internal_info">';
  311:     if ($response =~ /^(option|rank)$/) {
  312: 	my %answer=&Apache::lonnet::str2hash($answer);
  313: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  314: 	my ($toprow,$bottomrow);
  315: 	foreach my $foil (@$order) {
  316: 	    if ($grading{$foil} == 1) {
  317: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
  318: 	    } else {
  319: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
  320: 	    }
  321: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  322: 	}
  323: 	return '<blockquote><table border="1">'.
  324: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  325: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  326: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
  327:     } elsif ($response eq 'match') {
  328: 	my %answer=&Apache::lonnet::str2hash($answer);
  329: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  330: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
  331: 	my ($toprow,$middlerow,$bottomrow);
  332: 	foreach my $foil (@$order) {
  333: 	    my $item=shift(@items);
  334: 	    if ($grading{$foil} == 1) {
  335: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
  336: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
  337: 	    } else {
  338: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
  339: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
  340: 	    }
  341: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  342: 	}
  343: 	return '<blockquote><table border="1">'.
  344: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  345: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
  346: 	    $middlerow.'</tr>'.
  347: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  348: 	    $bottomrow.'</tr>'.'</table></blockquote>';
  349:     } elsif ($response eq 'radiobutton') {
  350: 	my %answer=&Apache::lonnet::str2hash($answer);
  351: 	my ($toprow,$bottomrow);
  352: 	my $correct = 
  353: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom);
  354: 	foreach my $foil (@$order) {
  355: 	    if (exists($answer{$foil})) {
  356: 		if ($foil eq $correct) {
  357: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
  358: 		} else {
  359: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
  360: 		}
  361: 	    } else {
  362: 		$toprow.='<td>'.&mt('false').'</td>';
  363: 	    }
  364: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  365: 	}
  366: 	return '<blockquote><table border="1">'.
  367: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  368: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  369: 	    $bottomrow.'</tr>'.'</table></blockquote>';
  370:     } elsif ($response eq 'essay') {
  371: 	if (! exists ($env{'form.'.$symb})) {
  372: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
  373: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
  374: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
  375: 
  376: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
  377: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
  378: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
  379: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
  380: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
  381: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
  382: 	}
  383: 	$answer =~ s-\n-<br />-g;
  384: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
  385:     } elsif ( $response eq 'organic') {
  386: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
  387: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
  388: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
  389: 	return $result;
  390:     } elsif ( $response eq 'Task') {
  391: 	if ( $answer eq 'SUBMITTED') {
  392: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
  393: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
  394: 	    return $result;
  395: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
  396: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
  397: 			       keys(%{$record}));
  398: 	    return join('<br />',($version,@matches));
  399: 			       
  400: 			       
  401: 	} else {
  402: 	    my $result =
  403: 		'<p>'
  404: 		.&mt('Overall result: [_1]',
  405: 		     $record->{$version."resource.$respid.$partid.status"})
  406: 		.'</p>';
  407: 	    
  408: 	    $result .= '<ul>';
  409: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
  410: 			     keys(%{$record}));
  411: 	    foreach my $grade (sort(@grade)) {
  412: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
  413: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
  414: 				     $dim, $record->{$grade}).
  415: 			  '</li>';
  416: 	    }
  417: 	    $result.='</ul>';
  418: 	    return $result;
  419: 	}
  420:     } elsif ( $response =~ m/(?:numerical|formula)/) {
  421: 	$answer = 
  422: 	    &Apache::loncommon::format_previous_attempt_value('submission',
  423: 							      $answer);
  424:     }
  425:     return $answer;
  426: }
  427: 
  428: #-- A couple of common js functions
  429: sub commonJSfunctions {
  430:     my $request = shift;
  431:     $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
  432:     function radioSelection(radioButton) {
  433: 	var selection=null;
  434: 	if (radioButton.length > 1) {
  435: 	    for (var i=0; i<radioButton.length; i++) {
  436: 		if (radioButton[i].checked) {
  437: 		    return radioButton[i].value;
  438: 		}
  439: 	    }
  440: 	} else {
  441: 	    if (radioButton.checked) return radioButton.value;
  442: 	}
  443: 	return selection;
  444:     }
  445: 
  446:     function pullDownSelection(selectOne) {
  447: 	var selection="";
  448: 	if (selectOne.length > 1) {
  449: 	    for (var i=0; i<selectOne.length; i++) {
  450: 		if (selectOne[i].selected) {
  451: 		    return selectOne[i].value;
  452: 		}
  453: 	    }
  454: 	} else {
  455:             // only one value it must be the selected one
  456: 	    return selectOne.value;
  457: 	}
  458:     }
  459: COMMONJSFUNCTIONS
  460: }
  461: 
  462: #--- Dumps the class list with usernames,list of sections,
  463: #--- section, ids and fullnames for each user.
  464: sub getclasslist {
  465:     my ($getsec,$filterlist,$getgroup) = @_;
  466:     my @getsec;
  467:     my @getgroup;
  468:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  469:     if (!ref($getsec)) {
  470: 	if ($getsec ne '' && $getsec ne 'all') {
  471: 	    @getsec=($getsec);
  472: 	}
  473:     } else {
  474: 	@getsec=@{$getsec};
  475:     }
  476:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
  477:     if (!ref($getgroup)) {
  478: 	if ($getgroup ne '' && $getgroup ne 'all') {
  479: 	    @getgroup=($getgroup);
  480: 	}
  481:     } else {
  482: 	@getgroup=@{$getgroup};
  483:     }
  484:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
  485: 
  486:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
  487:     # Bail out if we were unable to get the classlist
  488:     return if (! defined($classlist));
  489:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
  490:     #
  491:     my %sections;
  492:     my %fullnames;
  493:     foreach my $student (keys(%$classlist)) {
  494:         my $end      = 
  495:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
  496:         my $start    = 
  497:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
  498:         my $id       = 
  499:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
  500:         my $section  = 
  501:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
  502:         my $fullname = 
  503:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
  504:         my $status   = 
  505:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
  506:         my $group   = 
  507:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
  508: 	# filter students according to status selected
  509: 	if ($filterlist && (!($stu_status =~ /Any/))) {
  510: 	    if (!($stu_status =~ $status)) {
  511: 		delete($classlist->{$student});
  512: 		next;
  513: 	    }
  514: 	}
  515: 	# filter students according to groups selected
  516: 	my @stu_groups = split(/,/,$group);
  517: 	if (@getgroup) {
  518: 	    my $exclude = 1;
  519: 	    foreach my $grp (@getgroup) {
  520: 	        foreach my $stu_group (@stu_groups) {
  521: 	            if ($stu_group eq $grp) {
  522: 	                $exclude = 0;
  523:     	            } 
  524: 	        }
  525:     	        if (($grp eq 'none') && !$group) {
  526:         	        $exclude = 0;
  527:         	}
  528: 	    }
  529: 	    if ($exclude) {
  530: 	        delete($classlist->{$student});
  531: 	    }
  532: 	}
  533: 	$section = ($section ne '' ? $section : 'none');
  534: 	if (&canview($section)) {
  535: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
  536: 		$sections{$section}++;
  537: 		if ($classlist->{$student}) {
  538: 		    $fullnames{$student}=$fullname;
  539: 		}
  540: 	    } else {
  541: 		delete($classlist->{$student});
  542: 	    }
  543: 	} else {
  544: 	    delete($classlist->{$student});
  545: 	}
  546:     }
  547:     my %seen = ();
  548:     my @sections = sort(keys(%sections));
  549:     return ($classlist,\@sections,\%fullnames);
  550: }
  551: 
  552: sub canmodify {
  553:     my ($sec)=@_;
  554:     if ($perm{'mgr'}) {
  555: 	if (!defined($perm{'mgr_section'})) {
  556: 	    # can modify whole class
  557: 	    return 1;
  558: 	} else {
  559: 	    if ($sec eq $perm{'mgr_section'}) {
  560: 		#can modify the requested section
  561: 		return 1;
  562: 	    } else {
  563: 		# can't modify the request section
  564: 		return 0;
  565: 	    }
  566: 	}
  567:     }
  568:     #can't modify
  569:     return 0;
  570: }
  571: 
  572: sub canview {
  573:     my ($sec)=@_;
  574:     if ($perm{'vgr'}) {
  575: 	if (!defined($perm{'vgr_section'})) {
  576: 	    # can modify whole class
  577: 	    return 1;
  578: 	} else {
  579: 	    if ($sec eq $perm{'vgr_section'}) {
  580: 		#can modify the requested section
  581: 		return 1;
  582: 	    } else {
  583: 		# can't modify the request section
  584: 		return 0;
  585: 	    }
  586: 	}
  587:     }
  588:     #can't modify
  589:     return 0;
  590: }
  591: 
  592: #--- Retrieve the grade status of a student for all the parts
  593: sub student_gradeStatus {
  594:     my ($symb,$udom,$uname,$partlist) = @_;
  595:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
  596:     my %partstatus = ();
  597:     foreach (@$partlist) {
  598: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
  599: 	$status              = 'nothing' if ($status eq '');
  600: 	$partstatus{$_}      = $status;
  601: 	my $subkey           = "resource.$_.submitted_by";
  602: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
  603:     }
  604:     return %partstatus;
  605: }
  606: 
  607: # hidden form and javascript that calls the form
  608: # Use by verifyscript and viewgrades
  609: # Shows a student's view of problem and submission
  610: sub jscriptNform {
  611:     my ($symb) = @_;
  612:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  613:     my $jscript= &Apache::lonhtmlcommon::scripttag(
  614: 	'    function viewOneStudent(user,domain) {'."\n".
  615: 	'	document.onestudent.student.value = user;'."\n".
  616: 	'	document.onestudent.userdom.value = domain;'."\n".
  617: 	'	document.onestudent.submit();'."\n".
  618: 	'    }'."\n".
  619: 	"\n");
  620:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
  621: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  622: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
  623: 	'<input type="hidden" name="command" value="submission" />'."\n".
  624: 	'<input type="hidden" name="student" value="" />'."\n".
  625: 	'<input type="hidden" name="userdom" value="" />'."\n".
  626: 	'</form>'."\n";
  627:     return $jscript;
  628: }
  629: 
  630: 
  631: 
  632: # Given the score (as a number [0-1] and the weight) what is the final
  633: # point value? This function will round to the nearest tenth, third,
  634: # or quarter if one of those is within the tolerance of .00001.
  635: sub compute_points {
  636:     my ($score, $weight) = @_;
  637:     
  638:     my $tolerance = .00001;
  639:     my $points = $score * $weight;
  640: 
  641:     # Check for nearness to 1/x.
  642:     my $check_for_nearness = sub {
  643:         my ($factor) = @_;
  644:         my $num = ($points * $factor) + $tolerance;
  645:         my $floored_num = floor($num);
  646:         if ($num - $floored_num < 2 * $tolerance * $factor) {
  647:             return $floored_num / $factor;
  648:         }
  649:         return $points;
  650:     };
  651: 
  652:     $points = $check_for_nearness->(10);
  653:     $points = $check_for_nearness->(3);
  654:     $points = $check_for_nearness->(4);
  655:     
  656:     return $points;
  657: }
  658: 
  659: #------------------ End of general use routines --------------------
  660: 
  661: #
  662: # Find most similar essay
  663: #
  664: 
  665: sub most_similar {
  666:     my ($uname,$udom,$uessay,$old_essays)=@_;
  667: 
  668: # ignore spaces and punctuation
  669: 
  670:     $uessay=~s/\W+/ /gs;
  671: 
  672: # ignore empty submissions (occuring when only files are sent)
  673: 
  674:     unless ($uessay=~/\w+/s) { return ''; }
  675: 
  676: # these will be returned. Do not care if not at least 50 percent similar
  677:     my $limit=0.6;
  678:     my $sname='';
  679:     my $sdom='';
  680:     my $scrsid='';
  681:     my $sessay='';
  682: # go through all essays ...
  683:     foreach my $tkey (keys(%$old_essays)) {
  684: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
  685: # ... except the same student
  686:         next if (($tname eq $uname) && ($tdom eq $udom));
  687: 	my $tessay=$old_essays->{$tkey};
  688: 	$tessay=~s/\W+/ /gs;
  689: # String similarity gives up if not even limit
  690: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
  691: # Found one
  692: 	if ($tsimilar>$limit) {
  693: 	    $limit=$tsimilar;
  694: 	    $sname=$tname;
  695: 	    $sdom=$tdom;
  696: 	    $scrsid=$tcrsid;
  697: 	    $sessay=$old_essays->{$tkey};
  698: 	}
  699:     }
  700:     if ($limit>0.6) {
  701:        return ($sname,$sdom,$scrsid,$sessay,$limit);
  702:     } else {
  703:        return ('','','','',0);
  704:     }
  705: }
  706: 
  707: #-------------------------------------------------------------------
  708: 
  709: #------------------------------------ Receipt Verification Routines
  710: #
  711: 
  712: sub initialverifyreceipt {
  713:    my ($request,$symb) = @_;
  714:    &commonJSfunctions($request);
  715:    return '<form name="gradingMenu"><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
  716:         &Apache::lonnet::recprefix($env{'request.course.id'}).
  717:         '-<input type="text" name="receipt" size="4" />'.
  718:         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  719:         '<input type="hidden" name="command" value="verify" />'.
  720:         "</form>\n";
  721: }
  722: 
  723: #--- Check whether a receipt number is valid.---
  724: sub verifyreceipt {
  725:     my ($request,$symb)  = @_;
  726: 
  727:     my $courseid = $env{'request.course.id'};
  728:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
  729: 	$env{'form.receipt'};
  730:     $receipt     =~ s/[^\-\d]//g;
  731: 
  732:     my $title.=
  733: 	'<h3><span class="LC_info">'.
  734: 	&mt('Verifying Receipt Number [_1]',$receipt).
  735: 	'</span></h3>'."\n";
  736: 
  737:     my ($string,$contents,$matches) = ('','',0);
  738:     my (undef,undef,$fullname) = &getclasslist('all','0');
  739:     
  740:     my $receiptparts=0;
  741:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
  742: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
  743:     my $parts=['0'];
  744:     if ($receiptparts) {
  745:         my $res_error; 
  746:         ($parts)=&response_type($symb,\$res_error);
  747:         if ($res_error) {
  748:             return &navmap_errormsg();
  749:         } 
  750:     }
  751:     
  752:     my $header = 
  753: 	&Apache::loncommon::start_data_table().
  754: 	&Apache::loncommon::start_data_table_header_row().
  755: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
  756: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
  757: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
  758:     if ($receiptparts) {
  759: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
  760:     }
  761:     $header.=
  762: 	&Apache::loncommon::end_data_table_header_row();
  763: 
  764:     foreach (sort 
  765: 	     {
  766: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  767: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  768: 		 }
  769: 		 return $a cmp $b;
  770: 	     } (keys(%$fullname))) {
  771: 	my ($uname,$udom)=split(/\:/);
  772: 	foreach my $part (@$parts) {
  773: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
  774: 		$contents.=
  775: 		    &Apache::loncommon::start_data_table_row().
  776: 		    '<td>&nbsp;'."\n".
  777: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
  778: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
  779: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
  780: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
  781: 		if ($receiptparts) {
  782: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
  783: 		}
  784: 		$contents.= 
  785: 		    &Apache::loncommon::end_data_table_row()."\n";
  786: 		
  787: 		$matches++;
  788: 	    }
  789: 	}
  790:     }
  791:     if ($matches == 0) {
  792:         $string = $title
  793:                  .'<p class="LC_warning">'
  794:                  .&mt('No match found for the above receipt number.')
  795:                  .'</p>';
  796:     } else {
  797: 	$string = &jscriptNform($symb).$title.
  798: 	    '<p>'.
  799: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
  800: 	    '</p>'.
  801: 	    $header.
  802: 	    $contents.
  803: 	    &Apache::loncommon::end_data_table()."\n";
  804:     }
  805:     return $string;
  806: }
  807: 
  808: #--- This is called by a number of programs.
  809: #--- Called from the Grading Menu - View/Grade an individual student
  810: #--- Also called directly when one clicks on the subm button 
  811: #    on the problem page.
  812: sub listStudents {
  813:     my ($request,$symb,$submitonly) = @_;
  814: 
  815:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
  816:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
  817:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
  818:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
  819:     unless ($submitonly) {
  820:        $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
  821:     }
  822: 
  823:     my $result='';
  824:     my $res_error;
  825:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
  826: 
  827:     my %lt = &Apache::lonlocal::texthash (
  828: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
  829: 		'single'   => 'Please select the student before clicking on the Next button.',
  830: 	     );
  831:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
  832:     function checkSelect(checkBox) {
  833: 	var ctr=0;
  834: 	var sense="";
  835: 	if (checkBox.length > 1) {
  836: 	    for (var i=0; i<checkBox.length; i++) {
  837: 		if (checkBox[i].checked) {
  838: 		    ctr++;
  839: 		}
  840: 	    }
  841: 	    sense = '$lt{'multiple'}';
  842: 	} else {
  843: 	    if (checkBox.checked) {
  844: 		ctr = 1;
  845: 	    }
  846: 	    sense = '$lt{'single'}';
  847: 	}
  848: 	if (ctr == 0) {
  849: 	    alert(sense);
  850: 	    return false;
  851: 	}
  852: 	document.gradesub.submit();
  853:     }
  854: 
  855:     function reLoadList(formname) {
  856: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
  857: 	formname.command.value = 'submission';
  858: 	formname.submit();
  859:     }
  860: LISTJAVASCRIPT
  861: 
  862:     &commonJSfunctions($request);
  863:     $request->print($result);
  864: 
  865:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
  866: 	"\n";
  867: 	
  868:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
  869:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
  870:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
  871:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
  872:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
  873:                   .&Apache::lonhtmlcommon::row_closure();
  874:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
  875:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
  876:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
  877:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
  878:                   .&Apache::lonhtmlcommon::row_closure();
  879: 
  880:     my $submission_options;
  881:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  882:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
  883:     $env{'form.Status'} = $saveStatus;
  884:     $submission_options.=
  885:         '<span class="LC_nobreak">'.
  886:         '<label><input type="radio" name="lastSub" value="lastonly" /> '.
  887:         &mt('last submission only').' </label></span>'."\n".
  888:         '<span class="LC_nobreak">'.
  889:         '<label><input type="radio" name="lastSub" value="last" /> '.
  890:         &mt('last submission &amp; parts info').' </label></span>'."\n".
  891:         '<span class="LC_nobreak">'.
  892:         '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.
  893:         &mt('by dates and submissions').'</label></span>'."\n".
  894:         '<span class="LC_nobreak">'.
  895:         '<label><input type="radio" name="lastSub" value="all" /> '.
  896:         &mt('all details').'</label></span>';
  897:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
  898:                   .$submission_options
  899:                   .&Apache::lonhtmlcommon::row_closure();
  900: 
  901:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
  902:                   .'<select name="increment">'
  903:                   .'<option value="1">'.&mt('Whole Points').'</option>'
  904:                   .'<option value=".5">'.&mt('Half Points').'</option>'
  905:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
  906:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
  907:                   .'</select>'
  908:                   .&Apache::lonhtmlcommon::row_closure();
  909: 
  910:     $gradeTable .= 
  911:         &build_section_inputs().
  912: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
  913: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  914: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
  915: 
  916:     if (exists($env{'form.Status'})) {
  917: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
  918:     } else {
  919:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
  920:                       .&Apache::lonhtmlcommon::StatusOptions(
  921:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
  922:                       .&Apache::lonhtmlcommon::row_closure();
  923:     }
  924: 
  925:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
  926:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
  927:                   .&Apache::lonhtmlcommon::row_closure(1)
  928:                   .&Apache::lonhtmlcommon::end_pick_box();
  929: 
  930:     $gradeTable .= '<p>'
  931:                   .&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"
  932:                   .'<input type="hidden" name="command" value="processGroup" />'
  933:                   .'</p>';
  934: 
  935: # checkall buttons
  936:     $gradeTable.=&check_script('gradesub', 'stuinfo');
  937:     $gradeTable.='<input type="button" '."\n".
  938:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
  939:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
  940:     $gradeTable.=&check_buttons();
  941:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
  942:     $gradeTable.= &Apache::loncommon::start_data_table().
  943: 	&Apache::loncommon::start_data_table_header_row();
  944:     my $loop = 0;
  945:     while ($loop < 2) {
  946: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
  947: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
  948: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
  949: 	    foreach my $part (sort(@$partlist)) {
  950: 		my $display_part=
  951: 		    &get_display_part((split(/_/,$part))[0],$symb);
  952: 		$gradeTable.=
  953: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
  954: 	    }
  955: 	} elsif ($submitonly eq 'queued') {
  956: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
  957: 	}
  958: 	$loop++;
  959: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
  960:     }
  961:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
  962: 
  963:     my $ctr = 0;
  964:     foreach my $student (sort 
  965: 			 {
  966: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  967: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  968: 			     }
  969: 			     return $a cmp $b;
  970: 			 }
  971: 			 (keys(%$fullname))) {
  972: 	my ($uname,$udom) = split(/:/,$student);
  973: 
  974: 	my %status = ();
  975: 
  976: 	if ($submitonly eq 'queued') {
  977: 	    my %queue_status = 
  978: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
  979: 							$udom,$uname);
  980: 	    next if (!defined($queue_status{'gradingqueue'}));
  981: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
  982: 	}
  983: 
  984: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
  985: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
  986: 	    my $submitted = 0;
  987: 	    my $graded = 0;
  988: 	    my $incorrect = 0;
  989: 	    foreach (keys(%status)) {
  990: 		$submitted = 1 if ($status{$_} ne 'nothing');
  991: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
  992: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
  993: 		
  994: 		my ($foo,$partid,$foo1) = split(/\./,$_);
  995: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
  996: 		    $submitted = 0;
  997: 		    my ($part)=split(/\./,$partid);
  998: 		    $gradeTable.='<input type="hidden" name="'.
  999: 			$student.':'.$part.':submitted_by" value="'.
 1000: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
 1001: 		}
 1002: 	    }
 1003: 	    
 1004: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 1005: 				     $submitonly eq 'incorrect' ||
 1006: 				     $submitonly eq 'graded'));
 1007: 	    next if (!$graded && ($submitonly eq 'graded'));
 1008: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 1009: 	}
 1010: 
 1011: 	$ctr++;
 1012: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
 1013:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
 1014: 	if ( $perm{'vgr'} eq 'F' ) {
 1015: 	    if ($ctr%2 ==1) {
 1016: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
 1017: 	    }
 1018: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
 1019:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
 1020:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
 1021: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
 1022: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
 1023: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
 1024: 
 1025: 	    if ($submitonly ne 'all') {
 1026: 		foreach (sort(keys(%status))) {
 1027: 		    next if ($_ =~ /^resource.*?submitted_by$/);
 1028: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
 1029: 		}
 1030: 	    }
 1031: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
 1032: 	    if ($ctr%2 ==0) {
 1033: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
 1034: 	    }
 1035: 	}
 1036:     }
 1037:     if ($ctr%2 ==1) {
 1038: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
 1039: 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1040: 		foreach (@$partlist) {
 1041: 		    $gradeTable.='<td>&nbsp;</td>';
 1042: 		}
 1043: 	    } elsif ($submitonly eq 'queued') {
 1044: 		$gradeTable.='<td>&nbsp;</td>';
 1045: 	    }
 1046: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
 1047:     }
 1048: 
 1049:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
 1050:         '<input type="button" '.
 1051:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
 1052:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
 1053:     if ($ctr == 0) {
 1054: 	my $num_students=(scalar(keys(%$fullname)));
 1055: 	if ($num_students eq 0) {
 1056: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
 1057: 	} else {
 1058: 	    my $submissions='submissions';
 1059: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
 1060: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
 1061: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
 1062: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
 1063: 		&mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
 1064: 		    $num_students).
 1065: 		'</span><br />';
 1066: 	}
 1067:     } elsif ($ctr == 1) {
 1068: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
 1069:     }
 1070:     $request->print($gradeTable);
 1071:     return '';
 1072: }
 1073: 
 1074: #---- Called from the listStudents routine
 1075: 
 1076: sub check_script {
 1077:     my ($form, $type)=@_;
 1078:     my $chkallscript= &Apache::lonhtmlcommon::scripttag('
 1079:     function checkall() {
 1080:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1081:             ele = document.forms.'.$form.'.elements[i];
 1082:             if (ele.name == "'.$type.'") {
 1083:             document.forms.'.$form.'.elements[i].checked=true;
 1084:                                        }
 1085:         }
 1086:     }
 1087: 
 1088:     function checksec() {
 1089:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1090:             ele = document.forms.'.$form.'.elements[i];
 1091:            string = document.forms.'.$form.'.chksec.value;
 1092:            if
 1093:           (ele.value.indexOf(":::SECTION"+string)>0) {
 1094:               document.forms.'.$form.'.elements[i].checked=true;
 1095:             }
 1096:         }
 1097:     }
 1098: 
 1099: 
 1100:     function uncheckall() {
 1101:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1102:             ele = document.forms.'.$form.'.elements[i];
 1103:             if (ele.name == "'.$type.'") {
 1104:             document.forms.'.$form.'.elements[i].checked=false;
 1105:                                        }
 1106:         }
 1107:     }
 1108: 
 1109: '."\n");
 1110:     return $chkallscript;
 1111: }
 1112: 
 1113: sub check_buttons {
 1114:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
 1115:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
 1116:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
 1117:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
 1118:     return $buttons;
 1119: }
 1120: 
 1121: #     Displays the submissions for one student or a group of students
 1122: sub processGroup {
 1123:     my ($request,$symb)  = @_;
 1124:     my $ctr        = 0;
 1125:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1126:     my $total      = scalar(@stuchecked)-1;
 1127: 
 1128:     foreach my $student (@stuchecked) {
 1129: 	my ($uname,$udom,$fullname) = split(/:/,$student);
 1130: 	$env{'form.student'}        = $uname;
 1131: 	$env{'form.userdom'}        = $udom;
 1132: 	$env{'form.fullname'}       = $fullname;
 1133: 	&submission($request,$ctr,$total,$symb);
 1134: 	$ctr++;
 1135:     }
 1136:     return '';
 1137: }
 1138: 
 1139: #------------------------------------------------------------------------------------
 1140: #
 1141: #-------------------------- Next few routines handles grading by student, essentially
 1142: #                           handles essay response type problem/part
 1143: #
 1144: #--- Javascript to handle the submission page functionality ---
 1145: sub sub_page_js {
 1146:     my $request = shift;
 1147: 	    my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 1148:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1149:     function updateRadio(formname,id,weight) {
 1150: 	var gradeBox = formname["GD_BOX"+id];
 1151: 	var radioButton = formname["RADVAL"+id];
 1152: 	var oldpts = formname["oldpts"+id].value;
 1153: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
 1154: 	gradeBox.value = pts;
 1155: 	var resetbox = false;
 1156: 	if (isNaN(pts) || pts < 0) {
 1157: 	    alert("$alertmsg"+pts);
 1158: 	    for (var i=0; i<radioButton.length; i++) {
 1159: 		if (radioButton[i].checked) {
 1160: 		    gradeBox.value = i;
 1161: 		    resetbox = true;
 1162: 		}
 1163: 	    }
 1164: 	    if (!resetbox) {
 1165: 		formtextbox.value = "";
 1166: 	    }
 1167: 	    return;
 1168: 	}
 1169: 
 1170: 	if (pts > weight) {
 1171: 	    var resp = confirm("You entered a value ("+pts+
 1172: 			       ") greater than the weight for the part. Accept?");
 1173: 	    if (resp == false) {
 1174: 		gradeBox.value = oldpts;
 1175: 		return;
 1176: 	    }
 1177: 	}
 1178: 
 1179: 	for (var i=0; i<radioButton.length; i++) {
 1180: 	    radioButton[i].checked=false;
 1181: 	    if (pts == i && pts != "") {
 1182: 		radioButton[i].checked=true;
 1183: 	    }
 1184: 	}
 1185: 	updateSelect(formname,id);
 1186: 	formname["stores"+id].value = "0";
 1187:     }
 1188: 
 1189:     function writeBox(formname,id,pts) {
 1190: 	var gradeBox = formname["GD_BOX"+id];
 1191: 	if (checkSolved(formname,id) == 'update') {
 1192: 	    gradeBox.value = pts;
 1193: 	} else {
 1194: 	    var oldpts = formname["oldpts"+id].value;
 1195: 	    gradeBox.value = oldpts;
 1196: 	    var radioButton = formname["RADVAL"+id];
 1197: 	    for (var i=0; i<radioButton.length; i++) {
 1198: 		radioButton[i].checked=false;
 1199: 		if (i == oldpts) {
 1200: 		    radioButton[i].checked=true;
 1201: 		}
 1202: 	    }
 1203: 	}
 1204: 	formname["stores"+id].value = "0";
 1205: 	updateSelect(formname,id);
 1206: 	return;
 1207:     }
 1208: 
 1209:     function clearRadBox(formname,id) {
 1210: 	if (checkSolved(formname,id) == 'noupdate') {
 1211: 	    updateSelect(formname,id);
 1212: 	    return;
 1213: 	}
 1214: 	gradeSelect = formname["GD_SEL"+id];
 1215: 	for (var i=0; i<gradeSelect.length; i++) {
 1216: 	    if (gradeSelect[i].selected) {
 1217: 		var selectx=i;
 1218: 	    }
 1219: 	}
 1220: 	var stores = formname["stores"+id];
 1221: 	if (selectx == stores.value) { return };
 1222: 	var gradeBox = formname["GD_BOX"+id];
 1223: 	gradeBox.value = "";
 1224: 	var radioButton = formname["RADVAL"+id];
 1225: 	for (var i=0; i<radioButton.length; i++) {
 1226: 	    radioButton[i].checked=false;
 1227: 	}
 1228: 	stores.value = selectx;
 1229:     }
 1230: 
 1231:     function checkSolved(formname,id) {
 1232: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
 1233: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
 1234: 	    if (!reply) {return "noupdate";}
 1235: 	    formname.overRideScore.value = 'yes';
 1236: 	}
 1237: 	return "update";
 1238:     }
 1239: 
 1240:     function updateSelect(formname,id) {
 1241: 	formname["GD_SEL"+id][0].selected = true;
 1242: 	return;
 1243:     }
 1244: 
 1245: //=========== Check that a point is assigned for all the parts  ============
 1246:     function checksubmit(formname,val,total,parttot) {
 1247: 	formname.gradeOpt.value = val;
 1248: 	if (val == "Save & Next") {
 1249: 	    for (i=0;i<=total;i++) {
 1250: 		for (j=0;j<parttot;j++) {
 1251: 		    var partid = formname["partid"+i+"_"+j].value;
 1252: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1253: 			var points = formname["GD_BOX"+i+"_"+partid].value;
 1254: 			if (points == "") {
 1255: 			    var name = formname["name"+i].value;
 1256: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
 1257: 			    var resp = confirm("You did not assign a score for "+studentID+
 1258: 					       ", part "+partid+". Continue?");
 1259: 			    if (resp == false) {
 1260: 				formname["GD_BOX"+i+"_"+partid].focus();
 1261: 				return false;
 1262: 			    }
 1263: 			}
 1264: 		    }
 1265: 		    
 1266: 		}
 1267: 	    }
 1268: 	    
 1269: 	}
 1270: 	formname.submit();
 1271:     }
 1272: 
 1273: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1274:     function checkSubmitPage(formname,total) {
 1275: 	noscore = new Array(100);
 1276: 	var ptr = 0;
 1277: 	for (i=1;i<total;i++) {
 1278: 	    var partid = formname["q_"+i].value;
 1279: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1280: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1281: 		var status = formname["solved"+i+"_"+partid].value;
 1282: 		if (points == "" && status != "correct_by_student") {
 1283: 		    noscore[ptr] = i;
 1284: 		    ptr++;
 1285: 		}
 1286: 	    }
 1287: 	}
 1288: 	if (ptr != 0) {
 1289: 	    var sense = ptr == 1 ? ": " : "s: ";
 1290: 	    var prolist = "";
 1291: 	    if (ptr == 1) {
 1292: 		prolist = noscore[0];
 1293: 	    } else {
 1294: 		var i = 0;
 1295: 		while (i < ptr-1) {
 1296: 		    prolist += noscore[i]+", ";
 1297: 		    i++;
 1298: 		}
 1299: 		prolist += "and "+noscore[i];
 1300: 	    }
 1301: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1302: 	    if (resp == false) {
 1303: 		return false;
 1304: 	    }
 1305: 	}
 1306: 
 1307: 	formname.submit();
 1308:     }
 1309: SUBJAVASCRIPT
 1310: }
 1311: 
 1312: #--- javascript for essay type problem --
 1313: sub sub_page_kw_js {
 1314:     my $request = shift;
 1315:     my $iconpath = $request->dir_config('lonIconsURL');
 1316:     &commonJSfunctions($request);
 1317: 
 1318:     my $inner_js_msg_central= (<<INNERJS);
 1319: <script type="text/javascript">
 1320:     function checkInput() {
 1321:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1322:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1323:       var usrctr = document.msgcenter.usrctr.value;
 1324:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1325:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1326: 
 1327:       var msgchk = "";
 1328:       if (document.msgcenter.subchk.checked) {
 1329:          msgchk = "msgsub,";
 1330:       }
 1331:       var includemsg = 0;
 1332:       for (var i=1; i<=nmsg; i++) {
 1333:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1334:           var frmmsg = document.msgcenter["msg"+i];
 1335:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1336:           var showflg = opener.document.SCORE["shownOnce"+i];
 1337:           showflg.value = "1";
 1338:           var chkbox = document.msgcenter["msgn"+i];
 1339:           if (chkbox.checked) {
 1340:              msgchk += "savemsg"+i+",";
 1341:              includemsg = 1;
 1342:           }
 1343:       }
 1344:       if (document.msgcenter.newmsgchk.checked) {
 1345:          msgchk += "newmsg"+usrctr;
 1346:          includemsg = 1;
 1347:       }
 1348:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1349:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1350:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1351:       includemsg.value = msgchk;
 1352: 
 1353:       self.close()
 1354: 
 1355:     }
 1356: </script>
 1357: INNERJS
 1358: 
 1359:     my $inner_js_highlight_central= (<<INNERJS);
 1360: <script type="text/javascript">
 1361:     function updateChoice(flag) {
 1362:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1363:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1364:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1365:       opener.document.SCORE.refresh.value = "on";
 1366:       if (opener.document.SCORE.keywords.value!=""){
 1367:          opener.document.SCORE.submit();
 1368:       }
 1369:       self.close()
 1370:     }
 1371: </script>
 1372: INNERJS
 1373: 
 1374:     my $start_page_msg_central = 
 1375:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1376: 				       {'js_ready'  => 1,
 1377: 					'only_body' => 1,
 1378: 					'bgcolor'   =>'#FFFFFF',});
 1379:     my $end_page_msg_central = 
 1380: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1381: 
 1382: 
 1383:     my $start_page_highlight_central = 
 1384:         &Apache::loncommon::start_page('Highlight Central',
 1385: 				       $inner_js_highlight_central,
 1386: 				       {'js_ready'  => 1,
 1387: 					'only_body' => 1,
 1388: 					'bgcolor'   =>'#FFFFFF',});
 1389:     my $end_page_highlight_central = 
 1390: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1391: 
 1392:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1393:     $docopen=~s/^document\.//;
 1394:     my $alertmsg = &mt('Please select a word or group of words from document and then click this link.');
 1395:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1396: 
 1397: //===================== Show list of keywords ====================
 1398:   function keywords(formname) {
 1399:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
 1400:     if (nret==null) return;
 1401:     formname.keywords.value = nret;
 1402: 
 1403:     if (formname.keywords.value != "") {
 1404: 	formname.refresh.value = "on";
 1405: 	formname.submit();
 1406:     }
 1407:     return;
 1408:   }
 1409: 
 1410: //===================== Script to view submitted by ==================
 1411:   function viewSubmitter(submitter) {
 1412:     document.SCORE.refresh.value = "on";
 1413:     document.SCORE.NCT.value = "1";
 1414:     document.SCORE.unamedom0.value = submitter;
 1415:     document.SCORE.submit();
 1416:     return;
 1417:   }
 1418: 
 1419: //===================== Script to add keyword(s) ==================
 1420:   function getSel() {
 1421:     if (document.getSelection) txt = document.getSelection();
 1422:     else if (document.selection) txt = document.selection.createRange().text;
 1423:     else return;
 1424:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1425:     if (cleantxt=="") {
 1426: 	alert("$alertmsg");
 1427: 	return;
 1428:     }
 1429:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
 1430:     if (nret==null) return;
 1431:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1432:     if (document.SCORE.keywords.value != "") {
 1433: 	document.SCORE.refresh.value = "on";
 1434: 	document.SCORE.submit();
 1435:     }
 1436:     return;
 1437:   }
 1438: 
 1439: //====================== Script for composing message ==============
 1440:    // preload images
 1441:    img1 = new Image();
 1442:    img1.src = "$iconpath/mailbkgrd.gif";
 1443:    img2 = new Image();
 1444:    img2.src = "$iconpath/mailto.gif";
 1445: 
 1446:   function msgCenter(msgform,usrctr,fullname) {
 1447:     var Nmsg  = msgform.savemsgN.value;
 1448:     savedMsgHeader(Nmsg,usrctr,fullname);
 1449:     var subject = msgform.msgsub.value;
 1450:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1451:     re = /msgsub/;
 1452:     var shwsel = "";
 1453:     if (re.test(msgchk)) { shwsel = "checked" }
 1454:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1455:     displaySubject(checkEntities(subject),shwsel);
 1456:     for (var i=1; i<=Nmsg; i++) {
 1457: 	var testmsg = "savemsg"+i+",";
 1458: 	re = new RegExp(testmsg,"g");
 1459: 	shwsel = "";
 1460: 	if (re.test(msgchk)) { shwsel = "checked" }
 1461: 	var message = document.SCORE["savemsg"+i].value;
 1462: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1463: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1464: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1465:     }
 1466:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1467:     shwsel = "";
 1468:     re = /newmsg/;
 1469:     if (re.test(msgchk)) { shwsel = "checked" }
 1470:     newMsg(newmsg,shwsel);
 1471:     msgTail(); 
 1472:     return;
 1473:   }
 1474: 
 1475:   function checkEntities(strx) {
 1476:     if (strx.length == 0) return strx;
 1477:     var orgStr = ["&", "<", ">", '"']; 
 1478:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1479:     var counter = 0;
 1480:     while (counter < 4) {
 1481: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1482: 	counter++;
 1483:     }
 1484:     return strx;
 1485:   }
 1486: 
 1487:   function strReplace(strx, orgStr, newStr) {
 1488:     return strx.split(orgStr).join(newStr);
 1489:   }
 1490: 
 1491:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1492:     var height = 70*Nmsg+250;
 1493:     var scrollbar = "no";
 1494:     if (height > 600) {
 1495: 	height = 600;
 1496: 	scrollbar = "yes";
 1497:     }
 1498:     var xpos = (screen.width-600)/2;
 1499:     xpos = (xpos < 0) ? '0' : xpos;
 1500:     var ypos = (screen.height-height)/2-30;
 1501:     ypos = (ypos < 0) ? '0' : ypos;
 1502: 
 1503:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
 1504:     pWin.focus();
 1505:     pDoc = pWin.document;
 1506:     pDoc.$docopen;
 1507:     pDoc.write('$start_page_msg_central');
 1508: 
 1509:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1510:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1511:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
 1512: 
 1513:     pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
 1514:     pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
 1515:     pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
 1516: }
 1517:     function displaySubject(msg,shwsel) {
 1518:     pDoc = pWin.document;
 1519:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1520:     pDoc.write("<td>Subject<\\/td>");
 1521:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1522:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
 1523: }
 1524: 
 1525:   function displaySavedMsg(ctr,msg,shwsel) {
 1526:     pDoc = pWin.document;
 1527:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1528:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
 1529:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1530:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
 1531: }
 1532: 
 1533:   function newMsg(newmsg,shwsel) {
 1534:     pDoc = pWin.document;
 1535:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1536:     pDoc.write("<td align=\\"center\\">New<\\/td>");
 1537:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1538:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
 1539: }
 1540: 
 1541:   function msgTail() {
 1542:     pDoc = pWin.document;
 1543:     pDoc.write("<\\/table>");
 1544:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1545:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1546:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onclick=\\"self.close()\\"><br /><br />");
 1547:     pDoc.write("<\\/form>");
 1548:     pDoc.write('$end_page_msg_central');
 1549:     pDoc.close();
 1550: }
 1551: 
 1552: //====================== Script for keyword highlight options ==============
 1553:   function kwhighlight() {
 1554:     var kwclr    = document.SCORE.kwclr.value;
 1555:     var kwsize   = document.SCORE.kwsize.value;
 1556:     var kwstyle  = document.SCORE.kwstyle.value;
 1557:     var redsel = "";
 1558:     var grnsel = "";
 1559:     var blusel = "";
 1560:     if (kwclr=="red")   {var redsel="checked"};
 1561:     if (kwclr=="green") {var grnsel="checked"};
 1562:     if (kwclr=="blue")  {var blusel="checked"};
 1563:     var sznsel = "";
 1564:     var sz1sel = "";
 1565:     var sz2sel = "";
 1566:     if (kwsize=="0")  {var sznsel="checked"};
 1567:     if (kwsize=="+1") {var sz1sel="checked"};
 1568:     if (kwsize=="+2") {var sz2sel="checked"};
 1569:     var synsel = "";
 1570:     var syisel = "";
 1571:     var sybsel = "";
 1572:     if (kwstyle=="")    {var synsel="checked"};
 1573:     if (kwstyle=="<i>") {var syisel="checked"};
 1574:     if (kwstyle=="<b>") {var sybsel="checked"};
 1575:     highlightCentral();
 1576:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
 1577:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
 1578:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
 1579:     highlightend();
 1580:     return;
 1581:   }
 1582: 
 1583:   function highlightCentral() {
 1584: //    if (window.hwdWin) window.hwdWin.close();
 1585:     var xpos = (screen.width-400)/2;
 1586:     xpos = (xpos < 0) ? '0' : xpos;
 1587:     var ypos = (screen.height-330)/2-30;
 1588:     ypos = (ypos < 0) ? '0' : ypos;
 1589: 
 1590:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1591:     hwdWin.focus();
 1592:     var hDoc = hwdWin.document;
 1593:     hDoc.$docopen;
 1594:     hDoc.write('$start_page_highlight_central');
 1595:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1596:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options<\\/span><\\/h3><br /><br />");
 1597: 
 1598:     hDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
 1599:     hDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
 1600:     hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
 1601:   }
 1602: 
 1603:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1604:     var hDoc = hwdWin.document;
 1605:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1606:     hDoc.write("<td align=\\"left\\">");
 1607:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
 1608:     hDoc.write("<td align=\\"left\\">");
 1609:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
 1610:     hDoc.write("<td align=\\"left\\">");
 1611:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
 1612:     hDoc.write("<\\/tr>");
 1613:   }
 1614: 
 1615:   function highlightend() { 
 1616:     var hDoc = hwdWin.document;
 1617:     hDoc.write("<\\/table>");
 1618:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1619:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onclick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
 1620:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onclick=\\"self.close()\\"><br /><br />");
 1621:     hDoc.write("<\\/form>");
 1622:     hDoc.write('$end_page_highlight_central');
 1623:     hDoc.close();
 1624:   }
 1625: 
 1626: SUBJAVASCRIPT
 1627: }
 1628: 
 1629: sub get_increment {
 1630:     my $increment = $env{'form.increment'};
 1631:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1632:         $increment != .1) {
 1633:         $increment = 1;
 1634:     }
 1635:     return $increment;
 1636: }
 1637: 
 1638: sub gradeBox_start {
 1639:     return (
 1640:         &Apache::loncommon::start_data_table()
 1641:        .&Apache::loncommon::start_data_table_header_row()
 1642:        .'<th>'.&mt('Part').'</th>'
 1643:        .'<th>'.&mt('Points').'</th>'
 1644:        .'<th>&nbsp;</th>'
 1645:        .'<th>'.&mt('Assign Grade').'</th>'
 1646:        .'<th>'.&mt('Weight').'</th>'
 1647:        .'<th>'.&mt('Grade Status').'</th>'
 1648:        .&Apache::loncommon::end_data_table_header_row()
 1649:     );
 1650: }
 1651: 
 1652: sub gradeBox_end {
 1653:     return (
 1654:         &Apache::loncommon::end_data_table()
 1655:     );
 1656: }
 1657: #--- displays the grading box, used in essay type problem and grading by page/sequence
 1658: sub gradeBox {
 1659:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 1660:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1661: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 1662:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 1663:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
 1664:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
 1665:     $wgt       = ($wgt > 0 ? $wgt : '1');
 1666:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 1667: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 1668:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 1669:     my $display_part= &get_display_part($partid,$symb);
 1670:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 1671: 				       [$partid]);
 1672:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 1673:     if ($last_resets{$partid}) {
 1674:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 1675:     }
 1676:     $result.=&Apache::loncommon::start_data_table_row();
 1677:     my $ctr = 0;
 1678:     my $thisweight = 0;
 1679:     my $increment = &get_increment();
 1680: 
 1681:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 1682:     while ($thisweight<=$wgt) {
 1683: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 1684:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 1685: 	    $thisweight.')" value="'.$thisweight.'" '.
 1686: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 1687: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 1688:         $thisweight += $increment;
 1689: 	$ctr++;
 1690:     }
 1691:     $radio.='</tr></table>';
 1692: 
 1693:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 1694: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 1695: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 1696: 	$wgt.')" /></td>'."\n";
 1697:     $line.='<td>/'.$wgt.' '.$wgtmsg.
 1698: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 1699: 	' </td>'."\n";
 1700:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
 1701: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 1702:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 1703: 	$line.='<option></option>'.
 1704: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
 1705:     } else {
 1706: 	$line.='<option selected="selected"></option>'.
 1707: 	    '<option value="excused" >'.&mt('excused').'</option>';
 1708:     }
 1709:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
 1710: 
 1711: 
 1712:     $result .= 
 1713: 	    '<td>'.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
 1714:     $result.=&Apache::loncommon::end_data_table_row();
 1715:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 1716: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 1717: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 1718: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 1719:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 1720:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 1721:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 1722:         $aggtries.'" />'."\n";
 1723:     my $res_error;
 1724:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
 1725:     if ($res_error) {
 1726:         return &navmap_errormsg();
 1727:     }
 1728:     return $result;
 1729: }
 1730: 
 1731: sub handback_box {
 1732:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
 1733:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error_pointer);
 1734:     my (@respids);
 1735:      my @part_response_id = &flatten_responseType($responseType);
 1736:     foreach my $part_response_id (@part_response_id) {
 1737:     	my ($part,$resp) = @{ $part_response_id };
 1738:         if ($part eq $partid) {
 1739:             push(@respids,$resp);
 1740:         }
 1741:     }
 1742:     my $result;
 1743:     foreach my $respid (@respids) {
 1744: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 1745: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 1746: 	next if (!@$files);
 1747: 	my $file_counter = 1;
 1748: 	foreach my $file (@$files) {
 1749: 	    if ($file =~ /\/portfolio\//) {
 1750:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 1751:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
 1752:     	        $file_disp = "$name.$ext";
 1753:     	        $file = $file_path.$file_disp;
 1754:     	        $result.=&mt('Return commented version of [_1] to student.',
 1755:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 1756:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 1757:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
 1758:     	        $result.='('.&mt('File will be uploaded when you click on Save &amp; Next below.').')<br />';
 1759:     	        $file_counter++;
 1760: 	    }
 1761: 	}
 1762:     }
 1763:     return $result;    
 1764: }
 1765: 
 1766: sub show_problem {
 1767:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 1768:     my $rendered;
 1769:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 1770:     &Apache::lonxml::remember_problem_counter();
 1771:     if ($mode eq 'both' or $mode eq 'text') {
 1772: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 1773: 						       $env{'request.course.id'},
 1774: 						       undef,\%form);
 1775:     }
 1776:     if ($removeform) {
 1777: 	$rendered=~s|<form(.*?)>||g;
 1778: 	$rendered=~s|</form>||g;
 1779: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 1780:     }
 1781:     my $companswer;
 1782:     if ($mode eq 'both' or $mode eq 'answer') {
 1783: 	&Apache::lonxml::restore_problem_counter();
 1784: 	$companswer=
 1785: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 1786: 						    $env{'request.course.id'},
 1787: 						    %form);
 1788:     }
 1789:     if ($removeform) {
 1790: 	$companswer=~s|<form(.*?)>||g;
 1791: 	$companswer=~s|</form>||g;
 1792: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 1793:     }
 1794:     $rendered=
 1795:         '<div class="LC_Box">'
 1796:        .'<h3 class="LC_hcell">'.&mt('View of the problem').'</h3>'
 1797:        .$rendered
 1798:        .'</div>';
 1799:     $companswer=
 1800:         '<div class="LC_Box">'
 1801:        .'<h3 class="LC_hcell">'.&mt('Correct answer').'</h3>'
 1802:        .$companswer
 1803:        .'</div>';
 1804:     my $result;
 1805:     if ($mode eq 'both') {
 1806:         $result=$rendered.$companswer;
 1807:     } elsif ($mode eq 'text') {
 1808:         $result=$rendered;
 1809:     } elsif ($mode eq 'answer') {
 1810:         $result=$companswer;
 1811:     }
 1812:     return $result;
 1813: }
 1814: 
 1815: sub files_exist {
 1816:     my ($r, $symb) = @_;
 1817:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1818: 
 1819:     foreach my $student (@students) {
 1820:         my ($uname,$udom,$fullname) = split(/:/,$student);
 1821:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 1822: 					      $udom,$uname);
 1823:         my ($string,$timestamp)= &get_last_submission(\%record);
 1824:         foreach my $submission (@$string) {
 1825:             my ($partid,$respid) =
 1826: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 1827:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 1828: 					   \%record);
 1829:             return 1 if (@$files);
 1830:         }
 1831:     }
 1832:     return 0;
 1833: }
 1834: 
 1835: sub download_all_link {
 1836:     my ($r,$symb) = @_;
 1837:     unless (&files_exist($r, $symb)) {
 1838:        $r->print(&mt('There are currently no submitted documents.'));
 1839:        return;
 1840:     }
 1841: 
 1842:     my $all_students = 
 1843: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 1844: 
 1845:     my $parts =
 1846: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 1847: 
 1848:     my $identifier = &Apache::loncommon::get_cgi_id();
 1849:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 1850:                              'cgi.'.$identifier.'.symb' => $symb,
 1851:                              'cgi.'.$identifier.'.parts' => $parts,});
 1852:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 1853: 	      &mt('Download All Submitted Documents').'</a>');
 1854:     return;
 1855: }
 1856: 
 1857: sub submit_download_link {
 1858:     my ($request,$symb) = @_;
 1859:     if (!$symb) { return ''; }
 1860: #FIXME: Figure out which type of problem this is and provide appropriate download
 1861:     &download_all_link($request,$symb);
 1862: }
 1863: 
 1864: sub build_section_inputs {
 1865:     my $section_inputs;
 1866:     if ($env{'form.section'} eq '') {
 1867:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 1868:     } else {
 1869:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 1870:         foreach my $section (@sections) {
 1871:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 1872:         }
 1873:     }
 1874:     return $section_inputs;
 1875: }
 1876: 
 1877: # --------------------------- show submissions of a student, option to grade 
 1878: sub submission {
 1879:     my ($request,$counter,$total,$symb) = @_;
 1880:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 1881:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 1882:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 1883:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 1884: 
 1885:     my $probtitle=&Apache::lonnet::gettitle($symb); 
 1886:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 1887: 
 1888:     if (!&canview($usec)) {
 1889: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
 1890: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
 1891: 			$env{'request.course.id'}.')</span>');
 1892: 	return;
 1893:     }
 1894: 
 1895:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 1896:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 1897:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 1898:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 1899:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1900: 	'" src="'.$request->dir_config('lonIconsURL').
 1901: 	'/check.gif" height="16" border="0" />';
 1902: 
 1903:     my %old_essays;
 1904:     # header info
 1905:     if ($counter == 0) {
 1906: 	&sub_page_js($request);
 1907: 	&sub_page_kw_js($request);
 1908: 
 1909: 	# option to display problem, only once else it cause problems 
 1910:         # with the form later since the problem has a form.
 1911: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 1912: 	    my $mode;
 1913: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 1914: 		$mode='both';
 1915: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 1916: 		$mode='text';
 1917: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 1918: 		$mode='answer';
 1919: 	    }
 1920: 	    &Apache::lonxml::clear_problem_counter();
 1921: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 1922: 	}
 1923: 
 1924: 	# kwclr is the only variable that is guaranteed to be non blank 
 1925:         # if this subroutine has been called once.
 1926: 	my %keyhash = ();
 1927: #	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
 1928:         if (1) {
 1929: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 1930: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 1931: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 1932: 
 1933: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 1934: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 1935: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 1936: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 1937: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 1938: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
 1939: 		$keyhash{$symb.'_subject'} : $probtitle;
 1940: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 1941: 	}
 1942: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 1943: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 1944: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 1945: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 1946: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 1947: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 1948: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 1949: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 1950: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 1951: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 1952: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 1953: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 1954: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 1955: 			&build_section_inputs().
 1956: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 1957: 			'<input type="hidden" name="NCT"'.
 1958: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 1959: #	if ($env{'form.handgrade'} eq 'yes') {
 1960:         if (1) {
 1961: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 1962: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 1963: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 1964: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
 1965: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 1966: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 1967: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 1968: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
 1969: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
 1970: 	    }
 1971: 	}
 1972: 	
 1973: 	my ($cts,$prnmsg) = (1,'');
 1974: 	while ($cts <= $env{'form.savemsgN'}) {
 1975: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 1976: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 1977: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 1978: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 1979: 		'" />'."\n".
 1980: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 1981: 	    $cts++;
 1982: 	}
 1983: 	$request->print($prnmsg);
 1984: 
 1985: #	if ($env{'form.handgrade'} eq 'yes') {
 1986:         if (1) {
 1987: #
 1988: # Print out the keyword options line
 1989: #
 1990: 	    $request->print(<<KEYWORDS);
 1991: &nbsp;<b>Keyword Options:</b>&nbsp;
 1992: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
 1993: <a href="#" onmousedown="javascript:getSel(); return false"
 1994:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
 1995: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
 1996: KEYWORDS
 1997: #
 1998: # Load the other essays for similarity check
 1999: #
 2000:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 2001: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 2002: 	    $apath=&escape($apath);
 2003: 	    $apath=~s/\W/\_/gs;
 2004: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
 2005:         }
 2006:     }
 2007: 
 2008: # This is where output for one specific student would start
 2009:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
 2010:     $request->print(
 2011:         "\n\n"
 2012:        .'<div class="LC_grade_show_user'.$add_class.'">'
 2013:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
 2014:        ."\n"
 2015:     );
 2016: 
 2017:     # Show additional functions if allowed
 2018:     if ($perm{'vgr'}) {
 2019:         $request->print(
 2020:             &Apache::loncommon::track_student_link(
 2021:                 &mt('View recent activity'),
 2022:                 $uname,$udom,'check')
 2023:            .' '
 2024:         );
 2025:     }
 2026:     if ($perm{'opa'}) {
 2027:         $request->print(
 2028:             &Apache::loncommon::pprmlink(
 2029:                 &mt('Set/Change parameters'),
 2030:                 $uname,$udom,$symb,'check'));
 2031:     }
 2032: 
 2033:     # Show Problem
 2034:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2035: 	my $mode;
 2036: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2037: 	    $mode='both';
 2038: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2039: 	    $mode='text';
 2040: 	} elsif ($env{'form.vAns'} eq 'all') {
 2041: 	    $mode='answer';
 2042: 	}
 2043: 	&Apache::lonxml::clear_problem_counter();
 2044: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2045:     }
 2046: 
 2047:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2048:     my $res_error;
 2049:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2050:     if ($res_error) {
 2051:         $request->print(&navmap_errormsg());
 2052:         return;
 2053:     }
 2054: 
 2055:     # Display student info
 2056:     $request->print(($counter == 0 ? '' : '<br />'));
 2057: 
 2058:     my $result='<div class="LC_Box">'
 2059:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
 2060:     $result.='<input type="hidden" name="name'.$counter.
 2061:              '" value="'.$env{'form.fullname'}.'" />'."\n";
 2062: #    if ($env{'form.handgrade'} eq 'no') {
 2063:     if (1) {
 2064:         $result.='<p class="LC_info">'
 2065:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
 2066:                 ."</p>\n";
 2067:     }
 2068: 
 2069:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
 2070:     my $fullname;
 2071:     my $col_fullnames = [];
 2072: #    if ($env{'form.handgrade'} eq 'yes') {
 2073:     if (1) {
 2074: 	(my $sub_result,$fullname,$col_fullnames)=
 2075: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2076: 				 $counter);
 2077: 	$result.=$sub_result;
 2078:     }
 2079:     $request->print($result."\n");
 2080: 
 2081:     # print student answer/submission
 2082:     # Options are (1) Handgraded submission only
 2083:     #             (2) Last submission, includes submission that is not handgraded 
 2084:     #                  (for multi-response type part)
 2085:     #             (3) Last submission plus the parts info
 2086:     #             (4) The whole record for this student
 2087:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
 2088: 	my ($string,$timestamp)= &get_last_submission(\%record);
 2089: 	
 2090: 	my $lastsubonly;
 2091: 
 2092:         if ($$timestamp eq '') {
 2093:             $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
 2094:         } else {
 2095:             $lastsubonly =
 2096:                 '<div class="LC_grade_submissions_body">'
 2097:                .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
 2098: 
 2099: 	    my %seenparts;
 2100: 	    my @part_response_id = &flatten_responseType($responseType);
 2101: 	    foreach my $part (@part_response_id) {
 2102: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
 2103: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
 2104: 
 2105: 		my ($partid,$respid) = @{ $part };
 2106: 		my $display_part=&get_display_part($partid,$symb);
 2107: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2108: 		    if (exists($seenparts{$partid})) { next; }
 2109: 		    $seenparts{$partid}=1;
 2110: 		    my $submitby='<b>Part:</b> '.$display_part.
 2111: 			' <b>Collaborative submission by:</b> '.
 2112: 			'<a href="javascript:viewSubmitter(\''.
 2113: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
 2114: 			'\');" target="_self">'.
 2115: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
 2116: 		    $request->print($submitby);
 2117: 		    next;
 2118: 		}
 2119: 		my $responsetype = $responseType->{$partid}->{$respid};
 2120: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
 2121:                     $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
 2122:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2123:                         ' <span class="LC_internal_info">'.
 2124:                         '('.&mt('Response ID: [_1]',$respid).')'.
 2125:                         '</span>&nbsp; &nbsp;'.
 2126: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
 2127: 		    next;
 2128: 		}
 2129: 		foreach my $submission (@$string) {
 2130: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2131: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2132: 		    my ($ressub,$hide,$subval) = split(/:/,$submission,3);
 2133: 		    # Similarity check
 2134: 		    my $similar='';
 2135: 		    if($env{'form.checkPlag'}){
 2136: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2137: 			    &most_similar($uname,$udom,$subval,\%old_essays);
 2138: 			if ($osim) {
 2139: 			    $osim=int($osim*100.0);
 2140: 			    my %old_course_desc = 
 2141: 				&Apache::lonnet::coursedescription($ocrsid,
 2142: 								   {'one_time' => 1});
 2143: 
 2144:                             if ($hide) {
 2145:                                 $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
 2146:                                          &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
 2147:                             } else {
 2148: 			        $similar="<hr /><h3><span class=\"LC_warning\">".
 2149: 				    &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
 2150: 				        $osim,
 2151: 				        &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
 2152: 				        $old_course_desc{'description'},
 2153: 				        $old_course_desc{'num'},
 2154: 				        $old_course_desc{'domain'}).
 2155: 				    '</span></h3><blockquote><i>'.
 2156: 				    &keywords_highlight($oessay).
 2157: 				    '</i></blockquote><hr />';
 2158:                             }
 2159: 			}
 2160: 		    }
 2161: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
 2162: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
 2163: 			($env{'form.lastSub'} eq 'hdgrade' && 
 2164: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
 2165: 			my $display_part=&get_display_part($partid,$symb);
 2166:                         $lastsubonly.='<div class="LC_grade_submission_part">'.
 2167:                             '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2168:                             ' <span class="LC_internal_info">'.
 2169:                             '('.&mt('Response ID: [_1]',$respid).')'.
 2170:                             '</span>&nbsp; &nbsp;';
 2171: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2172: 			if (@$files) {
 2173:                             if ($hide) {
 2174:                                 $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
 2175:                             } else {
 2176:                                 $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
 2177:                                 foreach my $file (@$files) {
 2178:                                     &Apache::lonnet::allowuploaded('/adm/grades',$file);
 2179:                                     $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" /> '.$file.'</a>';
 2180:                                 }
 2181:                             }
 2182: 			    $lastsubonly.='<br />';
 2183: 			}
 2184:                         if ($hide) {
 2185:                             $lastsubonly.='<b>'.&mt('Anonymous Survey').'</b>'; 
 2186:                         } else {
 2187: 			    $lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
 2188: 			        &cleanRecord($subval,$responsetype,$symb,$partid,
 2189: 					     $respid,\%record,$order,undef,$uname,$udom);
 2190:                         }
 2191: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2192: 			$lastsubonly.='</div>';
 2193: 		    }
 2194: 		}
 2195: 	    }
 2196: 	    $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
 2197: 	}
 2198: 	$request->print($lastsubonly);
 2199:    } elsif ($env{'form.lastSub'} eq 'datesub') {
 2200:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2201: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2202:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2203: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2204: 								 $env{'request.course.id'},
 2205: 								 $last,'.submission',
 2206: 								 'Apache::grades::keywords_highlight'));
 2207:     }
 2208:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2209: 	.$udom.'" />'."\n");
 2210:     # return if view submission with no grading option
 2211:     if (!&canmodify($usec)) {
 2212: 	$request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
 2213: 	return;
 2214:     } else {
 2215: 	$request->print('</div>'."\n");
 2216:     }
 2217: 
 2218:     # essay grading message center
 2219: #    if ($env{'form.handgrade'} eq 'yes') {
 2220:     if (1) {
 2221: 	my $result='<div class="LC_grade_message_center">';
 2222:     
 2223: 	$result.='<div class="LC_grade_message_center_header">'.
 2224: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
 2225: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2226: 	my $msgfor = $givenn.' '.$lastname;
 2227: 	if (scalar(@$col_fullnames) > 0) {
 2228: 	    my $lastone = pop(@$col_fullnames);
 2229: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2230: 	}
 2231: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2232: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2233: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
 2234: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2235: 	    ',\''.$msgfor.'\');" target="_self">'.
 2236: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
 2237: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2238: 	    '<img src="'.$request->dir_config('lonIconsURL').
 2239: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
 2240: 	    '<br />&nbsp;('.
 2241: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
 2242: 	$result.='</div></div>';
 2243: 	$request->print($result);
 2244:     }
 2245: 
 2246:     my %seen = ();
 2247:     my @partlist;
 2248:     my @gradePartRespid;
 2249:     my @part_response_id = &flatten_responseType($responseType);
 2250:     $request->print(
 2251:         '<div class="LC_Box">'
 2252:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
 2253:     );
 2254:     $request->print(&gradeBox_start());
 2255:     foreach my $part_response_id (@part_response_id) {
 2256:     	my ($partid,$respid) = @{ $part_response_id };
 2257: 	my $part_resp = join('_',@{ $part_response_id });
 2258: 	next if ($seen{$partid} > 0);
 2259: 	$seen{$partid}++;
 2260: 	next if ($$handgrade{$part_resp} ne 'yes' 
 2261: 		 && $env{'form.lastSub'} eq 'hdgrade');
 2262: 	push(@partlist,$partid);
 2263: 	push(@gradePartRespid,$partid.'.'.$respid);
 2264: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2265:     }
 2266:     $request->print(&gradeBox_end()); # </div>
 2267:     $request->print('</div>');
 2268: 
 2269:     $request->print('<div class="LC_grade_info_links">');
 2270:     $request->print('</div>');
 2271: 
 2272:     $result='<input type="hidden" name="partlist'.$counter.
 2273: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2274:     $result.='<input type="hidden" name="gradePartRespid'.
 2275: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2276:     my $ctr = 0;
 2277:     while ($ctr < scalar(@partlist)) {
 2278: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2279: 	    $partlist[$ctr].'" />'."\n";
 2280: 	$ctr++;
 2281:     }
 2282:     $request->print($result.''."\n");
 2283: 
 2284: # Done with printing info for one student
 2285: 
 2286:     $request->print('</div>');#LC_grade_show_user
 2287: 
 2288: 
 2289:     # print end of form
 2290:     if ($counter == $total) {
 2291:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
 2292: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2293: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
 2294: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2295: 	my $ntstu ='<select name="NTSTU">'.
 2296: 	    '<option>1</option><option>2</option>'.
 2297: 	    '<option>3</option><option>5</option>'.
 2298: 	    '<option>7</option><option>10</option></select>'."\n";
 2299: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2300: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2301:         $endform.=&mt('[_1]student(s)',$ntstu);
 2302: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2303: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2304: 	    '<input type="button" value="'.&mt('Next').'" '.
 2305: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2306:         $endform.='<span class="LC_warning">'.
 2307:                   &mt('(Next and Previous (student) do not save the scores.)').
 2308:                   '</span>'."\n" ;
 2309:         $endform.="<input type='hidden' value='".&get_increment().
 2310:             "' name='increment' />";
 2311: 	$endform.='</td></tr></table></form>';
 2312: 	$request->print($endform);
 2313:     }
 2314:     return '';
 2315: }
 2316: 
 2317: sub check_collaborators {
 2318:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2319:     my ($result,@col_fullnames);
 2320:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2321:     foreach my $part (keys(%$handgrade)) {
 2322: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2323: 					'.maxcollaborators',
 2324: 					$symb,$udom,$uname);
 2325: 	next if ($ncol <= 0);
 2326: 	$part =~ s/\_/\./g;
 2327: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2328: 	my (@good_collaborators, @bad_collaborators);
 2329: 	foreach my $possible_collaborator
 2330: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2331: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2332: 	    next if ($possible_collaborator eq '');
 2333: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
 2334: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2335: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2336: 	    # Doing this grep allows 'fuzzy' specification
 2337: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2338: 			       keys(%$classlist));
 2339: 	    if (! scalar(@matches)) {
 2340: 		push(@bad_collaborators, $possible_collaborator);
 2341: 	    } else {
 2342: 		push(@good_collaborators, @matches);
 2343: 	    }
 2344: 	}
 2345: 	if (scalar(@good_collaborators) != 0) {
 2346: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
 2347: 	    foreach my $name (@good_collaborators) {
 2348: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2349: 		push(@col_fullnames, $givenn.' '.$lastname);
 2350: 		$result.='<li>'.$fullname->{$name}.'</li>';
 2351: 	    }
 2352: 	    $result.='</ol><br />'."\n";
 2353: 	    my ($part)=split(/\./,$part);
 2354: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2355: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2356: 		"\n";
 2357: 	}
 2358: 	if (scalar(@bad_collaborators) > 0) {
 2359: 	    $result.='<div class="LC_warning">';
 2360: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2361: 	    $result .= '</div>';
 2362: 	}         
 2363: 	if (scalar(@bad_collaborators > $ncol)) {
 2364: 	    $result .= '<div class="LC_warning">';
 2365: 	    $result .= &mt('This student has submitted too many '.
 2366: 		'collaborators.  Maximum is [_1].',$ncol);
 2367: 	    $result .= '</div>';
 2368: 	}
 2369:     }
 2370:     return ($result,$fullname,\@col_fullnames);
 2371: }
 2372: 
 2373: #--- Retrieve the last submission for all the parts
 2374: sub get_last_submission {
 2375:     my ($returnhash)=@_;
 2376:     my (@string,$timestamp,%lasthidden);
 2377:     if ($$returnhash{'version'}) {
 2378: 	my %lasthash=();
 2379: 	my ($version);
 2380: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2381: 	    foreach my $key (sort(split(/\:/,
 2382: 					$$returnhash{$version.':keys'}))) {
 2383: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2384: 		$timestamp = 
 2385: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2386: 	    }
 2387: 	}
 2388:         my %typeparts;
 2389:         my $showsurv = 
 2390:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
 2391:         foreach my $key (sort(keys(%lasthash))) {
 2392:             if ($key =~ /\.type$/) {
 2393:                 if (($lasthash{$key} eq 'anonsurvey') || 
 2394:                     ($lasthash{$key} eq 'anonsurveycred')) {
 2395:                     my ($ign,@parts) = split(/\./,$key);
 2396:                     pop(@parts);
 2397:                     unless ($showsurv) {
 2398:                         my $id = join(',',@parts);
 2399:                         $typeparts{$ign.'.'.$id} = $lasthash{$key};
 2400:                     }
 2401:                     delete($lasthash{$key});
 2402:                 }
 2403:             }
 2404:         }
 2405:         my @hidden = keys(%typeparts);
 2406: 	foreach my $key (keys(%lasthash)) {
 2407: 	    next if ($key !~ /\.submission$/);
 2408:             my $hide;
 2409:             if (@hidden) {
 2410:                 foreach my $id (@hidden) {
 2411:                     if ($key =~ /^\Q$id\E/) {
 2412:                         $hide = 1;
 2413:                         last;
 2414:                     }
 2415:                 }
 2416:             }
 2417: 	    my ($partid,$foo) = split(/submission$/,$key);
 2418: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
 2419: 		'<span class="LC_warning">Draft Copy</span> ' : '';
 2420: 	    push(@string, join(':', $key, $hide, $draft.$lasthash{$key}));
 2421: 	}
 2422:     }
 2423:     if (!@string) {
 2424: 	$string[0] =
 2425: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
 2426:     }
 2427:     return (\@string,\$timestamp);
 2428: }
 2429: 
 2430: #--- High light keywords, with style choosen by user.
 2431: sub keywords_highlight {
 2432:     my $string    = shift;
 2433:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2434:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2435:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2436:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2437:     foreach my $keyword (@keylist) {
 2438: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2439:     }
 2440:     return $string;
 2441: }
 2442: 
 2443: #--- Called from submission routine
 2444: sub processHandGrade {
 2445:     my ($request,$symb) = @_;
 2446:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2447:     my $button = $env{'form.gradeOpt'};
 2448:     my $ngrade = $env{'form.NCT'};
 2449:     my $ntstu  = $env{'form.NTSTU'};
 2450:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2451:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 2452: 
 2453:     if ($button eq 'Save & Next') {
 2454: 	my $ctr = 0;
 2455: 	while ($ctr < $ngrade) {
 2456: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 2457: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 2458: 	    if ($errorflag eq 'no_score') {
 2459: 		$ctr++;
 2460: 		next;
 2461: 	    }
 2462: 	    if ($errorflag eq 'not_allowed') {
 2463: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
 2464: 		$ctr++;
 2465: 		next;
 2466: 	    }
 2467: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 2468: 	    my ($subject,$message,$msgstatus) = ('','','');
 2469: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 2470:             my ($feedurl,$showsymb) =
 2471: 		&get_feedurl_and_symb($symb,$uname,$udom);
 2472: 	    my $messagetail;
 2473: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 2474: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 2475: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 2476: 		$subject.=' ['.$restitle.']';
 2477: 		my (@msgnum) = split(/,/,$includemsg);
 2478: 		foreach (@msgnum) {
 2479: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 2480: 		}
 2481: 		$message =&Apache::lonfeedback::clear_out_html($message);
 2482: 		if ($env{'form.withgrades'.$ctr}) {
 2483: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 2484: 		    $messagetail = " for <a href=\"".
 2485: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
 2486: 		}
 2487: 		$msgstatus = 
 2488:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 2489: 						     $message.$messagetail,
 2490:                                                      undef,$feedurl,undef,
 2491:                                                      undef,undef,$showsymb,
 2492:                                                      $restitle);
 2493: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
 2494: 				$msgstatus);
 2495: 	    }
 2496: 	    if ($env{'form.collaborator'.$ctr}) {
 2497: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 2498: 		foreach my $collabstr (@collabstrs) {
 2499: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 2500: 		    foreach my $collaborator (@collaborators) {
 2501: 			my ($errorflag,$pts,$wgt) = 
 2502: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 2503: 					   $env{'form.unamedom'.$ctr},$part);
 2504: 			if ($errorflag eq 'not_allowed') {
 2505: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 2506: 			    next;
 2507: 			} elsif ($message ne '') {
 2508: 			    my ($baseurl,$showsymb) = 
 2509: 				&get_feedurl_and_symb($symb,$collaborator,
 2510: 						      $udom);
 2511: 			    if ($env{'form.withgrades'.$ctr}) {
 2512: 				$messagetail = " for <a href=\"".
 2513:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
 2514: 			    }
 2515: 			    $msgstatus = 
 2516: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 2517: 			}
 2518: 		    }
 2519: 		}
 2520: 	    }
 2521: 	    $ctr++;
 2522: 	}
 2523:     }
 2524: 
 2525: #    if ($env{'form.handgrade'} eq 'yes') {
 2526:     if (1) {
 2527: 	# Keywords sorted in alphabatical order
 2528: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2529: 	my %keyhash = ();
 2530: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 2531: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 2532: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 2533: 	$env{'form.keywords'} = join(' ',@keywords);
 2534: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 2535: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 2536: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 2537: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 2538: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 2539: 
 2540: 	# message center - Order of message gets changed. Blank line is eliminated.
 2541: 	# New messages are saved in env for the next student.
 2542: 	# All messages are saved in nohist_handgrade.db
 2543: 	my ($ctr,$idx) = (1,1);
 2544: 	while ($ctr <= $env{'form.savemsgN'}) {
 2545: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 2546: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 2547: 		$idx++;
 2548: 	    }
 2549: 	    $ctr++;
 2550: 	}
 2551: 	$ctr = 0;
 2552: 	while ($ctr < $ngrade) {
 2553: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 2554: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2555: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2556: 		$idx++;
 2557: 	    }
 2558: 	    $ctr++;
 2559: 	}
 2560: 	$env{'form.savemsgN'} = --$idx;
 2561: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 2562: 	my $putresult = &Apache::lonnet::put
 2563: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 2564:     }
 2565:     # Called by Save & Refresh from Highlight Attribute Window
 2566:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 2567:     if ($env{'form.refresh'} eq 'on') {
 2568: 	my ($ctr,$total) = (0,0);
 2569: 	while ($ctr < $ngrade) {
 2570: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 2571: 	    $ctr++;
 2572: 	}
 2573: 	$env{'form.NTSTU'}=$ngrade;
 2574: 	$ctr = 0;
 2575: 	while ($ctr < $total) {
 2576: 	    my $processUser = $env{'form.unamedom'.$ctr};
 2577: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2578: 	    $env{'form.fullname'} = $$fullname{$processUser};
 2579: 	    &submission($request,$ctr,$total-1,$symb);
 2580: 	    $ctr++;
 2581: 	}
 2582: 	return '';
 2583:     }
 2584: 
 2585:     # Get the next/previous one or group of students
 2586:     my $firststu = $env{'form.unamedom0'};
 2587:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 2588:     my $ctr = 2;
 2589:     while ($laststu eq '') {
 2590: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 2591: 	$ctr++;
 2592: 	$laststu = $firststu if ($ctr > $ngrade);
 2593:     }
 2594: 
 2595:     my (@parsedlist,@nextlist);
 2596:     my ($nextflg) = 0;
 2597:     foreach my $item (sort 
 2598: 	     {
 2599: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 2600: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 2601: 		 }
 2602: 		 return $a cmp $b;
 2603: 	     } (keys(%$fullname))) {
 2604: # FIXME: this is fishy, looks like the button label
 2605: 	if ($nextflg == 1 && $button =~ /Next$/) {
 2606: 	    push(@parsedlist,$item);
 2607: 	}
 2608: 	$nextflg = 1 if ($item eq $laststu);
 2609: 	if ($button eq 'Previous') {
 2610: 	    last if ($item eq $firststu);
 2611: 	    push(@parsedlist,$item);
 2612: 	}
 2613:     }
 2614:     $ctr = 0;
 2615: # FIXME: this is fishy, looks like the button label
 2616:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 2617:     my $res_error;
 2618:     my ($partlist) = &response_type($symb,\$res_error);
 2619:     if ($res_error) {
 2620:         $request->print(&navmap_errormsg());
 2621:         return;
 2622:     }
 2623:     foreach my $student (@parsedlist) {
 2624: 	my $submitonly=$env{'form.submitonly'};
 2625: 	my ($uname,$udom) = split(/:/,$student);
 2626: 	
 2627: 	if ($submitonly eq 'queued') {
 2628: 	    my %queue_status = 
 2629: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 2630: 							$udom,$uname);
 2631: 	    next if (!defined($queue_status{'gradingqueue'}));
 2632: 	}
 2633: 
 2634: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 2635: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2636: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 2637: 	    my $submitted = 0;
 2638: 	    my $ungraded = 0;
 2639: 	    my $incorrect = 0;
 2640: 	    foreach my $item (keys(%status)) {
 2641: 		$submitted = 1 if ($status{$item} ne 'nothing');
 2642: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 2643: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 2644: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 2645: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 2646: 		    $submitted = 0;
 2647: 		}
 2648: 	    }
 2649: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 2650: 				     $submitonly eq 'incorrect' ||
 2651: 				     $submitonly eq 'graded'));
 2652: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 2653: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 2654: 	}
 2655: 	push(@nextlist,$student) if ($ctr < $ntstu);
 2656: 	last if ($ctr == $ntstu);
 2657: 	$ctr++;
 2658:     }
 2659: 
 2660:     $ctr = 0;
 2661:     my $total = scalar(@nextlist)-1;
 2662: 
 2663:     foreach (sort(@nextlist)) {
 2664: 	my ($uname,$udom,$submitter) = split(/:/);
 2665: 	$env{'form.student'}  = $uname;
 2666: 	$env{'form.userdom'}  = $udom;
 2667: 	$env{'form.fullname'} = $$fullname{$_};
 2668: 	&submission($request,$ctr,$total,$symb);
 2669: 	$ctr++;
 2670:     }
 2671:     if ($total < 0) {
 2672: 	my $the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
 2673: 	$request->print($the_end);
 2674:     }
 2675:     return '';
 2676: }
 2677: 
 2678: #---- Save the score and award for each student, if changed
 2679: sub saveHandGrade {
 2680:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 2681:     my @version_parts;
 2682:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 2683: 					   $env{'request.course.id'});
 2684:     if (!&canmodify($usec)) { return('not_allowed'); }
 2685:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 2686:     my @parts_graded;
 2687:     my %newrecord  = ();
 2688:     my ($pts,$wgt) = ('','');
 2689:     my %aggregate = ();
 2690:     my $aggregateflag = 0;
 2691:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 2692:     foreach my $new_part (@parts) {
 2693: 	#collaborator ($submi may vary for different parts
 2694: 	if ($submitter && $new_part ne $part) { next; }
 2695: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 2696: 	if ($dropMenu eq 'excused') {
 2697: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 2698: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 2699: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 2700: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 2701: 		}
 2702: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 2703: 	    }
 2704: 	} elsif ($dropMenu eq 'reset status'
 2705: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 2706: 	    foreach my $key (keys(%record)) {
 2707: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 2708: 	    }
 2709: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2710: 		"$env{'user.name'}:$env{'user.domain'}";
 2711:             my $totaltries = $record{'resource.'.$part.'.tries'};
 2712: 
 2713:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 2714: 					       [$new_part]);
 2715:             my $aggtries =$totaltries;
 2716:             if ($last_resets{$new_part}) {
 2717:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 2718: 					   $new_part);
 2719:             }
 2720: 
 2721:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 2722:             if ($aggtries > 0) {
 2723:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 2724:                 $aggregateflag = 1;
 2725:             }
 2726: 	} elsif ($dropMenu eq '') {
 2727: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 2728: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 2729: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 2730: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 2731: 		next;
 2732: 	    }
 2733: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 2734: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 2735: 	    my $partial= $pts/$wgt;
 2736: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 2737: 		#do not update score for part if not changed.
 2738:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 2739: 		next;
 2740: 	    } else {
 2741: 	        push(@parts_graded,$new_part);
 2742: 	    }
 2743: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 2744: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 2745: 	    }
 2746: 	    my $reckey = 'resource.'.$new_part.'.solved';
 2747: 	    if ($partial == 0) {
 2748: 		if ($record{$reckey} ne 'incorrect_by_override') {
 2749: 		    $newrecord{$reckey} = 'incorrect_by_override';
 2750: 		}
 2751: 	    } else {
 2752: 		if ($record{$reckey} ne 'correct_by_override') {
 2753: 		    $newrecord{$reckey} = 'correct_by_override';
 2754: 		}
 2755: 	    }	    
 2756: 	    if ($submitter && 
 2757: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 2758: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 2759: 	    }
 2760: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2761: 		"$env{'user.name'}:$env{'user.domain'}";
 2762: 	}
 2763: 	# unless problem has been graded, set flag to version the submitted files
 2764: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 2765: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 2766: 	        $dropMenu eq 'reset status')
 2767: 	   {
 2768: 	    push(@version_parts,$new_part);
 2769: 	}
 2770:     }
 2771:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2772:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2773: 
 2774:     if (%newrecord) {
 2775:         if (@version_parts) {
 2776:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 2777:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 2778: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 2779: 	    foreach my $new_part (@version_parts) {
 2780: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 2781: 				$new_part,\%newrecord);
 2782: 	    }
 2783:         }
 2784: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 2785: 				$env{'request.course.id'},$domain,$stuname);
 2786: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 2787: 				     $cdom,$cnum,$domain,$stuname);
 2788:     }
 2789:     if ($aggregateflag) {
 2790:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 2791: 			      $cdom,$cnum);
 2792:     }
 2793:     return ('',$pts,$wgt);
 2794: }
 2795: 
 2796: sub check_and_remove_from_queue {
 2797:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 2798:     my @ungraded_parts;
 2799:     foreach my $part (@{$parts}) {
 2800: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 2801: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 2802: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 2803: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 2804: 		) {
 2805: 	    push(@ungraded_parts, $part);
 2806: 	}
 2807:     }
 2808:     if ( !@ungraded_parts ) {
 2809: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 2810: 					       $cnum,$domain,$stuname);
 2811:     }
 2812: }
 2813: 
 2814: sub handback_files {
 2815:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 2816:     my $portfolio_root = '/userfiles/portfolio';
 2817:     my $res_error;
 2818:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2819:     if ($res_error) {
 2820:         $request->print('<br />'.&navmap_errormsg().'<br />');
 2821:         return;
 2822:     }
 2823:     my @part_response_id = &flatten_responseType($responseType);
 2824:     foreach my $part_response_id (@part_response_id) {
 2825:     	my ($part_id,$resp_id) = @{ $part_response_id };
 2826: 	my $part_resp = join('_',@{ $part_response_id });
 2827:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
 2828:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
 2829:                 my $file_counter = 1;
 2830: 		my $file_msg;
 2831:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
 2832:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
 2833:                     my ($directory,$answer_file) = 
 2834:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
 2835:                     my ($answer_name,$answer_ver,$answer_ext) =
 2836: 		        &file_name_version_ext($answer_file);
 2837: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 2838:                     my $getpropath = 1;
 2839: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
 2840: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 2841:                     # fix file name
 2842:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 2843:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 2844:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
 2845:             	                                $save_file_name);
 2846:                     if ($result !~ m|^/uploaded/|) {
 2847:                         $request->print('<br /><span class="LC_error">'.
 2848:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 2849:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$file_counter).
 2850:                                         '</span>');
 2851:                     } else {
 2852:                         # mark the file as read only
 2853:                         my @files = ($save_file_name);
 2854:                         my @what = ($symb,$env{'request.course.id'},'handback');
 2855:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
 2856: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 2857: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 2858: 			}
 2859:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 2860: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
 2861: 
 2862:                     }
 2863:                     $request->print("<br />".$fname." will be the uploaded file name");
 2864:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
 2865:                     $file_counter++;
 2866:                 }
 2867: 		my $subject = "File Handed Back by Instructor ";
 2868: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
 2869: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
 2870: 		$message .= ' The returned file(s) are named: '. $file_msg;
 2871: 		$message .= " and can be found in your portfolio space.";
 2872: 		my ($feedurl,$showsymb) = 
 2873: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
 2874:                 my $restitle = &Apache::lonnet::gettitle($symb);
 2875: 		my $msgstatus = 
 2876:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
 2877: 			 ' (File Returned) ['.$restitle.']',$message,undef,
 2878:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
 2879:             }
 2880:         }
 2881:     return;
 2882: }
 2883: 
 2884: sub get_feedurl_and_symb {
 2885:     my ($symb,$uname,$udom) = @_;
 2886:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2887:     $url = &Apache::lonnet::clutter($url);
 2888:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 2889: 					$symb,$udom,$uname);
 2890:     if ($encrypturl =~ /^yes$/i) {
 2891: 	&Apache::lonenc::encrypted(\$url,1);
 2892: 	&Apache::lonenc::encrypted(\$symb,1);
 2893:     }
 2894:     return ($url,$symb);
 2895: }
 2896: 
 2897: sub get_submitted_files {
 2898:     my ($udom,$uname,$partid,$respid,$record) = @_;
 2899:     my @files;
 2900:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 2901:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 2902:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 2903:     	    push(@files,$file_url.$file);
 2904:         }
 2905:     }
 2906:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 2907:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 2908:     }
 2909:     return (\@files);
 2910: }
 2911: 
 2912: # ----------- Provides number of tries since last reset.
 2913: sub get_num_tries {
 2914:     my ($record,$last_reset,$part) = @_;
 2915:     my $timestamp = '';
 2916:     my $num_tries = 0;
 2917:     if ($$record{'version'}) {
 2918:         for (my $version=$$record{'version'};$version>=1;$version--) {
 2919:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 2920:                 $timestamp = $$record{$version.':timestamp'};
 2921:                 if ($timestamp > $last_reset) {
 2922:                     $num_tries ++;
 2923:                 } else {
 2924:                     last;
 2925:                 }
 2926:             }
 2927:         }
 2928:     }
 2929:     return $num_tries;
 2930: }
 2931: 
 2932: # ----------- Determine decrements required in aggregate totals 
 2933: sub decrement_aggs {
 2934:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 2935:     my %decrement = (
 2936:                         attempts => 0,
 2937:                         users => 0,
 2938:                         correct => 0
 2939:                     );
 2940:     $decrement{'attempts'} = $aggtries;
 2941:     if ($solvedstatus =~ /^correct/) {
 2942:         $decrement{'correct'} = 1;
 2943:     }
 2944:     if ($aggtries == $totaltries) {
 2945:         $decrement{'users'} = 1;
 2946:     }
 2947:     foreach my $type (keys(%decrement)) {
 2948:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 2949:     }
 2950:     return;
 2951: }
 2952: 
 2953: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 2954: sub get_last_resets {
 2955:     my ($symb,$courseid,$partids) =@_;
 2956:     my %last_resets;
 2957:     my $cdom = $env{'course.'.$courseid.'.domain'};
 2958:     my $cname = $env{'course.'.$courseid.'.num'};
 2959:     my @keys;
 2960:     foreach my $part (@{$partids}) {
 2961: 	push(@keys,"$symb\0$part\0resettime");
 2962:     }
 2963:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 2964: 				     $cdom,$cname);
 2965:     foreach my $part (@{$partids}) {
 2966: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 2967:     }
 2968:     return %last_resets;
 2969: }
 2970: 
 2971: # ----------- Handles creating versions for portfolio files as answers
 2972: sub version_portfiles {
 2973:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 2974:     my $version_parts = join('|',@$v_flag);
 2975:     my @returned_keys;
 2976:     my $parts = join('|', @$parts_graded);
 2977:     my $portfolio_root = '/userfiles/portfolio';
 2978:     foreach my $key (keys(%$record)) {
 2979:         my $new_portfiles;
 2980:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 2981:             my @versioned_portfiles;
 2982:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 2983:             foreach my $file (@portfiles) {
 2984:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 2985:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 2986: 		my ($answer_name,$answer_ver,$answer_ext) =
 2987: 		    &file_name_version_ext($answer_file);
 2988:                 my $getpropath = 1;    
 2989:                 my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
 2990:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 2991:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
 2992:                 if ($new_answer ne 'problem getting file') {
 2993:                     push(@versioned_portfiles, $directory.$new_answer);
 2994:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
 2995:                         [$directory.$new_answer],
 2996:                         [$symb,$env{'request.course.id'},'graded']);
 2997:                 }
 2998:             }
 2999:             $$record{$key} = join(',',@versioned_portfiles);
 3000:             push(@returned_keys,$key);
 3001:         }
 3002:     } 
 3003:     return (@returned_keys);   
 3004: }
 3005: 
 3006: sub get_next_version {
 3007:     my ($answer_name, $answer_ext, $dir_list) = @_;
 3008:     my $version;
 3009:     foreach my $row (@$dir_list) {
 3010:         my ($file) = split(/\&/,$row,2);
 3011:         my ($file_name,$file_version,$file_ext) =
 3012: 	    &file_name_version_ext($file);
 3013:         if (($file_name eq $answer_name) && 
 3014: 	    ($file_ext eq $answer_ext)) {
 3015:                 # gets here if filename and extension match, regardless of version
 3016:                 if ($file_version ne '') {
 3017:                 # a versioned file is found  so save it for later
 3018:                 if ($file_version > $version) {
 3019: 		    $version = $file_version;
 3020: 	        }
 3021:             }
 3022:         }
 3023:     } 
 3024:     $version ++;
 3025:     return($version);
 3026: }
 3027: 
 3028: sub version_selected_portfile {
 3029:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 3030:     my ($answer_name,$answer_ver,$answer_ext) =
 3031:         &file_name_version_ext($file_name);
 3032:     my $new_answer;
 3033:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 3034:     if($env{'form.copy'} eq '-1') {
 3035:         $new_answer = 'problem getting file';
 3036:     } else {
 3037:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 3038:         my $copy_result = &Apache::lonnet::finishuserfileupload(
 3039:                             $stu_name,$domain,'copy',
 3040: 		        '/portfolio'.$directory.$new_answer);
 3041:     }    
 3042:     return ($new_answer);
 3043: }
 3044: 
 3045: sub file_name_version_ext {
 3046:     my ($file)=@_;
 3047:     my @file_parts = split(/\./, $file);
 3048:     my ($name,$version,$ext);
 3049:     if (@file_parts > 1) {
 3050: 	$ext=pop(@file_parts);
 3051: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 3052: 	    $version=pop(@file_parts);
 3053: 	}
 3054: 	$name=join('.',@file_parts);
 3055:     } else {
 3056: 	$name=join('.',@file_parts);
 3057:     }
 3058:     return($name,$version,$ext);
 3059: }
 3060: 
 3061: #--------------------------------------------------------------------------------------
 3062: #
 3063: #-------------------------- Next few routines handles grading by section or whole class
 3064: #
 3065: #--- Javascript to handle grading by section or whole class
 3066: sub viewgrades_js {
 3067:     my ($request) = shift;
 3068: 
 3069:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3070:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
 3071:    function writePoint(partid,weight,point) {
 3072: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3073: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3074: 	if (point == "textval") {
 3075: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3076: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3077: 		alert("$alertmsg"+parseFloat(point));
 3078: 		var resetbox = false;
 3079: 		for (var i=0; i<radioButton.length; i++) {
 3080: 		    if (radioButton[i].checked) {
 3081: 			textbox.value = i;
 3082: 			resetbox = true;
 3083: 		    }
 3084: 		}
 3085: 		if (!resetbox) {
 3086: 		    textbox.value = "";
 3087: 		}
 3088: 		return;
 3089: 	    }
 3090: 	    if (parseFloat(point) > parseFloat(weight)) {
 3091: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3092: 				   ") greater than the weight for the part. Accept?");
 3093: 		if (resp == false) {
 3094: 		    textbox.value = "";
 3095: 		    return;
 3096: 		}
 3097: 	    }
 3098: 	    for (var i=0; i<radioButton.length; i++) {
 3099: 		radioButton[i].checked=false;
 3100: 		if (parseFloat(point) == i) {
 3101: 		    radioButton[i].checked=true;
 3102: 		}
 3103: 	    }
 3104: 
 3105: 	} else {
 3106: 	    textbox.value = parseFloat(point);
 3107: 	}
 3108: 	for (i=0;i<document.classgrade.total.value;i++) {
 3109: 	    var user = document.classgrade["ctr"+i].value;
 3110: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3111: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3112: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3113: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3114: 	    if (saveval != "correct") {
 3115: 		scorename.value = point;
 3116: 		if (selname[0].selected != true) {
 3117: 		    selname[0].selected = true;
 3118: 		}
 3119: 	    }
 3120: 	}
 3121: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3122:     }
 3123: 
 3124:     function writeRadText(partid,weight) {
 3125: 	var selval   = document.classgrade["SELVAL_"+partid];
 3126: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3127:         var override = document.classgrade["FORCE_"+partid].checked;
 3128: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3129: 	if (selval[1].selected || selval[2].selected) {
 3130: 	    for (var i=0; i<radioButton.length; i++) {
 3131: 		radioButton[i].checked=false;
 3132: 
 3133: 	    }
 3134: 	    textbox.value = "";
 3135: 
 3136: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3137: 		var user = document.classgrade["ctr"+i].value;
 3138: 		user = user.replace(new RegExp(':', 'g'),"_");
 3139: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3140: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3141: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3142: 		if ((saveval != "correct") || override) {
 3143: 		    scorename.value = "";
 3144: 		    if (selval[1].selected) {
 3145: 			selname[1].selected = true;
 3146: 		    } else {
 3147: 			selname[2].selected = true;
 3148: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3149: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3150: 		    }
 3151: 		}
 3152: 	    }
 3153: 	} else {
 3154: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3155: 		var user = document.classgrade["ctr"+i].value;
 3156: 		user = user.replace(new RegExp(':', 'g'),"_");
 3157: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3158: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3159: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3160: 		if ((saveval != "correct") || override) {
 3161: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3162: 		    selname[0].selected = true;
 3163: 		}
 3164: 	    }
 3165: 	}	    
 3166:     }
 3167: 
 3168:     function changeSelect(partid,user) {
 3169: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3170: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3171: 	var point  = textbox.value;
 3172: 	var weight = document.classgrade["weight_"+partid].value;
 3173: 
 3174: 	if (isNaN(point) || parseFloat(point) < 0) {
 3175: 	    alert("$alertmsg"+parseFloat(point));
 3176: 	    textbox.value = "";
 3177: 	    return;
 3178: 	}
 3179: 	if (parseFloat(point) > parseFloat(weight)) {
 3180: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3181: 			       ") greater than the weight of the part. Accept?");
 3182: 	    if (resp == false) {
 3183: 		textbox.value = "";
 3184: 		return;
 3185: 	    }
 3186: 	}
 3187: 	selval[0].selected = true;
 3188:     }
 3189: 
 3190:     function changeOneScore(partid,user) {
 3191: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3192: 	if (selval[1].selected || selval[2].selected) {
 3193: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3194: 	    if (selval[2].selected) {
 3195: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3196: 	    }
 3197:         }
 3198:     }
 3199: 
 3200:     function resetEntry(numpart) {
 3201: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3202: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3203: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3204: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3205: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3206: 	    for (var i=0; i<radioButton.length; i++) {
 3207: 		radioButton[i].checked=false;
 3208: 
 3209: 	    }
 3210: 	    textbox.value = "";
 3211: 	    selval[0].selected = true;
 3212: 
 3213: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3214: 		var user = document.classgrade["ctr"+i].value;
 3215: 		user = user.replace(new RegExp(':', 'g'),"_");
 3216: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3217: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3218: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3219: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3220: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3221: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3222: 		if (saveselval == "excused") {
 3223: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3224: 		} else {
 3225: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3226: 		}
 3227: 	    }
 3228: 	}
 3229:     }
 3230: 
 3231: VIEWJAVASCRIPT
 3232: }
 3233: 
 3234: #--- show scores for a section or whole class w/ option to change/update a score
 3235: sub viewgrades {
 3236:     my ($request,$symb) = @_;
 3237:     &viewgrades_js($request);
 3238: 
 3239:     #need to make sure we have the correct data for later EXT calls, 
 3240:     #thus invalidate the cache
 3241:     &Apache::lonnet::devalidatecourseresdata(
 3242:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3243:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3244:     &Apache::lonnet::clear_EXT_cache_status();
 3245: 
 3246:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3247: 
 3248:     #view individual student submission form - called using Javascript viewOneStudent
 3249:     $result.=&jscriptNform($symb);
 3250: 
 3251:     #beginning of class grading form
 3252:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3253:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3254: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3255: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3256: 	&build_section_inputs().
 3257: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3258: 
 3259:     my ($common_header,$specific_header);
 3260:     if ($env{'form.section'} eq 'all') {
 3261: 	$common_header = &mt('Assign Common Grade to Class');
 3262:         $specific_header = &mt('Assign Grade to Specific Students in Class');
 3263:     } elsif ($env{'form.section'} eq 'none') {
 3264:         $common_header = &mt('Assign Common Grade to Students in no Section');
 3265: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
 3266:     } else {
 3267:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3268:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
 3269: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
 3270:     }
 3271:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
 3272:     #radio buttons/text box for assigning points for a section or class.
 3273:     #handles different parts of a problem
 3274:     my $res_error;
 3275:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3276:     if ($res_error) {
 3277:         return &navmap_errormsg();
 3278:     }
 3279:     my %weight = ();
 3280:     my $ctsparts = 0;
 3281:     my %seen = ();
 3282:     my @part_response_id = &flatten_responseType($responseType);
 3283:     foreach my $part_response_id (@part_response_id) {
 3284:     	my ($partid,$respid) = @{ $part_response_id };
 3285: 	my $part_resp = join('_',@{ $part_response_id });
 3286: 	next if $seen{$partid};
 3287: 	$seen{$partid}++;
 3288: 	my $handgrade=$$handgrade{$part_resp};
 3289: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 3290: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 3291: 
 3292: 	my $display_part=&get_display_part($partid,$symb);
 3293: 	my $radio.='<table border="0"><tr>';  
 3294: 	my $ctr = 0;
 3295: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 3296: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 3297: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 3298: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 3299: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 3300: 	    $ctr++;
 3301: 	}
 3302: 	$radio.='</tr></table>';
 3303: 	my $line = '<input type="text" name="TEXTVAL_'.
 3304: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
 3305: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 3306: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 3307: 	$line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
 3308: 	    'onchange="javascript:writeRadText(\''.$partid.'\','.
 3309: 		$weight{$partid}.')"> '.
 3310: 	    '<option selected="selected"> </option>'.
 3311: 	    '<option value="excused">'.&mt('excused').'</option>'.
 3312: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 3313: 	    '</select></td>'.
 3314:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 3315: 	$line.='<input type="hidden" name="partid_'.
 3316: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 3317: 	$line.='<input type="hidden" name="weight_'.
 3318: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 3319: 
 3320: 	$result.=
 3321: 	    &Apache::loncommon::start_data_table_row()."\n".
 3322: 	    '<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>'.
 3323: 	    &Apache::loncommon::end_data_table_row()."\n";
 3324: 	$ctsparts++;
 3325:     }
 3326:     $result.=&Apache::loncommon::end_data_table()."\n".
 3327: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 3328:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 3329: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
 3330: 
 3331:     #table listing all the students in a section/class
 3332:     #header of table
 3333:     $result.= '<h3>'.$specific_header.'</h3>'.
 3334:               &Apache::loncommon::start_data_table().
 3335: 	      &Apache::loncommon::start_data_table_header_row().
 3336: 	      '<th>'.&mt('No.').'</th>'.
 3337: 	      '<th>'.&nameUserString('header')."</th>\n";
 3338:     my $partserror;
 3339:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3340:     if ($partserror) {
 3341:         return &navmap_errormsg();
 3342:     }
 3343:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 3344:     my @partids = ();
 3345:     foreach my $part (@parts) {
 3346: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3347:         my $narrowtext = &mt('Tries');
 3348: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 3349: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 3350: 	my ($partid) = &split_part_type($part);
 3351:         push(@partids,$partid);
 3352: #
 3353: # FIXME: Looks like $display looks at English text
 3354: #
 3355: 	my $display_part=&get_display_part($partid,$symb);
 3356: 	if ($display =~ /^Partial Credit Factor/) {
 3357: 	    $result.='<th>'.
 3358: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
 3359: 		    $display_part,$weight{$partid}).'</th>'."\n";
 3360: 	    next;
 3361: 	    
 3362: 	} else {
 3363: 	    if ($display =~ /Problem Status/) {
 3364: 		my $grade_status_mt = &mt('Grade Status');
 3365: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 3366: 	    }
 3367: 	    my $part_mt = &mt('Part:');
 3368: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 3369: 	}
 3370: 
 3371: 	$result.='<th>'.$display.'</th>'."\n";
 3372:     }
 3373:     $result.=&Apache::loncommon::end_data_table_header_row();
 3374: 
 3375:     my %last_resets = 
 3376: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 3377: 
 3378:     #get info for each student
 3379:     #list all the students - with points and grade status
 3380:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3381:     my $ctr = 0;
 3382:     foreach (sort 
 3383: 	     {
 3384: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3385: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3386: 		 }
 3387: 		 return $a cmp $b;
 3388: 	     } (keys(%$fullname))) {
 3389: 	$ctr++;
 3390: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 3391: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
 3392:     }
 3393:     $result.=&Apache::loncommon::end_data_table();
 3394:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 3395:     $result.='<input type="button" value="'.&mt('Save').'" '.
 3396: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
 3397:     if (scalar(%$fullname) eq 0) {
 3398: 	my $colspan=3+scalar(@parts);
 3399: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3400:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 3401: 	$result='<span class="LC_warning">'.
 3402: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 3403: 	        $section_display, $stu_status).
 3404: 	    '</span>';
 3405:     }
 3406:     return $result;
 3407: }
 3408: 
 3409: #--- call by previous routine to display each student
 3410: sub viewstudentgrade {
 3411:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 3412:     my ($uname,$udom) = split(/:/,$student);
 3413:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 3414:     my %aggregates = (); 
 3415:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 3416: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
 3417: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
 3418: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 3419: 	'\');" target="_self">'.$fullname.'</a> '.
 3420: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 3421:     $student=~s/:/_/; # colon doen't work in javascript for names
 3422:     foreach my $apart (@$parts) {
 3423: 	my ($part,$type) = &split_part_type($apart);
 3424: 	my $score=$record{"resource.$part.$type"};
 3425:         $result.='<td align="center">';
 3426:         my ($aggtries,$totaltries);
 3427:         unless (exists($aggregates{$part})) {
 3428: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 3429: 
 3430: 	    $aggtries = $totaltries;
 3431:             if ($$last_resets{$part}) {  
 3432:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 3433: 					   $part);
 3434:             }
 3435:             $result.='<input type="hidden" name="'.
 3436:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 3437:             $result.='<input type="hidden" name="'.
 3438:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 3439:             $aggregates{$part} = 1;
 3440:         }
 3441: 	if ($type eq 'awarded') {
 3442: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 3443: 	    $result.='<input type="hidden" name="'.
 3444: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 3445: 	    $result.='<input type="text" name="'.
 3446: 		'GD_'.$student.'_'.$part.'_awarded" '.
 3447:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
 3448: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 3449: 	} elsif ($type eq 'solved') {
 3450: 	    my ($status,$foo)=split(/_/,$score,2);
 3451: 	    $status = 'nothing' if ($status eq '');
 3452: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 3453: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 3454: 	    $result.='&nbsp;<select name="'.
 3455: 		'GD_'.$student.'_'.$part.'_solved" '.
 3456:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 3457: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 3458: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 3459: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 3460: 	    $result.="</select>&nbsp;</td>\n";
 3461: 	} else {
 3462: 	    $result.='<input type="hidden" name="'.
 3463: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 3464: 		    "\n";
 3465: 	    $result.='<input type="text" name="'.
 3466: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 3467: 		'value="'.$score.'" size="4" /></td>'."\n";
 3468: 	}
 3469:     }
 3470:     $result.=&Apache::loncommon::end_data_table_row();
 3471:     return $result;
 3472: }
 3473: 
 3474: #--- change scores for all the students in a section/class
 3475: #    record does not get update if unchanged
 3476: sub editgrades {
 3477:     my ($request,$symb) = @_;
 3478: 
 3479:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3480:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 3481:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
 3482: 
 3483:     my $result= &Apache::loncommon::start_data_table().
 3484: 	&Apache::loncommon::start_data_table_header_row().
 3485: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 3486: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 3487:     my %scoreptr = (
 3488: 		    'correct'  =>'correct_by_override',
 3489: 		    'incorrect'=>'incorrect_by_override',
 3490: 		    'excused'  =>'excused',
 3491: 		    'ungraded' =>'ungraded_attempted',
 3492:                     'credited' =>'credit_attempted',
 3493: 		    'nothing'  => '',
 3494: 		    );
 3495:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 3496: 
 3497:     my (@partid);
 3498:     my %weight = ();
 3499:     my %columns = ();
 3500:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 3501: 
 3502:     my $partserror;
 3503:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3504:     if ($partserror) {
 3505:         return &navmap_errormsg();
 3506:     }
 3507:     my $header;
 3508:     while ($ctr < $env{'form.totalparts'}) {
 3509: 	my $partid = $env{'form.partid_'.$ctr};
 3510: 	push(@partid,$partid);
 3511: 	$weight{$partid} = $env{'form.weight_'.$partid};
 3512: 	$ctr++;
 3513:     }
 3514:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3515:     foreach my $partid (@partid) {
 3516: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 3517: 	    '<th align="center">'.&mt('New Score').'</th>';
 3518: 	$columns{$partid}=2;
 3519: 	foreach my $stores (@parts) {
 3520: 	    my ($part,$type) = &split_part_type($stores);
 3521: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 3522: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 3523: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 3524: 	    $display =~ s/\[Part: \Q$part\E\]//;
 3525:             my $narrowtext = &mt('Tries');
 3526: 	    $display =~ s/Number of Attempts/$narrowtext/;
 3527: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 3528: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 3529: 	    $columns{$partid}+=2;
 3530: 	}
 3531:     }
 3532:     foreach my $partid (@partid) {
 3533: 	my $display_part=&get_display_part($partid,$symb);
 3534: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 3535: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 3536: 	    '</th>';
 3537: 
 3538:     }
 3539:     $result .= &Apache::loncommon::end_data_table_header_row().
 3540: 	&Apache::loncommon::start_data_table_header_row().
 3541: 	$header.
 3542: 	&Apache::loncommon::end_data_table_header_row();
 3543:     my @noupdate;
 3544:     my ($updateCtr,$noupdateCtr) = (1,1);
 3545:     for ($i=0; $i<$env{'form.total'}; $i++) {
 3546: 	my $line;
 3547: 	my $user = $env{'form.ctr'.$i};
 3548: 	my ($uname,$udom)=split(/:/,$user);
 3549: 	my %newrecord;
 3550: 	my $updateflag = 0;
 3551: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 3552: 	my $usec=$classlist->{"$uname:$udom"}[5];
 3553: 	if (!&canmodify($usec)) {
 3554: 	    my $numcols=scalar(@partid)*4+2;
 3555: 	    push(@noupdate,
 3556: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
 3557: 		 &mt('Not allowed to modify student')."</span></td></tr>");
 3558: 	    next;
 3559: 	}
 3560:         my %aggregate = ();
 3561:         my $aggregateflag = 0;
 3562: 	$user=~s/:/_/; # colon doen't work in javascript for names
 3563: 	foreach (@partid) {
 3564: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 3565: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 3566: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 3567: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3568: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 3569: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 3570: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 3571: 	    my $score;
 3572: 	    if ($partial eq '') {
 3573: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3574: 	    } elsif ($partial > 0) {
 3575: 		$score = 'correct_by_override';
 3576: 	    } elsif ($partial == 0) {
 3577: 		$score = 'incorrect_by_override';
 3578: 	    }
 3579: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 3580: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 3581: 
 3582: 	    $newrecord{'resource.'.$_.'.regrader'}=
 3583: 		"$env{'user.name'}:$env{'user.domain'}";
 3584: 	    if ($dropMenu eq 'reset status' &&
 3585: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 3586: 		$newrecord{'resource.'.$_.'.tries'} = '';
 3587: 		$newrecord{'resource.'.$_.'.solved'} = '';
 3588: 		$newrecord{'resource.'.$_.'.award'} = '';
 3589: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 3590: 		$updateflag = 1;
 3591:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 3592:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 3593:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 3594:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 3595:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3596:                     $aggregateflag = 1;
 3597:                 }
 3598: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 3599: 		$updateflag = 1;
 3600: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 3601: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 3602: 		$rec_update++;
 3603: 	    }
 3604: 
 3605: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3606: 		'<td align="center">'.$awarded.
 3607: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 3608: 
 3609: 
 3610: 	    my $partid=$_;
 3611: 	    foreach my $stores (@parts) {
 3612: 		my ($part,$type) = &split_part_type($stores);
 3613: 		if ($part !~ m/^\Q$partid\E/) { next;}
 3614: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 3615: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 3616: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 3617: 		if ($awarded ne '' && $awarded ne $old_aw) {
 3618: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 3619: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3620: 		    $updateflag=1;
 3621: 		}
 3622: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3623: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 3624: 	    }
 3625: 	}
 3626: 	$line.="\n";
 3627: 
 3628: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3629: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3630: 
 3631: 	if ($updateflag) {
 3632: 	    $count++;
 3633: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 3634: 				    $udom,$uname);
 3635: 
 3636: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 3637: 					      $cnum,$udom,$uname)) {
 3638: 		# need to figure out if should be in queue.
 3639: 		my %record =  
 3640: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 3641: 					     $udom,$uname);
 3642: 		my $all_graded = 1;
 3643: 		my $none_graded = 1;
 3644: 		foreach my $part (@parts) {
 3645: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 3646: 			$all_graded = 0;
 3647: 		    } else {
 3648: 			$none_graded = 0;
 3649: 		    }
 3650: 		}
 3651: 
 3652: 		if ($all_graded || $none_graded) {
 3653: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 3654: 							   $symb,$cdom,$cnum,
 3655: 							   $udom,$uname);
 3656: 		}
 3657: 	    }
 3658: 
 3659: 	    $result.=&Apache::loncommon::start_data_table_row().
 3660: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 3661: 		&Apache::loncommon::end_data_table_row();
 3662: 	    $updateCtr++;
 3663: 	} else {
 3664: 	    push(@noupdate,
 3665: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 3666: 	    $noupdateCtr++;
 3667: 	}
 3668:         if ($aggregateflag) {
 3669:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3670: 				  $cdom,$cnum);
 3671:         }
 3672:     }
 3673:     if (@noupdate) {
 3674: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
 3675: 	my $numcols=scalar(@partid)*4+2;
 3676: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 3677: 	    '<td align="center" colspan="'.$numcols.'">'.
 3678: 	    &mt('No Changes Occurred For the Students Below').
 3679: 	    '</td>'.
 3680: 	    &Apache::loncommon::end_data_table_row();
 3681: 	foreach my $line (@noupdate) {
 3682: 	    $result.=
 3683: 		&Apache::loncommon::start_data_table_row().
 3684: 		$line.
 3685: 		&Apache::loncommon::end_data_table_row();
 3686: 	}
 3687:     }
 3688:     $result .= &Apache::loncommon::end_data_table();
 3689:     my $msg = '<p><b>'.
 3690: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 3691: 	    $rec_update,$count).'</b><br />'.
 3692: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 3693: 	'</b></p>';
 3694:     return $title.$msg.$result;
 3695: }
 3696: 
 3697: sub split_part_type {
 3698:     my ($partstr) = @_;
 3699:     my ($temp,@allparts)=split(/_/,$partstr);
 3700:     my $type=pop(@allparts);
 3701:     my $part=join('_',@allparts);
 3702:     return ($part,$type);
 3703: }
 3704: 
 3705: #------------- end of section for handling grading by section/class ---------
 3706: #
 3707: #----------------------------------------------------------------------------
 3708: 
 3709: 
 3710: #----------------------------------------------------------------------------
 3711: #
 3712: #-------------------------- Next few routines handles grading by csv upload
 3713: #
 3714: #--- Javascript to handle csv upload
 3715: sub csvupload_javascript_reverse_associate {
 3716:     my $error1=&mt('You need to specify the username or the student/employee ID');
 3717:     my $error2=&mt('You need to specify at least one grading field');
 3718:   return(<<ENDPICK);
 3719:   function verify(vf) {
 3720:     var foundsomething=0;
 3721:     var founduname=0;
 3722:     var foundID=0;
 3723:     for (i=0;i<=vf.nfields.value;i++) {
 3724:       tw=eval('vf.f'+i+'.selectedIndex');
 3725:       if (i==0 && tw!=0) { foundID=1; }
 3726:       if (i==1 && tw!=0) { founduname=1; }
 3727:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 3728:     }
 3729:     if (founduname==0 && foundID==0) {
 3730: 	alert('$error1');
 3731: 	return;
 3732:     }
 3733:     if (foundsomething==0) {
 3734: 	alert('$error2');
 3735: 	return;
 3736:     }
 3737:     vf.submit();
 3738:   }
 3739:   function flip(vf,tf) {
 3740:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3741:     var i;
 3742:     for (i=0;i<=vf.nfields.value;i++) {
 3743:       //can not pick the same destination field for both name and domain
 3744:       if (((i ==0)||(i ==1)) && 
 3745:           ((tf==0)||(tf==1)) && 
 3746:           (i!=tf) &&
 3747:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3748:         eval('vf.f'+i+'.selectedIndex=0;')
 3749:       }
 3750:     }
 3751:   }
 3752: ENDPICK
 3753: }
 3754: 
 3755: sub csvupload_javascript_forward_associate {
 3756:     my $error1=&mt('You need to specify the username or the student/employee ID');
 3757:     my $error2=&mt('You need to specify at least one grading field');
 3758:   return(<<ENDPICK);
 3759:   function verify(vf) {
 3760:     var foundsomething=0;
 3761:     var founduname=0;
 3762:     var foundID=0;
 3763:     for (i=0;i<=vf.nfields.value;i++) {
 3764:       tw=eval('vf.f'+i+'.selectedIndex');
 3765:       if (tw==1) { foundID=1; }
 3766:       if (tw==2) { founduname=1; }
 3767:       if (tw>3) { foundsomething=1; }
 3768:     }
 3769:     if (founduname==0 && foundID==0) {
 3770: 	alert('$error1');
 3771: 	return;
 3772:     }
 3773:     if (foundsomething==0) {
 3774: 	alert('$error2');
 3775: 	return;
 3776:     }
 3777:     vf.submit();
 3778:   }
 3779:   function flip(vf,tf) {
 3780:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3781:     var i;
 3782:     //can not pick the same destination field twice
 3783:     for (i=0;i<=vf.nfields.value;i++) {
 3784:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3785:         eval('vf.f'+i+'.selectedIndex=0;')
 3786:       }
 3787:     }
 3788:   }
 3789: ENDPICK
 3790: }
 3791: 
 3792: sub csvuploadmap_header {
 3793:     my ($request,$symb,$datatoken,$distotal)= @_;
 3794:     my $javascript;
 3795:     if ($env{'form.upfile_associate'} eq 'reverse') {
 3796: 	$javascript=&csvupload_javascript_reverse_associate();
 3797:     } else {
 3798: 	$javascript=&csvupload_javascript_forward_associate();
 3799:     }
 3800: 
 3801:     $symb = &Apache::lonenc::check_encrypt($symb);
 3802:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
 3803:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
 3804:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
 3805:     my $reverse=&mt("Reverse Association");
 3806:     $request->print(<<ENDPICK);
 3807: <br />
 3808: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 3809: <input type="hidden" name="associate"  value="" />
 3810: <input type="hidden" name="phase"      value="three" />
 3811: <input type="hidden" name="datatoken"  value="$datatoken" />
 3812: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 3813: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 3814: <input type="hidden" name="upfile_associate" 
 3815:                                        value="$env{'form.upfile_associate'}" />
 3816: <input type="hidden" name="symb"       value="$symb" />
 3817: <input type="hidden" name="command"    value="csvuploadoptions" />
 3818: <hr />
 3819: ENDPICK
 3820:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
 3821:     return '';
 3822: 
 3823: }
 3824: 
 3825: sub csvupload_fields {
 3826:     my ($symb,$errorref) = @_;
 3827:     my (@parts) = &getpartlist($symb,$errorref);
 3828:     if (ref($errorref)) {
 3829:         if ($$errorref) {
 3830:             return;
 3831:         }
 3832:     }
 3833: 
 3834:     my @fields=(['ID','Student/Employee ID'],
 3835: 		['username','Student Username'],
 3836: 		['domain','Student Domain']);
 3837:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3838:     foreach my $part (sort(@parts)) {
 3839: 	my @datum;
 3840: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3841: 	my $name=$part;
 3842: 	if  (!$display) { $display = $name; }
 3843: 	@datum=($name,$display);
 3844: 	if ($name=~/^stores_(.*)_awarded/) {
 3845: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 3846: 	}
 3847: 	push(@fields,\@datum);
 3848:     }
 3849:     return (@fields);
 3850: }
 3851: 
 3852: sub csvuploadmap_footer {
 3853:     my ($request,$i,$keyfields) =@_;
 3854:     $request->print(<<ENDPICK);
 3855: </table>
 3856: <input type="hidden" name="nfields" value="$i" />
 3857: <input type="hidden" name="keyfields" value="$keyfields" />
 3858: <input type="button" onclick="javascript:verify(this.form)" value="Assign Grades" /><br />
 3859: </form>
 3860: ENDPICK
 3861: }
 3862: 
 3863: sub checkforfile_js {
 3864:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 3865:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
 3866:     function checkUpload(formname) {
 3867: 	if (formname.upfile.value == "") {
 3868: 	    alert("$alertmsg");
 3869: 	    return false;
 3870: 	}
 3871: 	formname.submit();
 3872:     }
 3873: CSVFORMJS
 3874:     return $result;
 3875: }
 3876: 
 3877: sub upcsvScores_form {
 3878:     my ($request,$symb) = @_;
 3879:     if (!$symb) {return '';}
 3880:     my $result=&checkforfile_js();
 3881:     $result.=&Apache::loncommon::start_data_table().
 3882:              &Apache::loncommon::start_data_table_header_row().
 3883:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
 3884:              &Apache::loncommon::end_data_table_header_row().
 3885:              &Apache::loncommon::start_data_table_row().'<td>';
 3886:     my $upload=&mt("Upload Scores");
 3887:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 3888:     my $ignore=&mt('Ignore First Line');
 3889:     $symb = &Apache::lonenc::check_encrypt($symb);
 3890:     $result.=<<ENDUPFORM;
 3891: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3892: <input type="hidden" name="symb" value="$symb" />
 3893: <input type="hidden" name="command" value="csvuploadmap" />
 3894: $upfile_select
 3895: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 3896: </form>
 3897: ENDUPFORM
 3898:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 3899:                            &mt("How do I create a CSV file from a spreadsheet")).
 3900:              '</td>'.
 3901:             &Apache::loncommon::end_data_table_row().
 3902:             &Apache::loncommon::end_data_table();
 3903:     return $result;
 3904: }
 3905: 
 3906: 
 3907: sub csvuploadmap {
 3908:     my ($request,$symb)= @_;
 3909:     if (!$symb) {return '';}
 3910: 
 3911:     my $datatoken;
 3912:     if (!$env{'form.datatoken'}) {
 3913: 	$datatoken=&Apache::loncommon::upfile_store($request);
 3914:     } else {
 3915: 	$datatoken=$env{'form.datatoken'};
 3916: 	&Apache::loncommon::load_tmp_file($request);
 3917:     }
 3918:     my @records=&Apache::loncommon::upfile_record_sep();
 3919:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 3920:     my ($i,$keyfields);
 3921:     if (@records) {
 3922:         my $fieldserror;
 3923: 	my @fields=&csvupload_fields($symb,\$fieldserror);
 3924:         if ($fieldserror) {
 3925:             $request->print(&navmap_errormsg());
 3926:             return;
 3927:         }
 3928: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 3929: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 3930: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 3931: 							  \@fields);
 3932: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 3933: 	    chop($keyfields);
 3934: 	} else {
 3935: 	    unshift(@fields,['none','']);
 3936: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 3937: 							    \@fields);
 3938:             foreach my $rec (@records) {
 3939:                 my %temp = &Apache::loncommon::record_sep($rec);
 3940:                 if (%temp) {
 3941:                     $keyfields=join(',',sort(keys(%temp)));
 3942:                     last;
 3943:                 }
 3944:             }
 3945: 	}
 3946:     }
 3947:     &csvuploadmap_footer($request,$i,$keyfields);
 3948: 
 3949:     return '';
 3950: }
 3951: 
 3952: sub csvuploadoptions {
 3953:     my ($request,$symb)= @_;
 3954:     my $overwrite=&mt('Overwrite any existing score');
 3955:     $request->print(<<ENDPICK);
 3956: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3957: <input type="hidden" name="command"    value="csvuploadassign" />
 3958: <p>
 3959: <label>
 3960:    <input type="checkbox" name="overwite_scores" checked="checked" />
 3961:    $overwrite
 3962: </label>
 3963: </p>
 3964: ENDPICK
 3965:     my %fields=&get_fields();
 3966:     if (!defined($fields{'domain'})) {
 3967: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 3968: 	$request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
 3969:     }
 3970:     foreach my $key (sort(keys(%env))) {
 3971: 	if ($key !~ /^form\.(.*)$/) { next; }
 3972: 	my $cleankey=$1;
 3973: 	if ($cleankey eq 'command') { next; }
 3974: 	$request->print('<input type="hidden" name="'.$cleankey.
 3975: 			'"  value="'.$env{$key}.'" />'."\n");
 3976:     }
 3977:     # FIXME do a check for any duplicated user ids...
 3978:     # FIXME do a check for any invalid user ids?...
 3979:     $request->print('<input type="submit" value="Assign Grades" /><br />
 3980: <hr /></form>'."\n");
 3981:     return '';
 3982: }
 3983: 
 3984: sub get_fields {
 3985:     my %fields;
 3986:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 3987:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 3988: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 3989: 	    if ($env{'form.f'.$i} ne 'none') {
 3990: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 3991: 	    }
 3992: 	} else {
 3993: 	    if ($env{'form.f'.$i} ne 'none') {
 3994: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 3995: 	    }
 3996: 	}
 3997:     }
 3998:     return %fields;
 3999: }
 4000: 
 4001: sub csvuploadassign {
 4002:     my ($request,$symb)= @_;
 4003:     if (!$symb) {return '';}
 4004:     my $error_msg = '';
 4005:     &Apache::loncommon::load_tmp_file($request);
 4006:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 4007:     my %fields=&get_fields();
 4008:     my $courseid=$env{'request.course.id'};
 4009:     my ($classlist) = &getclasslist('all',0);
 4010:     my @notallowed;
 4011:     my @skipped;
 4012:     my $countdone=0;
 4013:     foreach my $grade (@gradedata) {
 4014: 	my %entries=&Apache::loncommon::record_sep($grade);
 4015: 	my $domain;
 4016: 	if ($entries{$fields{'domain'}}) {
 4017: 	    $domain=$entries{$fields{'domain'}};
 4018: 	} else {
 4019: 	    $domain=$env{'form.default_domain'};
 4020: 	}
 4021: 	$domain=~s/\s//g;
 4022: 	my $username=$entries{$fields{'username'}};
 4023: 	$username=~s/\s//g;
 4024: 	if (!$username) {
 4025: 	    my $id=$entries{$fields{'ID'}};
 4026: 	    $id=~s/\s//g;
 4027: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 4028: 	    $username=$ids{$id};
 4029: 	}
 4030: 	if (!exists($$classlist{"$username:$domain"})) {
 4031: 	    my $id=$entries{$fields{'ID'}};
 4032: 	    $id=~s/\s//g;
 4033: 	    if ($id) {
 4034: 		push(@skipped,"$id:$domain");
 4035: 	    } else {
 4036: 		push(@skipped,"$username:$domain");
 4037: 	    }
 4038: 	    next;
 4039: 	}
 4040: 	my $usec=$classlist->{"$username:$domain"}[5];
 4041: 	if (!&canmodify($usec)) {
 4042: 	    push(@notallowed,"$username:$domain");
 4043: 	    next;
 4044: 	}
 4045: 	my %points;
 4046: 	my %grades;
 4047: 	foreach my $dest (keys(%fields)) {
 4048: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 4049: 		$dest eq 'domain') { next; }
 4050: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 4051: 	    if ($dest=~/stores_(.*)_points/) {
 4052: 		my $part=$1;
 4053: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 4054: 					      $symb,$domain,$username);
 4055:                 if ($wgt) {
 4056:                     $entries{$fields{$dest}}=~s/\s//g;
 4057:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 4058:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 4059:                                           : 'correct_by_override';
 4060:                     if ($pcr>1) {
 4061:                        push(@skipped,&mt("[_1]: point value larger than weight","$username:$domain"));
 4062:                     }
 4063:                     $grades{"resource.$part.awarded"}=$pcr;
 4064:                     $grades{"resource.$part.solved"}=$award;
 4065:                     $points{$part}=1;
 4066:                 } else {
 4067:                     $error_msg = "<br />" .
 4068:                         &mt("Some point values were assigned"
 4069:                             ." for problems with a weight "
 4070:                             ."of zero. These values were "
 4071:                             ."ignored.");
 4072:                 }
 4073: 	    } else {
 4074: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 4075: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 4076: 		my $store_key=$dest;
 4077: 		$store_key=~s/^stores/resource/;
 4078: 		$store_key=~s/_/\./g;
 4079: 		$grades{$store_key}=$entries{$fields{$dest}};
 4080: 	    }
 4081: 	}
 4082: 	if (! %grades) { 
 4083:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 4084:         } else {
 4085: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 4086: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 4087: 					   $env{'request.course.id'},
 4088: 					   $domain,$username);
 4089: 	   if ($result eq 'ok') {
 4090: # Successfully stored
 4091: 	      $request->print('.');
 4092: # Remove from grading queue
 4093:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
 4094:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
 4095:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
 4096:                                              $domain,$username);
 4097:               $countdone++;
 4098:            } else {
 4099: 	      $request->print("<p><span class=\"LC_error\">".
 4100:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 4101:                                   "$username:$domain",$result)."</span></p>");
 4102: 	   }
 4103: 	   $request->rflush();
 4104:         }
 4105:     }
 4106:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
 4107:     if (@skipped) {
 4108: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
 4109:         $request->print(join(', ',@skipped));
 4110:     }
 4111:     if (@notallowed) {
 4112: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
 4113: 	$request->print(join(', ',@notallowed));
 4114:     }
 4115:     $request->print("<br />\n");
 4116:     return $error_msg;
 4117: }
 4118: #------------- end of section for handling csv file upload ---------
 4119: #
 4120: #-------------------------------------------------------------------
 4121: #
 4122: #-------------- Next few routines handle grading by page/sequence
 4123: #
 4124: #--- Select a page/sequence and a student to grade
 4125: sub pickStudentPage {
 4126:     my ($request,$symb) = @_;
 4127: 
 4128:     my $alertmsg = &mt('Please select the student you wish to grade.');
 4129:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
 4130: 
 4131: function checkPickOne(formname) {
 4132:     if (radioSelection(formname.student) == null) {
 4133: 	alert("$alertmsg");
 4134: 	return;
 4135:     }
 4136:     ptr = pullDownSelection(formname.selectpage);
 4137:     formname.page.value = formname["page"+ptr].value;
 4138:     formname.title.value = formname["title"+ptr].value;
 4139:     formname.submit();
 4140: }
 4141: 
 4142: LISTJAVASCRIPT
 4143:     &commonJSfunctions($request);
 4144: 
 4145:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4146:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4147:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4148: 
 4149:     my $result='<h3><span class="LC_info">&nbsp;'.
 4150: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 4151: 
 4152:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 4153:     my $map_error;
 4154:     my ($titles,$symbx) = &getSymbMap($map_error);
 4155:     if ($map_error) {
 4156:         $request->print(&navmap_errormsg());
 4157:         return; 
 4158:     }
 4159:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 4160: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 4161: #    my $type=($curpage =~ /\.(page|sequence)/);
 4162:     my $select = '<select name="selectpage">'."\n";
 4163:     my $ctr=0;
 4164:     foreach (@$titles) {
 4165: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4166: 	$select.='<option value="'.$ctr.'" '.
 4167: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4168: 	    '>'.$showtitle.'</option>'."\n";
 4169: 	$ctr++;
 4170:     }
 4171:     $select.= '</select>';
 4172:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
 4173: 
 4174:     $ctr=0;
 4175:     foreach (@$titles) {
 4176: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4177: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 4178: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 4179: 	$ctr++;
 4180:     }
 4181:     $result.='<input type="hidden" name="page" />'."\n".
 4182: 	'<input type="hidden" name="title" />'."\n";
 4183: 
 4184:     my $options =
 4185: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
 4186: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
 4187:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
 4188: 
 4189:     $options =
 4190: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
 4191: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
 4192: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
 4193:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
 4194:     
 4195:     $result.=&build_section_inputs();
 4196:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4197:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 4198: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 4199: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."<br />\n";
 4200: 
 4201:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
 4202: 
 4203:     $result.='&nbsp;<input type="button" '.
 4204:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 4205: 
 4206:     $request->print($result);
 4207: 
 4208:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 4209: 	&Apache::loncommon::start_data_table().
 4210: 	&Apache::loncommon::start_data_table_header_row().
 4211: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4212: 	'<th>'.&nameUserString('header').'</th>'.
 4213: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4214: 	'<th>'.&nameUserString('header').'</th>'.
 4215: 	&Apache::loncommon::end_data_table_header_row();
 4216:  
 4217:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 4218:     my $ptr = 1;
 4219:     foreach my $student (sort 
 4220: 			 {
 4221: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4222: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4223: 			     }
 4224: 			     return $a cmp $b;
 4225: 			 } (keys(%$fullname))) {
 4226: 	my ($uname,$udom) = split(/:/,$student);
 4227: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 4228:                                   : '</td>');
 4229: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 4230: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 4231: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 4232: 	$studentTable.=
 4233: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 4234:                          : '');
 4235: 	$ptr++;
 4236:     }
 4237:     if ($ptr%2 == 0) {
 4238: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 4239: 	    &Apache::loncommon::end_data_table_row();
 4240:     }
 4241:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 4242:     $studentTable.='<input type="button" '.
 4243:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 4244: 
 4245:     $request->print($studentTable);
 4246: 
 4247:     return '';
 4248: }
 4249: 
 4250: sub getSymbMap {
 4251:     my ($map_error) = @_;
 4252:     my $navmap = Apache::lonnavmaps::navmap->new();
 4253:     unless (ref($navmap)) {
 4254:         if (ref($map_error)) {
 4255:             $$map_error = 'navmap';
 4256:         }
 4257:         return;
 4258:     }
 4259:     my %symbx = ();
 4260:     my @titles = ();
 4261:     my $minder = 0;
 4262: 
 4263:     # Gather every sequence that has problems.
 4264:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 4265: 					       1,0,1);
 4266:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 4267: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 4268: 	    my $title = $minder.'.'.
 4269: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 4270: 	    push(@titles, $title); # minder in case two titles are identical
 4271: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 4272: 	    $minder++;
 4273: 	}
 4274:     }
 4275:     return \@titles,\%symbx;
 4276: }
 4277: 
 4278: #
 4279: #--- Displays a page/sequence w/wo problems, w/wo submissions
 4280: sub displayPage {
 4281:     my ($request,$symb) = @_;
 4282:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4283:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4284:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4285:     my $pageTitle = $env{'form.page'};
 4286:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4287:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4288:     my $usec=$classlist->{$env{'form.student'}}[5];
 4289: 
 4290:     #need to make sure we have the correct data for later EXT calls, 
 4291:     #thus invalidate the cache
 4292:     &Apache::lonnet::devalidatecourseresdata(
 4293:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 4294:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 4295:     &Apache::lonnet::clear_EXT_cache_status();
 4296: 
 4297:     if (!&canview($usec)) {
 4298: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
 4299: 	return;
 4300:     }
 4301:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4302:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 4303: 	'</h3>'."\n";
 4304:     $env{'form.CODE'} = uc($env{'form.CODE'});
 4305:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 4306: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 4307:     } else {
 4308: 	delete($env{'form.CODE'});
 4309:     }
 4310:     &sub_page_js($request);
 4311:     $request->print($result);
 4312: 
 4313:     my $navmap = Apache::lonnavmaps::navmap->new();
 4314:     unless (ref($navmap)) {
 4315:         $request->print(&navmap_errormsg());
 4316:         return;
 4317:     }
 4318:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 4319:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4320:     if (!$map) {
 4321: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 4322: 	return; 
 4323:     }
 4324:     my $iterator = $navmap->getIterator($map->map_start(),
 4325: 					$map->map_finish());
 4326: 
 4327:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 4328: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 4329: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 4330: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 4331: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 4332: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 4333: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4334: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
 4335: 
 4336:     if (defined($env{'form.CODE'})) {
 4337: 	$studentTable.=
 4338: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 4339:     }
 4340:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 4341: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 4342: 
 4343:     $studentTable.='&nbsp;<span class="LC_info">'.
 4344:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
 4345:         '</span>'."\n".
 4346: 	&Apache::loncommon::start_data_table().
 4347: 	&Apache::loncommon::start_data_table_header_row().
 4348: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
 4349: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 4350: 	&Apache::loncommon::end_data_table_header_row();
 4351: 
 4352:     &Apache::lonxml::clear_problem_counter();
 4353:     my ($depth,$question,$prob) = (1,1,1);
 4354:     $iterator->next(); # skip the first BEGIN_MAP
 4355:     my $curRes = $iterator->next(); # for "current resource"
 4356:     while ($depth > 0) {
 4357:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4358:         if($curRes == $iterator->END_MAP) { $depth--; }
 4359: 
 4360:         if (ref($curRes) && $curRes->is_problem()) {
 4361: 	    my $parts = $curRes->parts();
 4362:             my $title = $curRes->compTitle();
 4363: 	    my $symbx = $curRes->symb();
 4364: 	    $studentTable.=
 4365: 		&Apache::loncommon::start_data_table_row().
 4366: 		'<td align="center" valign="top" >'.$prob.
 4367: 		(scalar(@{$parts}) == 1 ? '' 
 4368: 		                        : '<br />('.&mt('[_1]&nbsp;parts)',
 4369: 							scalar(@{$parts}))
 4370: 		 ).
 4371: 		 '</td>';
 4372: 	    $studentTable.='<td valign="top">';
 4373: 	    my %form = ('CODE' => $env{'form.CODE'},);
 4374: 	    if ($env{'form.vProb'} eq 'yes' ) {
 4375: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 4376: 					     undef,'both',\%form);
 4377: 	    } else {
 4378: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 4379: 		$companswer =~ s|<form(.*?)>||g;
 4380: 		$companswer =~ s|</form>||g;
 4381: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 4382: #		    $companswer =~ s/$1/ /ms;
 4383: #		    $request->print('match='.$1."<br />\n");
 4384: #		}
 4385: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 4386: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 4387: 	    }
 4388: 
 4389: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 4390: 
 4391: 	    if ($env{'form.lastSub'} eq 'datesub') {
 4392: 		if ($record{'version'} eq '') {
 4393: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
 4394: 		} else {
 4395: 		    my %responseType = ();
 4396: 		    foreach my $partid (@{$parts}) {
 4397: 			my @responseIds =$curRes->responseIds($partid);
 4398: 			my @responseType =$curRes->responseType($partid);
 4399: 			my %responseIds;
 4400: 			for (my $i=0;$i<=$#responseIds;$i++) {
 4401: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 4402: 			}
 4403: 			$responseType{$partid} = \%responseIds;
 4404: 		    }
 4405: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 4406: 
 4407: 		}
 4408: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 4409: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 4410: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 4411: 									$env{'request.course.id'},
 4412: 									'','.submission');
 4413:  
 4414: 	    }
 4415: 	    if (&canmodify($usec)) {
 4416:             $studentTable.=&gradeBox_start();
 4417: 		foreach my $partid (@{$parts}) {
 4418: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 4419: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 4420: 		    $question++;
 4421: 		}
 4422:             $studentTable.=&gradeBox_end();
 4423: 		$prob++;
 4424: 	    }
 4425: 	    $studentTable.='</td></tr>';
 4426: 
 4427: 	}
 4428:         $curRes = $iterator->next();
 4429:     }
 4430: 
 4431:     $studentTable.=
 4432:         '</table>'."\n".
 4433:         '<input type="button" value="'.&mt('Save').'" '.
 4434:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 4435:         '</form>'."\n";
 4436:     $request->print($studentTable);
 4437: 
 4438:     return '';
 4439: }
 4440: 
 4441: sub displaySubByDates {
 4442:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 4443:     my $isCODE=0;
 4444:     my $isTask = ($symb =~/\.task$/);
 4445:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 4446:     my $studentTable=&Apache::loncommon::start_data_table().
 4447: 	&Apache::loncommon::start_data_table_header_row().
 4448: 	'<th>'.&mt('Date/Time').'</th>'.
 4449: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 4450: 	'<th>'.&mt('Submission').'</th>'.
 4451: 	'<th>'.&mt('Status').'</th>'.
 4452: 	&Apache::loncommon::end_data_table_header_row();
 4453:     my ($version);
 4454:     my %mark;
 4455:     my %orders;
 4456:     $mark{'correct_by_student'} = $checkIcon;
 4457:     if (!exists($$record{'1:timestamp'})) {
 4458: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 4459:     }
 4460: 
 4461:     my $interaction;
 4462:     my $no_increment = 1;
 4463:     for ($version=1;$version<=$$record{'version'};$version++) {
 4464: 	my $timestamp = 
 4465: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 4466: 	if (exists($$record{$version.':resource.0.version'})) {
 4467: 	    $interaction = $$record{$version.':resource.0.version'};
 4468: 	}
 4469: 
 4470: 	my $where = ($isTask ? "$version:resource.$interaction"
 4471: 		             : "$version:resource");
 4472: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 4473: 	    '<td>'.$timestamp.'</td>';
 4474: 	if ($isCODE) {
 4475: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 4476: 	}
 4477: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 4478: 	my @displaySub = ();
 4479: 	foreach my $partid (@{$parts}) {
 4480:             my $hidden;
 4481:             if (($$record{$version.':resource.'.$partid.'.type'} eq 'anonsurvey') ||
 4482:                 ($$record{$version.':resource.'.$partid.'.type'} eq 'anonsurveycred')) {
 4483:                 $hidden = 1;
 4484:             }
 4485: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
 4486: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 4487: 	    
 4488: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 4489: 	    my $display_part=&get_display_part($partid,$symb);
 4490: 	    foreach my $matchKey (@matchKey) {
 4491: 		if (exists($$record{$version.':'.$matchKey}) &&
 4492: 		    $$record{$version.':'.$matchKey} ne '') {
 4493:                     
 4494: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 4495: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 4496:                     $displaySub[0].='<span class="LC_nobreak"';
 4497:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
 4498:                                    .' <span class="LC_internal_info">'
 4499:                                    .'('.&mt('Response ID: [_1]',$responseId).')'
 4500:                                    .'</span>'
 4501:                                    .' <b>';
 4502:                     if ($hidden) {
 4503:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
 4504:                     } else {
 4505: 		        if ($$record{"$where.$partid.tries"} eq '') {
 4506: 			    $displaySub[0].=&mt('Trial not counted');
 4507: 		        } else {
 4508: 			    $displaySub[0].=&mt('Trial: [_1]',
 4509: 					    $$record{"$where.$partid.tries"});
 4510: 		        }
 4511: 		        my $responseType=($isTask ? 'Task'
 4512:                                               : $responseType->{$partid}->{$responseId});
 4513: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
 4514: 		        if (!exists($orders{$partid}->{$responseId})) {
 4515: 			    $orders{$partid}->{$responseId}=
 4516: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
 4517:                                            $no_increment);
 4518: 		        }
 4519: 		        $displaySub[0].='</b></span>'; # /nobreak
 4520: 		        $displaySub[0].='&nbsp; '.
 4521: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
 4522:                     }
 4523: 		}
 4524: 	    }
 4525: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 4526: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 4527: 				    $$record{"$where.$partid.checkedin"},
 4528: 				    $$record{"$where.$partid.checkedin.slot"}).
 4529: 					'<br />';
 4530: 	    }
 4531: 	    if (exists $$record{"$where.$partid.award"}) {
 4532: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 4533: 		    lc($$record{"$where.$partid.award"}).' '.
 4534: 		    $mark{$$record{"$where.$partid.solved"}}.
 4535: 		    '<br />';
 4536: 	    }
 4537: 	    if (exists $$record{"$where.$partid.regrader"}) {
 4538: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 4539: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4540: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 4541: 		$displaySub[2].=
 4542: 		    $$record{"$version:resource.$partid.regrader"}.
 4543: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4544: 	    }
 4545: 	}
 4546: 	# needed because old essay regrader has not parts info
 4547: 	if (exists $$record{"$version:resource.regrader"}) {
 4548: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 4549: 	}
 4550: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 4551: 	if ($displaySub[2]) {
 4552: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 4553: 	}
 4554: 	$studentTable.='&nbsp;</td>'.
 4555: 	    &Apache::loncommon::end_data_table_row();
 4556:     }
 4557:     $studentTable.=&Apache::loncommon::end_data_table();
 4558:     return $studentTable;
 4559: }
 4560: 
 4561: sub updateGradeByPage {
 4562:     my ($request,$symb) = @_;
 4563: 
 4564:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4565:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4566:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4567:     my $pageTitle = $env{'form.page'};
 4568:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4569:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4570:     my $usec=$classlist->{$env{'form.student'}}[5];
 4571:     if (!&canmodify($usec)) {
 4572: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 4573: 	return;
 4574:     }
 4575:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4576:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 4577: 	'</h3>'."\n";
 4578: 
 4579:     $request->print($result);
 4580: 
 4581: 
 4582:     my $navmap = Apache::lonnavmaps::navmap->new();
 4583:     unless (ref($navmap)) {
 4584:         $request->print(&navmap_errormsg());
 4585:         return;
 4586:     }
 4587:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 4588:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4589:     if (!$map) {
 4590: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 4591: 	return; 
 4592:     }
 4593:     my $iterator = $navmap->getIterator($map->map_start(),
 4594: 					$map->map_finish());
 4595: 
 4596:     my $studentTable=
 4597: 	&Apache::loncommon::start_data_table().
 4598: 	&Apache::loncommon::start_data_table_header_row().
 4599: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 4600: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 4601: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 4602: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 4603: 	&Apache::loncommon::end_data_table_header_row();
 4604: 
 4605:     $iterator->next(); # skip the first BEGIN_MAP
 4606:     my $curRes = $iterator->next(); # for "current resource"
 4607:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
 4608:     while ($depth > 0) {
 4609:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4610:         if($curRes == $iterator->END_MAP) { $depth--; }
 4611: 
 4612:         if (ref($curRes) && $curRes->is_problem()) {
 4613: 	    my $parts = $curRes->parts();
 4614:             my $title = $curRes->compTitle();
 4615: 	    my $symbx = $curRes->symb();
 4616: 	    $studentTable.=
 4617: 		&Apache::loncommon::start_data_table_row().
 4618: 		'<td align="center" valign="top" >'.$prob.
 4619: 		(scalar(@{$parts}) == 1 ? '' 
 4620:                                         : '<br />('.&mt('[quant,_1,&nbsp;part]',scalar(@{$parts}))
 4621: 		.')').'</td>';
 4622: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 4623: 
 4624: 	    my %newrecord=();
 4625: 	    my @displayPts=();
 4626:             my %aggregate = ();
 4627:             my $aggregateflag = 0;
 4628: 	    foreach my $partid (@{$parts}) {
 4629: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 4630: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 4631: 
 4632: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 4633: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 4634: 		my $partial = $newpts/$wgt;
 4635: 		my $score;
 4636: 		if ($partial > 0) {
 4637: 		    $score = 'correct_by_override';
 4638: 		} elsif ($newpts ne '') { #empty is taken as 0
 4639: 		    $score = 'incorrect_by_override';
 4640: 		}
 4641: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 4642: 		if ($dropMenu eq 'excused') {
 4643: 		    $partial = '';
 4644: 		    $score = 'excused';
 4645: 		} elsif ($dropMenu eq 'reset status'
 4646: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 4647: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 4648: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 4649: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 4650: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 4651: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 4652: 		    $changeflag++;
 4653: 		    $newpts = '';
 4654:                     
 4655:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 4656:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 4657:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 4658:                     if ($aggtries > 0) {
 4659:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4660:                         $aggregateflag = 1;
 4661:                     }
 4662: 		}
 4663: 		my $display_part=&get_display_part($partid,$curRes->symb());
 4664: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 4665: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4666: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 4667: 		    '&nbsp;<br />';
 4668: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4669: 		     (($score eq 'excused') ? 'excused' : $newpts).
 4670: 		    '&nbsp;<br />';
 4671: 		$question++;
 4672: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 4673: 
 4674: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 4675: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 4676: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 4677: 		    if (scalar(keys(%newrecord)) > 0);
 4678: 
 4679: 		$changeflag++;
 4680: 	    }
 4681: 	    if (scalar(keys(%newrecord)) > 0) {
 4682: 		my %record = 
 4683: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 4684: 					     $udom,$uname);
 4685: 
 4686: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 4687: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 4688: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 4689: 		    $newrecord{'resource.CODE'} = '';
 4690: 		}
 4691: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 4692: 					$udom,$uname);
 4693: 		%record = &Apache::lonnet::restore($symbx,
 4694: 						   $env{'request.course.id'},
 4695: 						   $udom,$uname);
 4696: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 4697: 					     $cdom,$cnum,$udom,$uname);
 4698: 	    }
 4699: 	    
 4700:             if ($aggregateflag) {
 4701:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4702:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 4703:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 4704:             }
 4705: 
 4706: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 4707: 		'<td valign="top">'.$displayPts[1].'</td>'.
 4708: 		&Apache::loncommon::end_data_table_row();
 4709: 
 4710: 	    $prob++;
 4711: 	}
 4712:         $curRes = $iterator->next();
 4713:     }
 4714: 
 4715:     $studentTable.=&Apache::loncommon::end_data_table();
 4716:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 4717: 		  &mt('The scores were changed for [quant,_1,problem].',
 4718: 		  $changeflag));
 4719:     $request->print($grademsg.$studentTable);
 4720: 
 4721:     return '';
 4722: }
 4723: 
 4724: #-------- end of section for handling grading by page/sequence ---------
 4725: #
 4726: #-------------------------------------------------------------------
 4727: 
 4728: #-------------------- Bubblesheet (Scantron) Grading -------------------
 4729: #
 4730: #------ start of section for handling grading by page/sequence ---------
 4731: 
 4732: =pod
 4733: 
 4734: =head1 Bubble sheet grading routines
 4735: 
 4736:   For this documentation:
 4737: 
 4738:    'scanline' refers to the full line of characters
 4739:    from the file that we are parsing that represents one entire sheet
 4740: 
 4741:    'bubble line' refers to the data
 4742:    representing the line of bubbles that are on the physical bubble sheet
 4743: 
 4744: 
 4745: The overall process is that a scanned in bubble sheet data is uploaded
 4746: into a course. When a user wants to grade, they select a
 4747: sequence/folder of resources, a file of bubble sheet info, and pick
 4748: one of the predefined configurations for what each scanline looks
 4749: like.
 4750: 
 4751: Next each scanline is checked for any errors of either 'missing
 4752: bubbles' (it's an error because it may have been mis-scanned
 4753: because too light bubbling), 'double bubble' (each bubble line should
 4754: have no more that one letter picked), invalid or duplicated CODE,
 4755: invalid student/employee ID
 4756: 
 4757: If the CODE option is used that determines the randomization of the
 4758: homework problems, either way the student/employee ID is looked up into a
 4759: username:domain.
 4760: 
 4761: During the validation phase the instructor can choose to skip scanlines. 
 4762: 
 4763: After the validation phase, there are now 3 bubble sheet files
 4764: 
 4765:   scantron_original_filename (unmodified original file)
 4766:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 4767:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 4768: 
 4769: Also there is a separate hash nohist_scantrondata that contains extra
 4770: correction information that isn't representable in the bubble sheet
 4771: file (see &scantron_getfile() for more information)
 4772: 
 4773: After all scanlines are either valid, marked as valid or skipped, then
 4774: foreach line foreach problem in the picked sequence, an ssi request is
 4775: made that simulates a user submitting their selected letter(s) against
 4776: the homework problem.
 4777: 
 4778: =over 4
 4779: 
 4780: 
 4781: 
 4782: =item defaultFormData
 4783: 
 4784:   Returns html hidden inputs used to hold context/default values.
 4785: 
 4786:  Arguments:
 4787:   $symb - $symb of the current resource 
 4788: 
 4789: =cut
 4790: 
 4791: sub defaultFormData {
 4792:     my ($symb)=@_;
 4793:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />';
 4794: }
 4795: 
 4796: 
 4797: =pod 
 4798: 
 4799: =item getSequenceDropDown
 4800: 
 4801:    Return html dropdown of possible sequences to grade
 4802:  
 4803:  Arguments:
 4804:    $symb - $symb of the current resource
 4805:    $map_error - ref to scalar which will container error if
 4806:                 $navmap object is unavailable in &getSymbMap().
 4807: 
 4808: =cut
 4809: 
 4810: sub getSequenceDropDown {
 4811:     my ($symb,$map_error)=@_;
 4812:     my $result='<select name="selectpage">'."\n";
 4813:     my ($titles,$symbx) = &getSymbMap($map_error);
 4814:     if (ref($map_error)) {
 4815:         return if ($$map_error);
 4816:     }
 4817:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 4818:     my $ctr=0;
 4819:     foreach (@$titles) {
 4820: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4821: 	$result.='<option value="'.$$symbx{$_}.'" '.
 4822: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4823: 	    '>'.$showtitle.'</option>'."\n";
 4824: 	$ctr++;
 4825:     }
 4826:     $result.= '</select>';
 4827:     return $result;
 4828: }
 4829: 
 4830: my %bubble_lines_per_response;     # no. bubble lines for each response.
 4831:                                    # key is zero-based index - 0, 1, 2 ...
 4832: 
 4833: my %first_bubble_line;             # First bubble line no. for each bubble.
 4834: 
 4835: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 4836:                                    # matchresponse or rankresponse, where 
 4837:                                    # an individual response can have multiple 
 4838:                                    # lines
 4839: 
 4840: my %responsetype_per_response;     # responsetype for each response
 4841: 
 4842: # Save and restore the bubble lines array to the form env.
 4843: 
 4844: 
 4845: sub save_bubble_lines {
 4846:     foreach my $line (keys(%bubble_lines_per_response)) {
 4847: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 4848: 	$env{"form.scantron.first_bubble_line.$line"} =
 4849: 	    $first_bubble_line{$line};
 4850:         $env{"form.scantron.sub_bubblelines.$line"} = 
 4851:             $subdivided_bubble_lines{$line};
 4852:         $env{"form.scantron.responsetype.$line"} =
 4853:             $responsetype_per_response{$line};
 4854:     }
 4855: }
 4856: 
 4857: 
 4858: sub restore_bubble_lines {
 4859:     my $line = 0;
 4860:     %bubble_lines_per_response = ();
 4861:     while ($env{"form.scantron.bubblelines.$line"}) {
 4862: 	my $value = $env{"form.scantron.bubblelines.$line"};
 4863: 	$bubble_lines_per_response{$line} = $value;
 4864: 	$first_bubble_line{$line}  =
 4865: 	    $env{"form.scantron.first_bubble_line.$line"};
 4866:         $subdivided_bubble_lines{$line} =
 4867:             $env{"form.scantron.sub_bubblelines.$line"};
 4868:         $responsetype_per_response{$line} =
 4869:             $env{"form.scantron.responsetype.$line"};
 4870: 	$line++;
 4871:     }
 4872: }
 4873: 
 4874: #  Given the parsed scanline, get the response for 
 4875: #  'answer' number n:
 4876: 
 4877: sub get_response_bubbles {
 4878:     my ($parsed_line, $response)  = @_;
 4879: 
 4880:     my $bubble_line = $first_bubble_line{$response-1} +1;
 4881:     my $bubble_lines= $bubble_lines_per_response{$response-1};
 4882:     
 4883:     my $selected = "";
 4884: 
 4885:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
 4886: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
 4887: 	$bubble_line++;
 4888:     }
 4889:     return $selected;
 4890: }
 4891: 
 4892: =pod 
 4893: 
 4894: =item scantron_filenames
 4895: 
 4896:    Returns a list of the scantron files in the current course 
 4897: 
 4898: =cut
 4899: 
 4900: sub scantron_filenames {
 4901:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4902:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4903:     my $getpropath = 1;
 4904:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
 4905:                                        $getpropath);
 4906:     my @possiblenames;
 4907:     foreach my $filename (sort(@files)) {
 4908: 	($filename)=split(/&/,$filename);
 4909: 	if ($filename!~/^scantron_orig_/) { next ; }
 4910: 	$filename=~s/^scantron_orig_//;
 4911: 	push(@possiblenames,$filename);
 4912:     }
 4913:     return @possiblenames;
 4914: }
 4915: 
 4916: =pod 
 4917: 
 4918: =item scantron_uploads
 4919: 
 4920:    Returns  html drop-down list of scantron files in current course.
 4921: 
 4922:  Arguments:
 4923:    $file2grade - filename to set as selected in the dropdown
 4924: 
 4925: =cut
 4926: 
 4927: sub scantron_uploads {
 4928:     my ($file2grade) = @_;
 4929:     my $result=	'<select name="scantron_selectfile">';
 4930:     $result.="<option></option>";
 4931:     foreach my $filename (sort(&scantron_filenames())) {
 4932: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 4933:     }
 4934:     $result.="</select>";
 4935:     return $result;
 4936: }
 4937: 
 4938: =pod 
 4939: 
 4940: =item scantron_scantab
 4941: 
 4942:   Returns html drop down of the scantron formats in the scantronformat.tab
 4943:   file.
 4944: 
 4945: =cut
 4946: 
 4947: sub scantron_scantab {
 4948:     my $result='<select name="scantron_format">'."\n";
 4949:     $result.='<option></option>'."\n";
 4950:     my @lines = &get_scantronformat_file();
 4951:     if (@lines > 0) {
 4952:         foreach my $line (@lines) {
 4953:             next if (($line =~ /^\#/) || ($line eq ''));
 4954: 	    my ($name,$descrip)=split(/:/,$line);
 4955: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 4956:         }
 4957:     }
 4958:     $result.='</select>'."\n";
 4959:     return $result;
 4960: }
 4961: 
 4962: =pod
 4963: 
 4964: =item get_scantronformat_file
 4965: 
 4966:   Returns an array containing lines from the scantron format file for
 4967:   the domain of the course.
 4968: 
 4969:   If a url for a custom.tab file is listed in domain's configuration.db, 
 4970:   lines are from this file.
 4971: 
 4972:   Otherwise, if a default.tab has been published in RES space by the 
 4973:   domainconfig user, lines are from this file.
 4974: 
 4975:   Otherwise, fall back to getting lines from the legacy file on the
 4976:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
 4977: 
 4978: =cut
 4979: 
 4980: sub get_scantronformat_file {
 4981:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 4982:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
 4983:     my $gottab = 0;
 4984:     my @lines;
 4985:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 4986:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 4987:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 4988:             if ($formatfile ne '-1') {
 4989:                 @lines = split("\n",$formatfile,-1);
 4990:                 $gottab = 1;
 4991:             }
 4992:         }
 4993:     }
 4994:     if (!$gottab) {
 4995:         my $confname = $cdom.'-domainconfig';
 4996:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 4997:         my $formatfile =  &Apache::lonnet::getfile($default);
 4998:         if ($formatfile ne '-1') {
 4999:             @lines = split("\n",$formatfile,-1);
 5000:             $gottab = 1;
 5001:         }
 5002:     }
 5003:     if (!$gottab) {
 5004:         my @domains = &Apache::lonnet::current_machine_domains();
 5005:         if (grep(/^\Q$cdom\E$/,@domains)) {
 5006:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 5007:             @lines = <$fh>;
 5008:             close($fh);
 5009:         } else {
 5010:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
 5011:             @lines = <$fh>;
 5012:             close($fh);
 5013:         }
 5014:     }
 5015:     return @lines;
 5016: }
 5017: 
 5018: =pod 
 5019: 
 5020: =item scantron_CODElist
 5021: 
 5022:   Returns html drop down of the saved CODE lists from current course,
 5023:   generated from earlier printings.
 5024: 
 5025: =cut
 5026: 
 5027: sub scantron_CODElist {
 5028:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5029:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5030:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 5031:     my $namechoice='<option></option>';
 5032:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 5033: 	if ($name =~ /^error: 2 /) { next; }
 5034: 	if ($name =~ /^type\0/) { next; }
 5035: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 5036:     }
 5037:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 5038:     return $namechoice;
 5039: }
 5040: 
 5041: =pod 
 5042: 
 5043: =item scantron_CODEunique
 5044: 
 5045:   Returns the html for "Each CODE to be used once" radio.
 5046: 
 5047: =cut
 5048: 
 5049: sub scantron_CODEunique {
 5050:     my $result='<span class="LC_nobreak">
 5051:                  <label><input type="radio" name="scantron_CODEunique"
 5052:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 5053:                 </span>
 5054:                 <span class="LC_nobreak">
 5055:                  <label><input type="radio" name="scantron_CODEunique"
 5056:                         value="no" />'.&mt('No').' </label>
 5057:                 </span>';
 5058:     return $result;
 5059: }
 5060: 
 5061: =pod 
 5062: 
 5063: =item scantron_selectphase
 5064: 
 5065:   Generates the initial screen to start the bubble sheet process.
 5066:   Allows for - starting a grading run.
 5067:              - downloading existing scan data (original, corrected
 5068:                                                 or skipped info)
 5069: 
 5070:              - uploading new scan data
 5071: 
 5072:  Arguments:
 5073:   $r          - The Apache request object
 5074:   $file2grade - name of the file that contain the scanned data to score
 5075: 
 5076: =cut
 5077: 
 5078: sub scantron_selectphase {
 5079:     my ($r,$file2grade,$symb) = @_;
 5080:     if (!$symb) {return '';}
 5081:     my $map_error;
 5082:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
 5083:     if ($map_error) {
 5084:         $r->print('<br />'.&navmap_errormsg().'<br />');
 5085:         return;
 5086:     }
 5087:     my $default_form_data=&defaultFormData($symb);
 5088:     my $file_selector=&scantron_uploads($file2grade);
 5089:     my $format_selector=&scantron_scantab();
 5090:     my $CODE_selector=&scantron_CODElist();
 5091:     my $CODE_unique=&scantron_CODEunique();
 5092:     my $result;
 5093: 
 5094:     $ssi_error = 0;
 5095: 
 5096:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 5097:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 5098: 
 5099: 	# Chunk of form to prompt for a scantron file upload.
 5100: 
 5101:         $r->print('
 5102:     <br />
 5103:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5104:        '.&Apache::loncommon::start_data_table_header_row().'
 5105:             <th>
 5106:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
 5107:             </th>
 5108:        '.&Apache::loncommon::end_data_table_header_row().'
 5109:        '.&Apache::loncommon::start_data_table_row().'
 5110:             <td>
 5111: ');
 5112:     my $default_form_data=&defaultFormData($symb);
 5113:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5114:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 5115:     $r->print(&Apache::lonhtmlcommon::scripttag('
 5116:     function checkUpload(formname) {
 5117: 	if (formname.upfile.value == "") {
 5118: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
 5119: 	    return false;
 5120: 	}
 5121: 	formname.submit();
 5122:     }'));
 5123:     $r->print('
 5124:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 5125:                 '.$default_form_data.'
 5126:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 5127:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 5128:                 <input name="command" value="scantronupload_save" type="hidden" />
 5129:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
 5130:                 <br />
 5131:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 5132:               </form>
 5133: ');
 5134: 
 5135:         $r->print('
 5136:             </td>
 5137:        '.&Apache::loncommon::end_data_table_row().'
 5138:        '.&Apache::loncommon::end_data_table().'
 5139: ');
 5140:     }
 5141: 
 5142:     # Chunk of form to prompt for a file to grade and how:
 5143: 
 5144:     $result.= '
 5145:     <br />
 5146:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 5147:     <input type="hidden" name="command" value="scantron_warning" />
 5148:     '.$default_form_data.'
 5149:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5150:        '.&Apache::loncommon::start_data_table_header_row().'
 5151:             <th colspan="2">
 5152:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 5153:             </th>
 5154:        '.&Apache::loncommon::end_data_table_header_row().'
 5155:        '.&Apache::loncommon::start_data_table_row().'
 5156:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 5157:        '.&Apache::loncommon::end_data_table_row().'
 5158:        '.&Apache::loncommon::start_data_table_row().'
 5159:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
 5160:        '.&Apache::loncommon::end_data_table_row().'
 5161:        '.&Apache::loncommon::start_data_table_row().'
 5162:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
 5163:        '.&Apache::loncommon::end_data_table_row().'
 5164:        '.&Apache::loncommon::start_data_table_row().'
 5165:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 5166:        '.&Apache::loncommon::end_data_table_row().'
 5167:        '.&Apache::loncommon::start_data_table_row().'
 5168:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 5169:        '.&Apache::loncommon::end_data_table_row().'
 5170:        '.&Apache::loncommon::start_data_table_row().'
 5171: 	    <td> '.&mt('Options:').' </td>
 5172:             <td>
 5173: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 5174:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 5175:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 5176: 	    </td>
 5177:        '.&Apache::loncommon::end_data_table_row().'
 5178:        '.&Apache::loncommon::start_data_table_row().'
 5179:             <td colspan="2">
 5180:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
 5181:             </td>
 5182:        '.&Apache::loncommon::end_data_table_row().'
 5183:     '.&Apache::loncommon::end_data_table().'
 5184:     </form>
 5185: ';
 5186:    
 5187:     $r->print($result);
 5188: 
 5189: 
 5190: 
 5191:     # Chunk of the form that prompts to view a scoring office file,
 5192:     # corrected file, skipped records in a file.
 5193: 
 5194:     $r->print('
 5195:    <br />
 5196:    <form action="/adm/grades" name="scantron_download">
 5197:      '.$default_form_data.'
 5198:      <input type="hidden" name="command" value="scantron_download" />
 5199:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5200:        '.&Apache::loncommon::start_data_table_header_row().'
 5201:               <th>
 5202:                 &nbsp;'.&mt('Download a scoring office file').'
 5203:               </th>
 5204:        '.&Apache::loncommon::end_data_table_header_row().'
 5205:        '.&Apache::loncommon::start_data_table_row().'
 5206:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 5207:                 <br />
 5208:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 5209:        '.&Apache::loncommon::end_data_table_row().'
 5210:      '.&Apache::loncommon::end_data_table().'
 5211:    </form>
 5212:    <br />
 5213: ');
 5214: 
 5215:     &Apache::lonpickcode::code_list($r,2);
 5216: 
 5217:     $r->print('<br /><form method="post" name="checkscantron">'.
 5218:              $default_form_data."\n".
 5219:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 5220:              &Apache::loncommon::start_data_table_header_row()."\n".
 5221:              '<th colspan="2">
 5222:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
 5223:              '</th>'."\n".
 5224:               &Apache::loncommon::end_data_table_header_row()."\n".
 5225:               &Apache::loncommon::start_data_table_row()."\n".
 5226:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 5227:               '<td> '.$sequence_selector.' </td>'.
 5228:               &Apache::loncommon::end_data_table_row()."\n".
 5229:               &Apache::loncommon::start_data_table_row()."\n".
 5230:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 5231:               '<td> '.$file_selector.' </td>'."\n".
 5232:               &Apache::loncommon::end_data_table_row()."\n".
 5233:               &Apache::loncommon::start_data_table_row()."\n".
 5234:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 5235:               '<td> '.$format_selector.' </td>'."\n".
 5236:               &Apache::loncommon::end_data_table_row()."\n".
 5237:               &Apache::loncommon::start_data_table_row()."\n".
 5238:               '<td> '.&mt('Options').' </td>'."\n".
 5239:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
 5240:               &Apache::loncommon::end_data_table_row()."\n".
 5241:               &Apache::loncommon::start_data_table_row()."\n".
 5242:               '<td colspan="2">'."\n".
 5243:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 5244:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
 5245:               '</td>'."\n".
 5246:               &Apache::loncommon::end_data_table_row()."\n".
 5247:               &Apache::loncommon::end_data_table()."\n".
 5248:               '</form><br />');
 5249:     return;
 5250: }
 5251: 
 5252: =pod
 5253: 
 5254: =item get_scantron_config
 5255: 
 5256:    Parse and return the scantron configuration line selected as a
 5257:    hash of configuration file fields.
 5258: 
 5259:  Arguments:
 5260:     which - the name of the configuration to parse from the file.
 5261: 
 5262: 
 5263:  Returns:
 5264:             If the named configuration is not in the file, an empty
 5265:             hash is returned.
 5266:     a hash with the fields
 5267:       name         - internal name for the this configuration setup
 5268:       description  - text to display to operator that describes this config
 5269:       CODElocation - if 0 or the string 'none'
 5270:                           - no CODE exists for this config
 5271:                      if -1 || the string 'letter'
 5272:                           - a CODE exists for this config and is
 5273:                             a string of letters
 5274:                      Unsupported value (but planned for future support)
 5275:                           if a positive integer
 5276:                                - The CODE exists as the first n items from
 5277:                                  the question section of the form
 5278:                           if the string 'number'
 5279:                                - The CODE exists for this config and is
 5280:                                  a string of numbers
 5281:       CODEstart   - (only matter if a CODE exists) column in the line where
 5282:                      the CODE starts
 5283:       CODElength  - length of the CODE
 5284:       IDstart     - column where the student/employee ID starts
 5285:       IDlength    - length of the student/employee ID info
 5286:       Qstart      - column where the information from the bubbled
 5287:                     'questions' start
 5288:       Qlength     - number of columns comprising a single bubble line from
 5289:                     the sheet. (usually either 1 or 10)
 5290:       Qon         - either a single character representing the character used
 5291:                     to signal a bubble was chosen in the positional setup, or
 5292:                     the string 'letter' if the letter of the chosen bubble is
 5293:                     in the final, or 'number' if a number representing the
 5294:                     chosen bubble is in the file (1->A 0->J)
 5295:       Qoff        - the character used to represent that a bubble was
 5296:                     left blank
 5297:       PaperID     - if the scanning process generates a unique number for each
 5298:                     sheet scanned the column that this ID number starts in
 5299:       PaperIDlength - number of columns that comprise the unique ID number
 5300:                       for the sheet of paper
 5301:       FirstName   - column that the first name starts in
 5302:       FirstNameLength - number of columns that the first name spans
 5303:  
 5304:       LastName    - column that the last name starts in
 5305:       LastNameLength - number of columns that the last name spans
 5306: 
 5307: =cut
 5308: 
 5309: sub get_scantron_config {
 5310:     my ($which) = @_;
 5311:     my @lines = &get_scantronformat_file();
 5312:     my %config;
 5313:     #FIXME probably should move to XML it has already gotten a bit much now
 5314:     foreach my $line (@lines) {
 5315: 	my ($name,$descrip)=split(/:/,$line);
 5316: 	if ($name ne $which ) { next; }
 5317: 	chomp($line);
 5318: 	my @config=split(/:/,$line);
 5319: 	$config{'name'}=$config[0];
 5320: 	$config{'description'}=$config[1];
 5321: 	$config{'CODElocation'}=$config[2];
 5322: 	$config{'CODEstart'}=$config[3];
 5323: 	$config{'CODElength'}=$config[4];
 5324: 	$config{'IDstart'}=$config[5];
 5325: 	$config{'IDlength'}=$config[6];
 5326: 	$config{'Qstart'}=$config[7];
 5327:  	$config{'Qlength'}=$config[8];
 5328: 	$config{'Qoff'}=$config[9];
 5329: 	$config{'Qon'}=$config[10];
 5330: 	$config{'PaperID'}=$config[11];
 5331: 	$config{'PaperIDlength'}=$config[12];
 5332: 	$config{'FirstName'}=$config[13];
 5333: 	$config{'FirstNamelength'}=$config[14];
 5334: 	$config{'LastName'}=$config[15];
 5335: 	$config{'LastNamelength'}=$config[16];
 5336: 	last;
 5337:     }
 5338:     return %config;
 5339: }
 5340: 
 5341: =pod 
 5342: 
 5343: =item username_to_idmap
 5344: 
 5345:     creates a hash keyed by student/employee ID with values of the corresponding
 5346:     student username:domain.
 5347: 
 5348:   Arguments:
 5349: 
 5350:     $classlist - reference to the class list hash. This is a hash
 5351:                  keyed by student name:domain  whose elements are references
 5352:                  to arrays containing various chunks of information
 5353:                  about the student. (See loncoursedata for more info).
 5354: 
 5355:   Returns
 5356:     %idmap - the constructed hash
 5357: 
 5358: =cut
 5359: 
 5360: sub username_to_idmap {
 5361:     my ($classlist)= @_;
 5362:     my %idmap;
 5363:     foreach my $student (keys(%$classlist)) {
 5364: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
 5365: 	    $student;
 5366:     }
 5367:     return %idmap;
 5368: }
 5369: 
 5370: =pod
 5371: 
 5372: =item scantron_fixup_scanline
 5373: 
 5374:    Process a requested correction to a scanline.
 5375: 
 5376:   Arguments:
 5377:     $scantron_config   - hash from &get_scantron_config()
 5378:     $scan_data         - hash of correction information 
 5379:                           (see &scantron_getfile())
 5380:     $line              - existing scanline
 5381:     $whichline         - line number of the passed in scanline
 5382:     $field             - type of change to process 
 5383:                          (either 
 5384:                           'ID'     -> correct the student/employee ID
 5385:                           'CODE'   -> correct the CODE
 5386:                           'answer' -> fixup the submitted answers)
 5387:     
 5388:    $args               - hash of additional info,
 5389:                           - 'ID' 
 5390:                                'newid' -> studentID to use in replacement
 5391:                                           of existing one
 5392:                           - 'CODE' 
 5393:                                'CODE_ignore_dup' - set to true if duplicates
 5394:                                                    should be ignored.
 5395: 	                       'CODE' - is new code or 'use_unfound'
 5396:                                         if the existing unfound code should
 5397:                                         be used as is
 5398:                           - 'answer'
 5399:                                'response' - new answer or 'none' if blank
 5400:                                'question' - the bubble line to change
 5401:                                'questionnum' - the question identifier,
 5402:                                                may include subquestion. 
 5403: 
 5404:   Returns:
 5405:     $line - the modified scanline
 5406: 
 5407:   Side effects: 
 5408:     $scan_data - may be updated
 5409: 
 5410: =cut
 5411: 
 5412: 
 5413: sub scantron_fixup_scanline {
 5414:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 5415:     if ($field eq 'ID') {
 5416: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 5417: 	    return ($line,1,'New value too large');
 5418: 	}
 5419: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 5420: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 5421: 				     $args->{'newid'});
 5422: 	}
 5423: 	substr($line,$$scantron_config{'IDstart'}-1,
 5424: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 5425: 	if ($args->{'newid'}=~/^\s*$/) {
 5426: 	    &scan_data($scan_data,"$whichline.user",
 5427: 		       $args->{'username'}.':'.$args->{'domain'});
 5428: 	}
 5429:     } elsif ($field eq 'CODE') {
 5430: 	if ($args->{'CODE_ignore_dup'}) {
 5431: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 5432: 	}
 5433: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 5434: 	if ($args->{'CODE'} ne 'use_unfound') {
 5435: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 5436: 		return ($line,1,'New CODE value too large');
 5437: 	    }
 5438: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 5439: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 5440: 	    }
 5441: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 5442: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 5443: 	}
 5444:     } elsif ($field eq 'answer') {
 5445: 	my $length=$scantron_config->{'Qlength'};
 5446: 	my $off=$scantron_config->{'Qoff'};
 5447: 	my $on=$scantron_config->{'Qon'};
 5448: 	my $answer=${off}x$length;
 5449: 	if ($args->{'response'} eq 'none') {
 5450: 	    &scan_data($scan_data,
 5451: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 5452: 	} else {
 5453: 	    if ($on eq 'letter') {
 5454: 		my @alphabet=('A'..'Z');
 5455: 		$answer=$alphabet[$args->{'response'}];
 5456: 	    } elsif ($on eq 'number') {
 5457: 		$answer=$args->{'response'}+1;
 5458: 		if ($answer == 10) { $answer = '0'; }
 5459: 	    } else {
 5460: 		substr($answer,$args->{'response'},1)=$on;
 5461: 	    }
 5462: 	    &scan_data($scan_data,
 5463: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 5464: 	}
 5465: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 5466: 	substr($line,$where-1,$length)=$answer;
 5467:     }
 5468:     return $line;
 5469: }
 5470: 
 5471: =pod
 5472: 
 5473: =item scan_data
 5474: 
 5475:     Edit or look up  an item in the scan_data hash.
 5476: 
 5477:   Arguments:
 5478:     $scan_data  - The hash (see scantron_getfile)
 5479:     $key        - shorthand of the key to edit (actual key is
 5480:                   scantronfilename_key).
 5481:     $data        - New value of the hash entry.
 5482:     $delete      - If true, the entry is removed from the hash.
 5483: 
 5484:   Returns:
 5485:     The new value of the hash table field (undefined if deleted).
 5486: 
 5487: =cut
 5488: 
 5489: 
 5490: sub scan_data {
 5491:     my ($scan_data,$key,$value,$delete)=@_;
 5492:     my $filename=$env{'form.scantron_selectfile'};
 5493:     if (defined($value)) {
 5494: 	$scan_data->{$filename.'_'.$key} = $value;
 5495:     }
 5496:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 5497:     return $scan_data->{$filename.'_'.$key};
 5498: }
 5499: 
 5500: # ----- These first few routines are general use routines.----
 5501: 
 5502: # Return the number of occurences of a pattern in a string.
 5503: 
 5504: sub occurence_count {
 5505:     my ($string, $pattern) = @_;
 5506: 
 5507:     my @matches = ($string =~ /$pattern/g);
 5508: 
 5509:     return scalar(@matches);
 5510: }
 5511: 
 5512: 
 5513: # Take a string known to have digits and convert all the
 5514: # digits into letters in the range J,A..I.
 5515: 
 5516: sub digits_to_letters {
 5517:     my ($input) = @_;
 5518: 
 5519:     my @alphabet = ('J', 'A'..'I');
 5520: 
 5521:     my @input    = split(//, $input);
 5522:     my $output ='';
 5523:     for (my $i = 0; $i < scalar(@input); $i++) {
 5524: 	if ($input[$i] =~ /\d/) {
 5525: 	    $output .= $alphabet[$input[$i]];
 5526: 	} else {
 5527: 	    $output .= $input[$i];
 5528: 	}
 5529:     }
 5530:     return $output;
 5531: }
 5532: 
 5533: =pod 
 5534: 
 5535: =item scantron_parse_scanline
 5536: 
 5537:   Decodes a scanline from the selected scantron file
 5538: 
 5539:  Arguments:
 5540:     line             - The text of the scantron file line to process
 5541:     whichline        - Line number
 5542:     scantron_config  - Hash describing the format of the scantron lines.
 5543:     scan_data        - Hash of extra information about the scanline
 5544:                        (see scantron_getfile for more information)
 5545:     just_header      - True if should not process question answers but only
 5546:                        the stuff to the left of the answers.
 5547:  Returns:
 5548:    Hash containing the result of parsing the scanline
 5549: 
 5550:    Keys are all proceeded by the string 'scantron.'
 5551: 
 5552:        CODE    - the CODE in use for this scanline
 5553:        useCODE - 1 if the CODE is invalid but it usage has been forced
 5554:                  by the operator
 5555:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 5556:                             CODEs were selected, but the usage has been
 5557:                             forced by the operator
 5558:        ID  - student/employee ID
 5559:        PaperID - if used, the ID number printed on the sheet when the 
 5560:                  paper was scanned
 5561:        FirstName - first name from the sheet
 5562:        LastName  - last name from the sheet
 5563: 
 5564:      if just_header was not true these key may also exist
 5565: 
 5566:        missingerror - a list of bubble ranges that are considered to be answers
 5567:                       to a single question that don't have any bubbles filled in.
 5568:                       Of the form questionnumber:firstbubblenumber:count.
 5569:        doubleerror  - a list of bubble ranges that are considered to be answers
 5570:                       to a single question that have more than one bubble filled in.
 5571:                       Of the form questionnumber::firstbubblenumber:count
 5572:    
 5573:                 In the above, count is the number of bubble responses in the
 5574:                 input line needed to represent the possible answers to the question.
 5575:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 5576:                 per line would have count = 2.
 5577: 
 5578:        maxquest     - the number of the last bubble line that was parsed
 5579: 
 5580:        (<number> starts at 1)
 5581:        <number>.answer - zero or more letters representing the selected
 5582:                          letters from the scanline for the bubble line 
 5583:                          <number>.
 5584:                          if blank there was either no bubble or there where
 5585:                          multiple bubbles, (consult the keys missingerror and
 5586:                          doubleerror if this is an error condition)
 5587: 
 5588: =cut
 5589: 
 5590: sub scantron_parse_scanline {
 5591:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
 5592: 
 5593:     my %record;
 5594:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 5595:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 5596:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
 5597:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 5598: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 5599: 	if ($$scantron_config{'CODElocation'} < 0 ||
 5600: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 5601: 	    $$scantron_config{'CODElocation'} eq 'number') {
 5602: 	    $record{'scantron.CODE'}=substr($data,
 5603: 					    $$scantron_config{'CODEstart'}-1,
 5604: 					    $$scantron_config{'CODElength'});
 5605: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 5606: 		$record{'scantron.useCODE'}=1;
 5607: 	    }
 5608: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 5609: 		$record{'scantron.CODE_ignore_dup'}=1;
 5610: 	    }
 5611: 	} else {
 5612: 	    #FIXME interpret first N questions
 5613: 	}
 5614:     }
 5615:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 5616: 				  $$scantron_config{'IDlength'});
 5617:     $record{'scantron.PaperID'}=
 5618: 	substr($data,$$scantron_config{'PaperID'}-1,
 5619: 	       $$scantron_config{'PaperIDlength'});
 5620:     $record{'scantron.FirstName'}=
 5621: 	substr($data,$$scantron_config{'FirstName'}-1,
 5622: 	       $$scantron_config{'FirstNamelength'});
 5623:     $record{'scantron.LastName'}=
 5624: 	substr($data,$$scantron_config{'LastName'}-1,
 5625: 	       $$scantron_config{'LastNamelength'});
 5626:     if ($just_header) { return \%record; }
 5627: 
 5628:     my @alphabet=('A'..'Z');
 5629:     my $questnum=0;
 5630:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 5631: 
 5632:     chomp($questions);		# Get rid of any trailing \n.
 5633:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 5634:     while (length($questions)) {
 5635: 	my $answers_needed = $bubble_lines_per_response{$questnum};
 5636:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 5637:                              || 1;
 5638:         $questnum++;
 5639:         my $quest_id = $questnum;
 5640:         my $currentquest = substr($questions,0,$answer_length);
 5641:         $questions       = substr($questions,$answer_length);
 5642:         if (length($currentquest) < $answer_length) { next; }
 5643: 
 5644:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
 5645:             my $subquestnum = 1;
 5646:             my $subquestions = $currentquest;
 5647:             my @subanswers_needed = 
 5648:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
 5649:             foreach my $subans (@subanswers_needed) {
 5650:                 my $subans_length =
 5651:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 5652:                 my $currsubquest = substr($subquestions,0,$subans_length);
 5653:                 $subquestions   = substr($subquestions,$subans_length);
 5654:                 $quest_id = "$questnum.$subquestnum";
 5655:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 5656:                     ($$scantron_config{'Qon'} eq 'number')) {
 5657:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 5658:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 5659:                         \@alphabet,\%record,$scantron_config,$scan_data);
 5660:                 } else {
 5661:                     $ansnum = &scantron_validator_positional($ansnum,
 5662:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
 5663:                 }
 5664:                 $subquestnum ++;
 5665:             }
 5666:         } else {
 5667:             if (($$scantron_config{'Qon'} eq 'letter') ||
 5668:                 ($$scantron_config{'Qon'} eq 'number')) {
 5669:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 5670:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5671:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5672:             } else {
 5673:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 5674:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5675:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5676:             }
 5677:         }
 5678:     }
 5679:     $record{'scantron.maxquest'}=$questnum;
 5680:     return \%record;
 5681: }
 5682: 
 5683: sub scantron_validator_lettnum {
 5684:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 5685:         $alphabet,$record,$scantron_config,$scan_data) = @_;
 5686: 
 5687:     # Qon 'letter' implies for each slot in currquest we have:
 5688:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 5689:     #    about anything else (esp. a value of Qoff) for missing
 5690:     #    bubbles.
 5691:     #
 5692:     # Qon 'number' implies each slot gives a digit that indexes the
 5693:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 5694:     #    and * or ? for double bubbles on a single line.
 5695:     #
 5696: 
 5697:     my $matchon;
 5698:     if ($$scantron_config{'Qon'} eq 'letter') {
 5699:         $matchon = '[A-Z]';
 5700:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 5701:         $matchon = '\d';
 5702:     }
 5703:     my $occurrences = 0;
 5704:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5705:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5706:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5707:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5708:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5709:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5710:         my @singlelines = split('',$currquest);
 5711:         foreach my $entry (@singlelines) {
 5712:             $occurrences = &occurence_count($entry,$matchon);
 5713:             if ($occurrences > 1) {
 5714:                 last;
 5715:             }
 5716:         } 
 5717:     } else {
 5718:         $occurrences = &occurence_count($currquest,$matchon); 
 5719:     }
 5720:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 5721:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5722:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5723:             my $bubble = substr($currquest,$ans,1);
 5724:             if ($bubble =~ /$matchon/ ) {
 5725:                 if ($$scantron_config{'Qon'} eq 'number') {
 5726:                     if ($bubble == 0) {
 5727:                         $bubble = 10; 
 5728:                     }
 5729:                     $record->{"scantron.$ansnum.answer"} = 
 5730:                         $alphabet->[$bubble-1];
 5731:                 } else {
 5732:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 5733:                 }
 5734:             } else {
 5735:                 $record->{"scantron.$ansnum.answer"}='';
 5736:             }
 5737:             $ansnum++;
 5738:         }
 5739:     } elsif (!defined($currquest)
 5740:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 5741:             || (&occurence_count($currquest,$matchon) == 0)) {
 5742:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5743:             $record->{"scantron.$ansnum.answer"}='';
 5744:             $ansnum++;
 5745:         }
 5746:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5747:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 5748:         }
 5749:     } else {
 5750:         if ($$scantron_config{'Qon'} eq 'number') {
 5751:             $currquest = &digits_to_letters($currquest);            
 5752:         }
 5753:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5754:             my $bubble = substr($currquest,$ans,1);
 5755:             $record->{"scantron.$ansnum.answer"} = $bubble;
 5756:             $ansnum++;
 5757:         }
 5758:     }
 5759:     return $ansnum;
 5760: }
 5761: 
 5762: sub scantron_validator_positional {
 5763:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 5764:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
 5765: 
 5766:     # Otherwise there's a positional notation;
 5767:     # each bubble line requires Qlength items, and there are filled in
 5768:     # bubbles for each case where there 'Qon' characters.
 5769:     #
 5770: 
 5771:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 5772: 
 5773:     # If the split only gives us one element.. the full length of the
 5774:     # answer string, no bubbles are filled in:
 5775: 
 5776:     if ($answers_needed eq '') {
 5777:         return;
 5778:     }
 5779: 
 5780:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 5781:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5782:             $record->{"scantron.$ansnum.answer"}='';
 5783:             $ansnum++;
 5784:         }
 5785:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5786:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 5787:         }
 5788:     } elsif (scalar(@array) == 2) {
 5789:         my $location = length($array[0]);
 5790:         my $line_num = int($location / $$scantron_config{'Qlength'});
 5791:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 5792:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5793:             if ($ans eq $line_num) {
 5794:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 5795:             } else {
 5796:                 $record->{"scantron.$ansnum.answer"} = ' ';
 5797:             }
 5798:             $ansnum++;
 5799:          }
 5800:     } else {
 5801:         #  If there's more than one instance of a bubble character
 5802:         #  That's a double bubble; with positional notation we can
 5803:         #  record all the bubbles filled in as well as the
 5804:         #  fact this response consists of multiple bubbles.
 5805:         #
 5806:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5807:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5808:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5809:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5810:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5811:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5812:             my $doubleerror = 0;
 5813:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 5814:                    (!$doubleerror)) {
 5815:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 5816:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 5817:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 5818:                if (length(@currarray) > 2) {
 5819:                    $doubleerror = 1;
 5820:                } 
 5821:             }
 5822:             if ($doubleerror) {
 5823:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5824:             }
 5825:         } else {
 5826:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5827:         }
 5828:         my $item = $ansnum;
 5829:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5830:             $record->{"scantron.$item.answer"} = '';
 5831:             $item ++;
 5832:         }
 5833: 
 5834:         my @ans=@array;
 5835:         my $i=0;
 5836:         my $increment = 0;
 5837:         while ($#ans) {
 5838:             $i+=length($ans[0]) + $increment;
 5839:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 5840:             my $bubble = $i%$$scantron_config{'Qlength'};
 5841:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 5842:             shift(@ans);
 5843:             $increment = 1;
 5844:         }
 5845:         $ansnum += $answers_needed;
 5846:     }
 5847:     return $ansnum;
 5848: }
 5849: 
 5850: =pod
 5851: 
 5852: =item scantron_add_delay
 5853: 
 5854:    Adds an error message that occurred during the grading phase to a
 5855:    queue of messages to be shown after grading pass is complete
 5856: 
 5857:  Arguments:
 5858:    $delayqueue  - arrary ref of hash ref of error messages
 5859:    $scanline    - the scanline that caused the error
 5860:    $errormesage - the error message
 5861:    $errorcode   - a numeric code for the error
 5862: 
 5863:  Side Effects:
 5864:    updates the $delayqueue to have a new hash ref of the error
 5865: 
 5866: =cut
 5867: 
 5868: sub scantron_add_delay {
 5869:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 5870:     push(@$delayqueue,
 5871: 	 {'line' => $scanline, 'emsg' => $errormessage,
 5872: 	  'ecode' => $errorcode }
 5873: 	 );
 5874: }
 5875: 
 5876: =pod
 5877: 
 5878: =item scantron_find_student
 5879: 
 5880:    Finds the username for the current scanline
 5881: 
 5882:   Arguments:
 5883:    $scantron_record - hash result from scantron_parse_scanline
 5884:    $scan_data       - hash of correction information 
 5885:                       (see &scantron_getfile() form more information)
 5886:    $idmap           - hash from &username_to_idmap()
 5887:    $line            - number of current scanline
 5888:  
 5889:   Returns:
 5890:    Either 'username:domain' or undef if unknown
 5891: 
 5892: =cut
 5893: 
 5894: sub scantron_find_student {
 5895:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 5896:     my $scanID=$$scantron_record{'scantron.ID'};
 5897:     if ($scanID =~ /^\s*$/) {
 5898:  	return &scan_data($scan_data,"$line.user");
 5899:     }
 5900:     foreach my $id (keys(%$idmap)) {
 5901:  	if (lc($id) eq lc($scanID)) {
 5902:  	    return $$idmap{$id};
 5903:  	}
 5904:     }
 5905:     return undef;
 5906: }
 5907: 
 5908: =pod
 5909: 
 5910: =item scantron_filter
 5911: 
 5912:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 5913:    hidden resources was selected
 5914: 
 5915: =cut
 5916: 
 5917: sub scantron_filter {
 5918:     my ($curres)=@_;
 5919: 
 5920:     if (ref($curres) && $curres->is_problem()) {
 5921: 	# if the user has asked to not have either hidden
 5922: 	# or 'randomout' controlled resources to be graded
 5923: 	# don't include them
 5924: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 5925: 	    && $curres->randomout) {
 5926: 	    return 0;
 5927: 	}
 5928: 	return 1;
 5929:     }
 5930:     return 0;
 5931: }
 5932: 
 5933: =pod
 5934: 
 5935: =item scantron_process_corrections
 5936: 
 5937:    Gets correction information out of submitted form data and corrects
 5938:    the scanline
 5939: 
 5940: =cut
 5941: 
 5942: sub scantron_process_corrections {
 5943:     my ($r) = @_;
 5944:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 5945:     my ($scanlines,$scan_data)=&scantron_getfile();
 5946:     my $classlist=&Apache::loncoursedata::get_classlist();
 5947:     my $which=$env{'form.scantron_line'};
 5948:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 5949:     my ($skip,$err,$errmsg);
 5950:     if ($env{'form.scantron_skip_record'}) {
 5951: 	$skip=1;
 5952:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 5953: 	my $newstudent=$env{'form.scantron_username'}.':'.
 5954: 	    $env{'form.scantron_domain'};
 5955: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 5956: 	($line,$err,$errmsg)=
 5957: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 5958: 				     'ID',{'newid'=>$newid,
 5959: 				    'username'=>$env{'form.scantron_username'},
 5960: 				    'domain'=>$env{'form.scantron_domain'}});
 5961:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 5962: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 5963: 	my $newCODE;
 5964: 	my %args;
 5965: 	if      ($resolution eq 'use_unfound') {
 5966: 	    $newCODE='use_unfound';
 5967: 	} elsif ($resolution eq 'use_found') {
 5968: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 5969: 	} elsif ($resolution eq 'use_typed') {
 5970: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 5971: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 5972: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 5973: 	}
 5974: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 5975: 	    $args{'CODE_ignore_dup'}=1;
 5976: 	}
 5977: 	$args{'CODE'}=$newCODE;
 5978: 	($line,$err,$errmsg)=
 5979: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 5980: 				     'CODE',\%args);
 5981:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 5982: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 5983: 	    ($line,$err,$errmsg)=
 5984: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 5985: 					 $which,'answer',
 5986: 					 { 'question'=>$question,
 5987: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 5988:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 5989: 	    if ($err) { last; }
 5990: 	}
 5991:     }
 5992:     if ($err) {
 5993: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
 5994:     } else {
 5995: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 5996: 	&scantron_putfile($scanlines,$scan_data);
 5997:     }
 5998: }
 5999: 
 6000: =pod
 6001: 
 6002: =item reset_skipping_status
 6003: 
 6004:    Forgets the current set of remember skipped scanlines (and thus
 6005:    reverts back to considering all lines in the
 6006:    scantron_skipped_<filename> file)
 6007: 
 6008: =cut
 6009: 
 6010: sub reset_skipping_status {
 6011:     my ($scanlines,$scan_data)=&scantron_getfile();
 6012:     &scan_data($scan_data,'remember_skipping',undef,1);
 6013:     &scantron_putfile(undef,$scan_data);
 6014: }
 6015: 
 6016: =pod
 6017: 
 6018: =item start_skipping
 6019: 
 6020:    Marks a scanline to be skipped. 
 6021: 
 6022: =cut
 6023: 
 6024: sub start_skipping {
 6025:     my ($scan_data,$i)=@_;
 6026:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6027:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 6028: 	$remembered{$i}=2;
 6029:     } else {
 6030: 	$remembered{$i}=1;
 6031:     }
 6032:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 6033: }
 6034: 
 6035: =pod
 6036: 
 6037: =item should_be_skipped
 6038: 
 6039:    Checks whether a scanline should be skipped.
 6040: 
 6041: =cut
 6042: 
 6043: sub should_be_skipped {
 6044:     my ($scanlines,$scan_data,$i)=@_;
 6045:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 6046: 	# not redoing old skips
 6047: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 6048: 	return 0;
 6049:     }
 6050:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6051: 
 6052:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 6053: 	return 0;
 6054:     }
 6055:     return 1;
 6056: }
 6057: 
 6058: =pod
 6059: 
 6060: =item remember_current_skipped
 6061: 
 6062:    Discovers what scanlines are in the scantron_skipped_<filename>
 6063:    file and remembers them into scan_data for later use.
 6064: 
 6065: =cut
 6066: 
 6067: sub remember_current_skipped {
 6068:     my ($scanlines,$scan_data)=&scantron_getfile();
 6069:     my %to_remember;
 6070:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6071: 	if ($scanlines->{'skipped'}[$i]) {
 6072: 	    $to_remember{$i}=1;
 6073: 	}
 6074:     }
 6075: 
 6076:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 6077:     &scantron_putfile(undef,$scan_data);
 6078: }
 6079: 
 6080: =pod
 6081: 
 6082: =item check_for_error
 6083: 
 6084:     Checks if there was an error when attempting to remove a specific
 6085:     scantron_.. bubble sheet data file. Prints out an error if
 6086:     something went wrong.
 6087: 
 6088: =cut
 6089: 
 6090: sub check_for_error {
 6091:     my ($r,$result)=@_;
 6092:     if ($result ne 'ok' && $result ne 'not_found' ) {
 6093: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 6094:     }
 6095: }
 6096: 
 6097: =pod
 6098: 
 6099: =item scantron_warning_screen
 6100: 
 6101:    Interstitial screen to make sure the operator has selected the
 6102:    correct options before we start the validation phase.
 6103: 
 6104: =cut
 6105: 
 6106: sub scantron_warning_screen {
 6107:     my ($button_text)=@_;
 6108:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 6109:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6110:     my $CODElist;
 6111:     if ($scantron_config{'CODElocation'} &&
 6112: 	$scantron_config{'CODEstart'} &&
 6113: 	$scantron_config{'CODElength'}) {
 6114: 	$CODElist=$env{'form.scantron_CODElist'};
 6115: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
 6116: 	$CODElist=
 6117: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 6118: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 6119:     }
 6120:     return ('
 6121: <p>
 6122: <span class="LC_warning">
 6123: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
 6124: </p>
 6125: <table>
 6126: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 6127: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 6128: '.$CODElist.'
 6129: </table>
 6130: <br />
 6131: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
 6132: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
 6133: 
 6134: <br />
 6135: ');
 6136: }
 6137: 
 6138: =pod
 6139: 
 6140: =item scantron_do_warning
 6141: 
 6142:    Check if the operator has picked something for all required
 6143:    fields. Error out if something is missing.
 6144: 
 6145: =cut
 6146: 
 6147: sub scantron_do_warning {
 6148:     my ($r,$symb)=@_;
 6149:     if (!$symb) {return '';}
 6150:     my $default_form_data=&defaultFormData($symb);
 6151:     $r->print(&scantron_form_start().$default_form_data);
 6152:     if ( $env{'form.selectpage'} eq '' ||
 6153: 	 $env{'form.scantron_selectfile'} eq '' ||
 6154: 	 $env{'form.scantron_format'} eq '' ) {
 6155: 	$r->print("<p>".&mt('You have forgetten to specify some information. Please go Back and try again.')."</p>");
 6156: 	if ( $env{'form.selectpage'} eq '') {
 6157: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 6158: 	} 
 6159: 	if ( $env{'form.scantron_selectfile'} eq '') {
 6160: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a file that contains the student\'s response data.').'</span></p>');
 6161: 	} 
 6162: 	if ( $env{'form.scantron_format'} eq '') {
 6163: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a the format of the student\'s response data.').'</span></p>');
 6164: 	} 
 6165:     } else {
 6166: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
 6167: 	$r->print('
 6168: '.$warning.'
 6169: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 6170: <input type="hidden" name="command" value="scantron_validate" />
 6171: ');
 6172:     }
 6173:     $r->print("</form><br />");
 6174:     return '';
 6175: }
 6176: 
 6177: =pod
 6178: 
 6179: =item scantron_form_start
 6180: 
 6181:     html hidden input for remembering all selected grading options
 6182: 
 6183: =cut
 6184: 
 6185: sub scantron_form_start {
 6186:     my ($max_bubble)=@_;
 6187:     my $result= <<SCANTRONFORM;
 6188: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 6189:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 6190:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 6191:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 6192:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 6193:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 6194:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 6195:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 6196:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 6197:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 6198: SCANTRONFORM
 6199: 
 6200:   my $line = 0;
 6201:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 6202:        my $chunk =
 6203: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 6204:        $chunk .=
 6205: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 6206:        $chunk .= 
 6207:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 6208:        $chunk .=
 6209:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 6210:        $result .= $chunk;
 6211:        $line++;
 6212:    }
 6213:     return $result;
 6214: }
 6215: 
 6216: =pod
 6217: 
 6218: =item scantron_validate_file
 6219: 
 6220:     Dispatch routine for doing validation of a bubble sheet data file.
 6221: 
 6222:     Also processes any necessary information resets that need to
 6223:     occur before validation begins (ignore previous corrections,
 6224:     restarting the skipped records processing)
 6225: 
 6226: =cut
 6227: 
 6228: sub scantron_validate_file {
 6229:     my ($r,$symb) = @_;
 6230:     if (!$symb) {return '';}
 6231:     my $default_form_data=&defaultFormData($symb);
 6232:     
 6233:     # do the detection of only doing skipped records first befroe we delete
 6234:     # them when doing the corrections reset
 6235:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 6236: 	&reset_skipping_status();
 6237:     }
 6238:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 6239: 	&remember_current_skipped();
 6240: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 6241:     }
 6242: 
 6243:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 6244: 	&check_for_error($r,&scantron_remove_file('corrected'));
 6245: 	&check_for_error($r,&scantron_remove_file('skipped'));
 6246: 	&check_for_error($r,&scantron_remove_scan_data());
 6247: 	$env{'form.scantron_options_ignore'}='done';
 6248:     }
 6249: 
 6250:     if ($env{'form.scantron_corrections'}) {
 6251: 	&scantron_process_corrections($r);
 6252:     }
 6253:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 6254:     #get the student pick code ready
 6255:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 6256:     my $nav_error;
 6257:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
 6258:     if ($nav_error) {
 6259:         $r->print(&navmap_errormsg());
 6260:         return '';
 6261:     }
 6262:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 6263:     $r->print($result);
 6264:     
 6265:     my @validate_phases=( 'sequence',
 6266: 			  'ID',
 6267: 			  'CODE',
 6268: 			  'doublebubble',
 6269: 			  'missingbubbles');
 6270:     if (!$env{'form.validatepass'}) {
 6271: 	$env{'form.validatepass'} = 0;
 6272:     }
 6273:     my $currentphase=$env{'form.validatepass'};
 6274: 
 6275: 
 6276:     my $stop=0;
 6277:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 6278: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 6279: 	$r->rflush();
 6280: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 6281: 	{
 6282: 	    no strict 'refs';
 6283: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 6284: 	}
 6285:     }
 6286:     if (!$stop) {
 6287: 	my $warning=&scantron_warning_screen('Start Grading');
 6288: 	$r->print(&mt('Validation process complete.').'<br />'.
 6289:                   $warning.
 6290:                   &mt('Perform verification for each student after storage of submissions?').
 6291:                   '&nbsp;<span class="LC_nobreak"><label>'.
 6292:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 6293:                   ('&nbsp;'x3).'<label>'.
 6294:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 6295:                   '</label></span><br />'.
 6296:                   &mt('Grading will take longer if you use verification.').'<br />'.
 6297:                   &mt("Alternatively, the 'Review bubblesheet data' utility (see grading menu) can be used for all students after grading is complete.").'<br /><br />'.
 6298:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 6299:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 6300:     } else {
 6301: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 6302: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 6303:     }
 6304:     if ($stop) {
 6305: 	if ($validate_phases[$currentphase] eq 'sequence') {
 6306: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 6307: 	    $r->print(' '.&mt('this error').' <br />');
 6308: 
 6309: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
 6310: 	} else {
 6311:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 6312: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 6313:             } else {
 6314:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 6315:             }
 6316: 	    $r->print(' '.&mt('using corrected info').' <br />');
 6317: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 6318: 	    $r->print(" ".&mt("this scanline saving it for later."));
 6319: 	}
 6320:     }
 6321:     $r->print(" </form><br />");
 6322:     return '';
 6323: }
 6324: 
 6325: 
 6326: =pod
 6327: 
 6328: =item scantron_remove_file
 6329: 
 6330:    Removes the requested bubble sheet data file, makes sure that
 6331:    scantron_original_<filename> is never removed
 6332: 
 6333: 
 6334: =cut
 6335: 
 6336: sub scantron_remove_file {
 6337:     my ($which)=@_;
 6338:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6339:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6340:     my $file='scantron_';
 6341:     if ($which eq 'corrected' || $which eq 'skipped') {
 6342: 	$file.=$which.'_';
 6343:     } else {
 6344: 	return 'refused';
 6345:     }
 6346:     $file.=$env{'form.scantron_selectfile'};
 6347:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 6348: }
 6349: 
 6350: 
 6351: =pod
 6352: 
 6353: =item scantron_remove_scan_data
 6354: 
 6355:    Removes all scan_data correction for the requested bubble sheet
 6356:    data file.  (In the case that both the are doing skipped records we need
 6357:    to remember the old skipped lines for the time being so that element
 6358:    persists for a while.)
 6359: 
 6360: =cut
 6361: 
 6362: sub scantron_remove_scan_data {
 6363:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6364:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6365:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 6366:     my @todelete;
 6367:     my $filename=$env{'form.scantron_selectfile'};
 6368:     foreach my $key (@keys) {
 6369: 	if ($key=~/^\Q$filename\E_/) {
 6370: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 6371: 		$key=~/remember_skipping/) {
 6372: 		next;
 6373: 	    }
 6374: 	    push(@todelete,$key);
 6375: 	}
 6376:     }
 6377:     my $result;
 6378:     if (@todelete) {
 6379: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 6380: 				       \@todelete,$cdom,$cname);
 6381:     } else {
 6382: 	$result = 'ok';
 6383:     }
 6384:     return $result;
 6385: }
 6386: 
 6387: 
 6388: =pod
 6389: 
 6390: =item scantron_getfile
 6391: 
 6392:     Fetches the requested bubble sheet data file (all 3 versions), and
 6393:     the scan_data hash
 6394:   
 6395:   Arguments:
 6396:     None
 6397: 
 6398:   Returns:
 6399:     2 hash references
 6400: 
 6401:      - first one has 
 6402:          orig      -
 6403:          corrected -
 6404:          skipped   -  each of which points to an array ref of the specified
 6405:                       file broken up into individual lines
 6406:          count     - number of scanlines
 6407:  
 6408:      - second is the scan_data hash possible keys are
 6409:        ($number refers to scanline numbered $number and thus the key affects
 6410:         only that scanline
 6411:         $bubline refers to the specific bubble line element and the aspects
 6412:         refers to that specific bubble line element)
 6413: 
 6414:        $number.user - username:domain to use
 6415:        $number.CODE_ignore_dup 
 6416:                     - ignore the duplicate CODE error 
 6417:        $number.useCODE
 6418:                     - use the CODE in the scanline as is
 6419:        $number.no_bubble.$bubline
 6420:                     - it is valid that there is no bubbled in bubble
 6421:                       at $number $bubline
 6422:        remember_skipping
 6423:                     - a frozen hash containing keys of $number and values
 6424:                       of either 
 6425:                         1 - we are on a 'do skipped records pass' and plan
 6426:                             on processing this line
 6427:                         2 - we are on a 'do skipped records pass' and this
 6428:                             scanline has been marked to skip yet again
 6429: 
 6430: =cut
 6431: 
 6432: sub scantron_getfile {
 6433:     #FIXME really would prefer a scantron directory
 6434:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6435:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6436:     my $lines;
 6437:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6438: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 6439:     my %scanlines;
 6440:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 6441:     my $temp=$scanlines{'orig'};
 6442:     $scanlines{'count'}=$#$temp;
 6443: 
 6444:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6445: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 6446:     if ($lines eq '-1') {
 6447: 	$scanlines{'corrected'}=[];
 6448:     } else {
 6449: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 6450:     }
 6451:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6452: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 6453:     if ($lines eq '-1') {
 6454: 	$scanlines{'skipped'}=[];
 6455:     } else {
 6456: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 6457:     }
 6458:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 6459:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 6460:     my %scan_data = @tmp;
 6461:     return (\%scanlines,\%scan_data);
 6462: }
 6463: 
 6464: =pod
 6465: 
 6466: =item lonnet_putfile
 6467: 
 6468:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 6469: 
 6470:  Arguments:
 6471:    $contents - data to store
 6472:    $filename - filename to store $contents into
 6473: 
 6474:  Returns:
 6475:    result value from &Apache::lonnet::finishuserfileupload
 6476: 
 6477: =cut
 6478: 
 6479: sub lonnet_putfile {
 6480:     my ($contents,$filename)=@_;
 6481:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6482:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6483:     $env{'form.sillywaytopassafilearound'}=$contents;
 6484:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 6485: 
 6486: }
 6487: 
 6488: =pod
 6489: 
 6490: =item scantron_putfile
 6491: 
 6492:     Stores the current version of the bubble sheet data files, and the
 6493:     scan_data hash. (Does not modify the original version only the
 6494:     corrected and skipped versions.
 6495: 
 6496:  Arguments:
 6497:     $scanlines - hash ref that looks like the first return value from
 6498:                  &scantron_getfile()
 6499:     $scan_data - hash ref that looks like the second return value from
 6500:                  &scantron_getfile()
 6501: 
 6502: =cut
 6503: 
 6504: sub scantron_putfile {
 6505:     my ($scanlines,$scan_data) = @_;
 6506:     #FIXME really would prefer a scantron directory
 6507:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6508:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6509:     if ($scanlines) {
 6510: 	my $prefix='scantron_';
 6511: # no need to update orig, shouldn't change
 6512: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 6513: #		    $env{'form.scantron_selectfile'});
 6514: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 6515: 			$prefix.'corrected_'.
 6516: 			$env{'form.scantron_selectfile'});
 6517: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 6518: 			$prefix.'skipped_'.
 6519: 			$env{'form.scantron_selectfile'});
 6520:     }
 6521:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 6522: }
 6523: 
 6524: =pod
 6525: 
 6526: =item scantron_get_line
 6527: 
 6528:    Returns the correct version of the scanline
 6529: 
 6530:  Arguments:
 6531:     $scanlines - hash ref that looks like the first return value from
 6532:                  &scantron_getfile()
 6533:     $scan_data - hash ref that looks like the second return value from
 6534:                  &scantron_getfile()
 6535:     $i         - number of the requested line (starts at 0)
 6536: 
 6537:  Returns:
 6538:    A scanline, (either the original or the corrected one if it
 6539:    exists), or undef if the requested scanline should be
 6540:    skipped. (Either because it's an skipped scanline, or it's an
 6541:    unskipped scanline and we are not doing a 'do skipped scanlines'
 6542:    pass.
 6543: 
 6544: =cut
 6545: 
 6546: sub scantron_get_line {
 6547:     my ($scanlines,$scan_data,$i)=@_;
 6548:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 6549:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 6550:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 6551:     return $scanlines->{'orig'}[$i]; 
 6552: }
 6553: 
 6554: =pod
 6555: 
 6556: =item scantron_todo_count
 6557: 
 6558:     Counts the number of scanlines that need processing.
 6559: 
 6560:  Arguments:
 6561:     $scanlines - hash ref that looks like the first return value from
 6562:                  &scantron_getfile()
 6563:     $scan_data - hash ref that looks like the second return value from
 6564:                  &scantron_getfile()
 6565: 
 6566:  Returns:
 6567:     $count - number of scanlines to process
 6568: 
 6569: =cut
 6570: 
 6571: sub get_todo_count {
 6572:     my ($scanlines,$scan_data)=@_;
 6573:     my $count=0;
 6574:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6575: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6576: 	if ($line=~/^[\s\cz]*$/) { next; }
 6577: 	$count++;
 6578:     }
 6579:     return $count;
 6580: }
 6581: 
 6582: =pod
 6583: 
 6584: =item scantron_put_line
 6585: 
 6586:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
 6587:     data file.
 6588: 
 6589:  Arguments:
 6590:     $scanlines - hash ref that looks like the first return value from
 6591:                  &scantron_getfile()
 6592:     $scan_data - hash ref that looks like the second return value from
 6593:                  &scantron_getfile()
 6594:     $i         - line number to update
 6595:     $newline   - contents of the updated scanline
 6596:     $skip      - if true make the line for skipping and update the
 6597:                  'skipped' file
 6598: 
 6599: =cut
 6600: 
 6601: sub scantron_put_line {
 6602:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 6603:     if ($skip) {
 6604: 	$scanlines->{'skipped'}[$i]=$newline;
 6605: 	&start_skipping($scan_data,$i);
 6606: 	return;
 6607:     }
 6608:     $scanlines->{'corrected'}[$i]=$newline;
 6609: }
 6610: 
 6611: =pod
 6612: 
 6613: =item scantron_clear_skip
 6614: 
 6615:    Remove a line from the 'skipped' file
 6616: 
 6617:  Arguments:
 6618:     $scanlines - hash ref that looks like the first return value from
 6619:                  &scantron_getfile()
 6620:     $scan_data - hash ref that looks like the second return value from
 6621:                  &scantron_getfile()
 6622:     $i         - line number to update
 6623: 
 6624: =cut
 6625: 
 6626: sub scantron_clear_skip {
 6627:     my ($scanlines,$scan_data,$i)=@_;
 6628:     if (exists($scanlines->{'skipped'}[$i])) {
 6629: 	undef($scanlines->{'skipped'}[$i]);
 6630: 	return 1;
 6631:     }
 6632:     return 0;
 6633: }
 6634: 
 6635: =pod
 6636: 
 6637: =item scantron_filter_not_exam
 6638: 
 6639:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 6640:    filter out resources that are not marked as 'exam' mode
 6641: 
 6642: =cut
 6643: 
 6644: sub scantron_filter_not_exam {
 6645:     my ($curres)=@_;
 6646:     
 6647:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 6648: 	# if the user has asked to not have either hidden
 6649: 	# or 'randomout' controlled resources to be graded
 6650: 	# don't include them
 6651: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6652: 	    && $curres->randomout) {
 6653: 	    return 0;
 6654: 	}
 6655: 	return 1;
 6656:     }
 6657:     return 0;
 6658: }
 6659: 
 6660: =pod
 6661: 
 6662: =item scantron_validate_sequence
 6663: 
 6664:     Validates the selected sequence, checking for resource that are
 6665:     not set to exam mode.
 6666: 
 6667: =cut
 6668: 
 6669: sub scantron_validate_sequence {
 6670:     my ($r,$currentphase) = @_;
 6671: 
 6672:     my $navmap=Apache::lonnavmaps::navmap->new();
 6673:     unless (ref($navmap)) {
 6674:         $r->print(&navmap_errormsg());
 6675:         return (1,$currentphase);
 6676:     }
 6677:     my (undef,undef,$sequence)=
 6678: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 6679: 
 6680:     my $map=$navmap->getResourceByUrl($sequence);
 6681: 
 6682:     $r->print('<input type="hidden" name="validate_sequence_exam"
 6683:                                     value="ignore" />');
 6684:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 6685: 	my @resources=
 6686: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 6687: 	if (@resources) {
 6688: 	    $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>");
 6689: 	    return (1,$currentphase);
 6690: 	}
 6691:     }
 6692: 
 6693:     return (0,$currentphase+1);
 6694: }
 6695: 
 6696: 
 6697: 
 6698: sub scantron_validate_ID {
 6699:     my ($r,$currentphase) = @_;
 6700:     
 6701:     #get student info
 6702:     my $classlist=&Apache::loncoursedata::get_classlist();
 6703:     my %idmap=&username_to_idmap($classlist);
 6704: 
 6705:     #get scantron line setup
 6706:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6707:     my ($scanlines,$scan_data)=&scantron_getfile();
 6708: 
 6709:     my $nav_error;
 6710:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble_lines.. array.
 6711:     if ($nav_error) {
 6712:         $r->print(&navmap_errormsg());
 6713:         return(1,$currentphase);
 6714:     }
 6715: 
 6716:     my %found=('ids'=>{},'usernames'=>{});
 6717:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6718: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6719: 	if ($line=~/^[\s\cz]*$/) { next; }
 6720: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 6721: 						 $scan_data);
 6722: 	my $id=$$scan_record{'scantron.ID'};
 6723: 	my $found;
 6724: 	foreach my $checkid (keys(%idmap)) {
 6725: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 6726: 	}
 6727: 	if ($found) {
 6728: 	    my $username=$idmap{$found};
 6729: 	    if ($found{'ids'}{$found}) {
 6730: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6731: 					 $line,'duplicateID',$found);
 6732: 		return(1,$currentphase);
 6733: 	    } elsif ($found{'usernames'}{$username}) {
 6734: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6735: 					 $line,'duplicateID',$username);
 6736: 		return(1,$currentphase);
 6737: 	    }
 6738: 	    #FIXME store away line we previously saw the ID on to use above
 6739: 	    $found{'ids'}{$found}++;
 6740: 	    $found{'usernames'}{$username}++;
 6741: 	} else {
 6742: 	    if ($id =~ /^\s*$/) {
 6743: 		my $username=&scan_data($scan_data,"$i.user");
 6744: 		if (defined($username) && $found{'usernames'}{$username}) {
 6745: 		    &scantron_get_correction($r,$i,$scan_record,
 6746: 					     \%scantron_config,
 6747: 					     $line,'duplicateID',$username);
 6748: 		    return(1,$currentphase);
 6749: 		} elsif (!defined($username)) {
 6750: 		    &scantron_get_correction($r,$i,$scan_record,
 6751: 					     \%scantron_config,
 6752: 					     $line,'incorrectID');
 6753: 		    return(1,$currentphase);
 6754: 		}
 6755: 		$found{'usernames'}{$username}++;
 6756: 	    } else {
 6757: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6758: 					 $line,'incorrectID');
 6759: 		return(1,$currentphase);
 6760: 	    }
 6761: 	}
 6762:     }
 6763: 
 6764:     return (0,$currentphase+1);
 6765: }
 6766: 
 6767: 
 6768: sub scantron_get_correction {
 6769:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
 6770: #FIXME in the case of a duplicated ID the previous line, probably need
 6771: #to show both the current line and the previous one and allow skipping
 6772: #the previous one or the current one
 6773: 
 6774:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 6775: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6776: 			    " for PaperID <tt>[_1]</tt>",
 6777: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
 6778:     } else {
 6779: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6780: 			    " in scanline [_1] <pre>[_2]</pre>",
 6781: 			    $i,$line)."</p> \n");
 6782:     }
 6783:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
 6784: 			  "The name on the paper is [_2],[_3]",
 6785: 			  $$scan_record{'scantron.ID'},
 6786: 			  $$scan_record{'scantron.LastName'},
 6787: 			  $$scan_record{'scantron.FirstName'})."</p>";
 6788: 
 6789:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 6790:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 6791:                            # Array populated for doublebubble or
 6792:     my @lines_to_correct;  # missingbubble errors to build javascript
 6793:                            # to validate radio button checking   
 6794: 
 6795:     if ($error =~ /ID$/) {
 6796: 	if ($error eq 'incorrectID') {
 6797: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
 6798: 		      "</p>\n");
 6799: 	} elsif ($error eq 'duplicateID') {
 6800: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 6801: 	}
 6802: 	$r->print($message);
 6803: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6804: 	$r->print("\n<ul><li> ");
 6805: 	#FIXME it would be nice if this sent back the user ID and
 6806: 	#could do partial userID matches
 6807: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 6808: 				       'scantron_username','scantron_domain'));
 6809: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 6810: 	$r->print("\n@".
 6811: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 6812: 
 6813: 	$r->print('</li>');
 6814:     } elsif ($error =~ /CODE$/) {
 6815: 	if ($error eq 'incorrectCODE') {
 6816: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 6817: 	} elsif ($error eq 'duplicateCODE') {
 6818: 	    $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");
 6819: 	}
 6820: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
 6821: 			    $$scan_record{'scantron.CODE'})."<br />\n");
 6822: 	$r->print($message);
 6823: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6824: 	$r->print("\n<br /> ");
 6825: 	my $i=0;
 6826: 	if ($error eq 'incorrectCODE' 
 6827: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 6828: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 6829: 	    if ($closest > 0) {
 6830: 		foreach my $testcode (@{$closest}) {
 6831: 		    my $checked='';
 6832: 		    if (!$i) { $checked=' checked="checked"'; }
 6833: 		    $r->print("
 6834:    <label>
 6835:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
 6836:        ".&mt("Use the similar CODE [_1] instead.",
 6837: 	    "<b><tt>".$testcode."</tt></b>")."
 6838:     </label>
 6839:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 6840: 		    $r->print("\n<br />");
 6841: 		    $i++;
 6842: 		}
 6843: 	    }
 6844: 	}
 6845: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 6846: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
 6847: 	    $r->print("
 6848:     <label>
 6849:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
 6850:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
 6851: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 6852:     </label>");
 6853: 	    $r->print("\n<br />");
 6854: 	}
 6855: 
 6856: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
 6857: function change_radio(field) {
 6858:     var slct=document.scantronupload.scantron_CODE_resolution;
 6859:     var i;
 6860:     for (i=0;i<slct.length;i++) {
 6861:         if (slct[i].value==field) { slct[i].checked=true; }
 6862:     }
 6863: }
 6864: ENDSCRIPT
 6865: 	my $href="/adm/pickcode?".
 6866: 	   "form=".&escape("scantronupload").
 6867: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 6868: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 6869: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 6870: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 6871: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 6872: 	    $r->print("
 6873:     <label>
 6874:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 6875:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 6876: 	     "<a target='_blank' href='$href'>","</a>")."
 6877:     </label> 
 6878:     ".&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\')" />'));
 6879: 	    $r->print("\n<br />");
 6880: 	}
 6881: 	$r->print("
 6882:     <label>
 6883:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 6884:        ".&mt("Use [_1] as the CODE.",
 6885: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 6886: 	$r->print("\n<br /><br />");
 6887:     } elsif ($error eq 'doublebubble') {
 6888: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 6889: 
 6890: 	# The form field scantron_questions is acutally a list of line numbers.
 6891: 	# represented by this form so:
 6892: 
 6893: 	my $line_list = &questions_to_line_list($arg);
 6894: 
 6895: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 6896: 		  $line_list.'" />');
 6897: 	$r->print($message);
 6898: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 6899: 	foreach my $question (@{$arg}) {
 6900: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 6901:                                                    $scan_record, $error);
 6902:             push(@lines_to_correct,@linenums);
 6903: 	}
 6904:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 6905:     } elsif ($error eq 'missingbubble') {
 6906: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
 6907: 	$r->print($message);
 6908: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 6909: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 6910: 
 6911: 	# The form field scantron_questions is actually a list of line numbers not
 6912: 	# a list of question numbers. Therefore:
 6913: 	#
 6914: 	
 6915: 	my $line_list = &questions_to_line_list($arg);
 6916: 
 6917: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 6918: 		  $line_list.'" />');
 6919: 	foreach my $question (@{$arg}) {
 6920: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 6921:                                                    $scan_record, $error);
 6922:             push(@lines_to_correct,@linenums);
 6923: 	}
 6924:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 6925:     } else {
 6926: 	$r->print("\n<ul>");
 6927:     }
 6928:     $r->print("\n</li></ul>");
 6929: }
 6930: 
 6931: sub verify_bubbles_checked {
 6932:     my (@ansnums) = @_;
 6933:     my $ansnumstr = join('","',@ansnums);
 6934:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 6935:     my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
 6936: function verify_bubble_radio(form) {
 6937:     var ansnumArray = new Array ("$ansnumstr");
 6938:     var need_bubble_count = 0;
 6939:     for (var i=0; i<ansnumArray.length; i++) {
 6940:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 6941:             var bubble_picked = 0; 
 6942:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 6943:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 6944:                     bubble_picked = 1;
 6945:                 }
 6946:             }
 6947:             if (bubble_picked == 0) {
 6948:                 need_bubble_count ++;
 6949:             }
 6950:         }
 6951:     }
 6952:     if (need_bubble_count) {
 6953:         alert("$warning");
 6954:         return;
 6955:     }
 6956:     form.submit(); 
 6957: }
 6958: ENDSCRIPT
 6959:     return $output;
 6960: }
 6961: 
 6962: =pod
 6963: 
 6964: =item  questions_to_line_list
 6965: 
 6966: Converts a list of questions into a string of comma separated
 6967: line numbers in the answer sheet used by the questions.  This is
 6968: used to fill in the scantron_questions form field.
 6969: 
 6970:   Arguments:
 6971:      questions    - Reference to an array of questions.
 6972: 
 6973: =cut
 6974: 
 6975: 
 6976: sub questions_to_line_list {
 6977:     my ($questions) = @_;
 6978:     my @lines;
 6979: 
 6980:     foreach my $item (@{$questions}) {
 6981:         my $question = $item;
 6982:         my ($first,$count,$last);
 6983:         if ($item =~ /^(\d+)\.(\d+)$/) {
 6984:             $question = $1;
 6985:             my $subquestion = $2;
 6986:             $first = $first_bubble_line{$question-1} + 1;
 6987:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 6988:             my $subcount = 1;
 6989:             while ($subcount<$subquestion) {
 6990:                 $first += $subans[$subcount-1];
 6991:                 $subcount ++;
 6992:             }
 6993:             $count = $subans[$subquestion-1];
 6994:         } else {
 6995: 	    $first   = $first_bubble_line{$question-1} + 1;
 6996: 	    $count   = $bubble_lines_per_response{$question-1};
 6997:         }
 6998:         $last = $first+$count-1;
 6999:         push(@lines, ($first..$last));
 7000:     }
 7001:     return join(',', @lines);
 7002: }
 7003: 
 7004: =pod 
 7005: 
 7006: =item prompt_for_corrections
 7007: 
 7008: Prompts for a potentially multiline correction to the
 7009: user's bubbling (factors out common code from scantron_get_correction
 7010: for multi and missing bubble cases).
 7011: 
 7012:  Arguments:
 7013:    $r           - Apache request object.
 7014:    $question    - The question number to prompt for.
 7015:    $scan_config - The scantron file configuration hash.
 7016:    $scan_record - Reference to the hash that has the the parsed scanlines.
 7017:    $error       - Type of error
 7018: 
 7019:  Implicit inputs:
 7020:    %bubble_lines_per_response   - Starting line numbers for each question.
 7021:                                   Numbered from 0 (but question numbers are from
 7022:                                   1.
 7023:    %first_bubble_line           - Starting bubble line for each question.
 7024:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 7025:                                   type problems render as separate sub-questions, 
 7026:                                   in exam mode. This hash contains a 
 7027:                                   comma-separated list of the lines per 
 7028:                                   sub-question.
 7029:    %responsetype_per_response   - essayresponse, formularesponse,
 7030:                                   stringresponse, imageresponse, reactionresponse,
 7031:                                   and organicresponse type problem parts can have
 7032:                                   multiple lines per response if the weight
 7033:                                   assigned exceeds 10.  In this case, only
 7034:                                   one bubble per line is permitted, but more 
 7035:                                   than one line might contain bubbles, e.g.
 7036:                                   bubbling of: line 1 - J, line 2 - J, 
 7037:                                   line 3 - B would assign 22 points.  
 7038: 
 7039: =cut
 7040: 
 7041: sub prompt_for_corrections {
 7042:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
 7043:     my ($current_line,$lines);
 7044:     my @linenums;
 7045:     my $questionnum = $question;
 7046:     if ($question =~ /^(\d+)\.(\d+)$/) {
 7047:         $question = $1;
 7048:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7049:         my $subquestion = $2;
 7050:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7051:         my $subcount = 1;
 7052:         while ($subcount<$subquestion) {
 7053:             $current_line += $subans[$subcount-1];
 7054:             $subcount ++;
 7055:         }
 7056:         $lines = $subans[$subquestion-1];
 7057:     } else {
 7058:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7059:         $lines        = $bubble_lines_per_response{$question-1};
 7060:     }
 7061:     if ($lines > 1) {
 7062:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 7063:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
 7064:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
 7065:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
 7066:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
 7067:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
 7068:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
 7069:             $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 />');
 7070:         } else {
 7071:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 7072:         }
 7073:     }
 7074:     for (my $i =0; $i < $lines; $i++) {
 7075:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 7076: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
 7077: 	        		  $questionnum,$error,split('', $selected));
 7078:         push(@linenums,$current_line);
 7079: 	$current_line++;
 7080:     }
 7081:     if ($lines > 1) {
 7082: 	$r->print("<hr /><br />");
 7083:     }
 7084:     return @linenums;
 7085: }
 7086: 
 7087: =pod
 7088: 
 7089: =item scantron_bubble_selector
 7090:   
 7091:    Generates the html radiobuttons to correct a single bubble line
 7092:    possibly showing the existing the selected bubbles if known
 7093: 
 7094:  Arguments:
 7095:     $r           - Apache request object
 7096:     $scan_config - hash from &get_scantron_config()
 7097:     $line        - Number of the line being displayed.
 7098:     $questionnum - Question number (may include subquestion)
 7099:     $error       - Type of error.
 7100:     @selected    - Array of bubbles picked on this line.
 7101: 
 7102: =cut
 7103: 
 7104: sub scantron_bubble_selector {
 7105:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 7106:     my $max=$$scan_config{'Qlength'};
 7107: 
 7108:     my $scmode=$$scan_config{'Qon'};
 7109:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
 7110: 
 7111:     my @alphabet=('A'..'Z');
 7112:     $r->print(&Apache::loncommon::start_data_table().
 7113:               &Apache::loncommon::start_data_table_row());
 7114:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 7115:     for (my $i=0;$i<$max+1;$i++) {
 7116: 	$r->print("\n".'<td align="center">');
 7117: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 7118: 	else { $r->print('&nbsp;'); }
 7119: 	$r->print('</td>');
 7120:     }
 7121:     $r->print(&Apache::loncommon::end_data_table_row().
 7122:               &Apache::loncommon::start_data_table_row());
 7123:     for (my $i=0;$i<$max;$i++) {
 7124: 	$r->print("\n".
 7125: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 7126: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 7127:     }
 7128:     my $nobub_checked = ' ';
 7129:     if ($error eq 'missingbubble') {
 7130:         $nobub_checked = ' checked = "checked" ';
 7131:     }
 7132:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 7133: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 7134:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 7135:               $line.'" value="'.$questionnum.'" /></td>');
 7136:     $r->print(&Apache::loncommon::end_data_table_row().
 7137:               &Apache::loncommon::end_data_table());
 7138: }
 7139: 
 7140: =pod
 7141: 
 7142: =item num_matches
 7143: 
 7144:    Counts the number of characters that are the same between the two arguments.
 7145: 
 7146:  Arguments:
 7147:    $orig - CODE from the scanline
 7148:    $code - CODE to match against
 7149: 
 7150:  Returns:
 7151:    $count - integer count of the number of same characters between the
 7152:             two arguments
 7153: 
 7154: =cut
 7155: 
 7156: sub num_matches {
 7157:     my ($orig,$code) = @_;
 7158:     my @code=split(//,$code);
 7159:     my @orig=split(//,$orig);
 7160:     my $same=0;
 7161:     for (my $i=0;$i<scalar(@code);$i++) {
 7162: 	if ($code[$i] eq $orig[$i]) { $same++; }
 7163:     }
 7164:     return $same;
 7165: }
 7166: 
 7167: =pod
 7168: 
 7169: =item scantron_get_closely_matching_CODEs
 7170: 
 7171:    Cycles through all CODEs and finds the set that has the greatest
 7172:    number of same characters as the provided CODE
 7173: 
 7174:  Arguments:
 7175:    $allcodes - hash ref returned by &get_codes()
 7176:    $CODE     - CODE from the current scanline
 7177: 
 7178:  Returns:
 7179:    2 element list
 7180:     - first elements is number of how closely matching the best fit is 
 7181:       (5 means best set has 5 matching characters)
 7182:     - second element is an arrary ref containing the set of valid CODEs
 7183:       that best fit the passed in CODE
 7184: 
 7185: =cut
 7186: 
 7187: sub scantron_get_closely_matching_CODEs {
 7188:     my ($allcodes,$CODE)=@_;
 7189:     my @CODEs;
 7190:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 7191: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 7192:     }
 7193: 
 7194:     return ($#CODEs,$CODEs[-1]);
 7195: }
 7196: 
 7197: =pod
 7198: 
 7199: =item get_codes
 7200: 
 7201:    Builds a hash which has keys of all of the valid CODEs from the selected
 7202:    set of remembered CODEs.
 7203: 
 7204:  Arguments:
 7205:   $old_name - name of the set of remembered CODEs
 7206:   $cdom     - domain of the course
 7207:   $cnum     - internal course name
 7208: 
 7209:  Returns:
 7210:   %allcodes - keys are the valid CODEs, values are all 1
 7211: 
 7212: =cut
 7213: 
 7214: sub get_codes {
 7215:     my ($old_name, $cdom, $cnum) = @_;
 7216:     if (!$old_name) {
 7217: 	$old_name=$env{'form.scantron_CODElist'};
 7218:     }
 7219:     if (!$cdom) {
 7220: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 7221:     }
 7222:     if (!$cnum) {
 7223: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 7224:     }
 7225:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 7226: 				    $cdom,$cnum);
 7227:     my %allcodes;
 7228:     if ($result{"type\0$old_name"} eq 'number') {
 7229: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 7230:     } else {
 7231: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 7232:     }
 7233:     return %allcodes;
 7234: }
 7235: 
 7236: =pod
 7237: 
 7238: =item scantron_validate_CODE
 7239: 
 7240:    Validates all scanlines in the selected file to not have any
 7241:    invalid or underspecified CODEs and that none of the codes are
 7242:    duplicated if this was requested.
 7243: 
 7244: =cut
 7245: 
 7246: sub scantron_validate_CODE {
 7247:     my ($r,$currentphase) = @_;
 7248:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7249:     if ($scantron_config{'CODElocation'} &&
 7250: 	$scantron_config{'CODEstart'} &&
 7251: 	$scantron_config{'CODElength'}) {
 7252: 	if (!defined($env{'form.scantron_CODElist'})) {
 7253: 	    &FIXME_blow_up()
 7254: 	}
 7255:     } else {
 7256: 	return (0,$currentphase+1);
 7257:     }
 7258:     
 7259:     my %usedCODEs;
 7260: 
 7261:     my %allcodes=&get_codes();
 7262: 
 7263:     my $nav_error;
 7264:     &scantron_get_maxbubble(\$nav_error); # parse needs the lines per response array.
 7265:     if ($nav_error) {
 7266:         $r->print(&navmap_errormsg());
 7267:         return(1,$currentphase);
 7268:     }
 7269: 
 7270:     my ($scanlines,$scan_data)=&scantron_getfile();
 7271:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7272: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7273: 	if ($line=~/^[\s\cz]*$/) { next; }
 7274: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7275: 						 $scan_data);
 7276: 	my $CODE=$$scan_record{'scantron.CODE'};
 7277: 	my $error=0;
 7278: 	if (!&Apache::lonnet::validCODE($CODE)) {
 7279: 	    &scantron_get_correction($r,$i,$scan_record,
 7280: 				     \%scantron_config,
 7281: 				     $line,'incorrectCODE',\%allcodes);
 7282: 	    return(1,$currentphase);
 7283: 	}
 7284: 	if (%allcodes && !exists($allcodes{$CODE}) 
 7285: 	    && !$$scan_record{'scantron.useCODE'}) {
 7286: 	    &scantron_get_correction($r,$i,$scan_record,
 7287: 				     \%scantron_config,
 7288: 				     $line,'incorrectCODE',\%allcodes);
 7289: 	    return(1,$currentphase);
 7290: 	}
 7291: 	if (exists($usedCODEs{$CODE}) 
 7292: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 7293: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 7294: 	    &scantron_get_correction($r,$i,$scan_record,
 7295: 				     \%scantron_config,
 7296: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 7297: 	    return(1,$currentphase);
 7298: 	}
 7299: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 7300:     }
 7301:     return (0,$currentphase+1);
 7302: }
 7303: 
 7304: =pod
 7305: 
 7306: =item scantron_validate_doublebubble
 7307: 
 7308:    Validates all scanlines in the selected file to not have any
 7309:    bubble lines with multiple bubbles marked.
 7310: 
 7311: =cut
 7312: 
 7313: sub scantron_validate_doublebubble {
 7314:     my ($r,$currentphase) = @_;
 7315:     #get student info
 7316:     my $classlist=&Apache::loncoursedata::get_classlist();
 7317:     my %idmap=&username_to_idmap($classlist);
 7318: 
 7319:     #get scantron line setup
 7320:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7321:     my ($scanlines,$scan_data)=&scantron_getfile();
 7322:     my $nav_error;
 7323:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble line array.
 7324:     if ($nav_error) {
 7325:         $r->print(&navmap_errormsg());
 7326:         return(1,$currentphase);
 7327:     }
 7328: 
 7329:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7330: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7331: 	if ($line=~/^[\s\cz]*$/) { next; }
 7332: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7333: 						 $scan_data);
 7334: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 7335: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 7336: 				 'doublebubble',
 7337: 				 $$scan_record{'scantron.doubleerror'});
 7338:     	return (1,$currentphase);
 7339:     }
 7340:     return (0,$currentphase+1);
 7341: }
 7342: 
 7343: 
 7344: sub scantron_get_maxbubble {
 7345:     my ($nav_error) = @_;
 7346:     if (defined($env{'form.scantron_maxbubble'}) &&
 7347: 	$env{'form.scantron_maxbubble'}) {
 7348: 	&restore_bubble_lines();
 7349: 	return $env{'form.scantron_maxbubble'};
 7350:     }
 7351: 
 7352:     my (undef, undef, $sequence) =
 7353: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7354: 
 7355:     my $navmap=Apache::lonnavmaps::navmap->new();
 7356:     unless (ref($navmap)) {
 7357:         if (ref($nav_error)) {
 7358:             $$nav_error = 1;
 7359:         }
 7360:         return;
 7361:     }
 7362:     my $map=$navmap->getResourceByUrl($sequence);
 7363:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7364: 
 7365:     &Apache::lonxml::clear_problem_counter();
 7366: 
 7367:     my $uname       = $env{'user.name'};
 7368:     my $udom        = $env{'user.domain'};
 7369:     my $cid         = $env{'request.course.id'};
 7370:     my $total_lines = 0;
 7371:     %bubble_lines_per_response = ();
 7372:     %first_bubble_line         = ();
 7373:     %subdivided_bubble_lines   = ();
 7374:     %responsetype_per_response = ();
 7375: 
 7376:     my $response_number = 0;
 7377:     my $bubble_line     = 0;
 7378:     foreach my $resource (@resources) {
 7379:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom);
 7380:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 7381: 	    foreach my $part_id (@{$parts}) {
 7382:                 my $lines;
 7383: 
 7384: 	        # TODO - make this a persistent hash not an array.
 7385: 
 7386:                 # optionresponse, matchresponse and rankresponse type items 
 7387:                 # render as separate sub-questions in exam mode.
 7388:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 7389:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 7390:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 7391:                     my ($numbub,$numshown);
 7392:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 7393:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 7394:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 7395:                         }
 7396:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 7397:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 7398:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 7399:                         }
 7400:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 7401:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 7402:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 7403:                         }
 7404:                     }
 7405:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 7406:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 7407:                     }
 7408:                     my $bubbles_per_line = 10;
 7409:                     my $inner_bubble_lines = int($numbub/$bubbles_per_line);
 7410:                     if (($numbub % $bubbles_per_line) != 0) {
 7411:                         $inner_bubble_lines++;
 7412:                     }
 7413:                     for (my $i=0; $i<$numshown; $i++) {
 7414:                         $subdivided_bubble_lines{$response_number} .= 
 7415:                             $inner_bubble_lines.',';
 7416:                     }
 7417:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 7418:                     $lines = $numshown * $inner_bubble_lines;
 7419:                 } else {
 7420:                     $lines = $analysis->{"$part_id.bubble_lines"};
 7421:                 } 
 7422: 
 7423:                 $first_bubble_line{$response_number} = $bubble_line;
 7424: 	        $bubble_lines_per_response{$response_number} = $lines;
 7425:                 $responsetype_per_response{$response_number} = 
 7426:                     $analysis->{$part_id.'.type'};
 7427: 	        $response_number++;
 7428: 
 7429: 	        $bubble_line +=  $lines;
 7430: 	        $total_lines +=  $lines;
 7431: 	    }
 7432:         }
 7433:     }
 7434:     &Apache::lonnet::delenv('scantron.');
 7435: 
 7436:     &save_bubble_lines();
 7437:     $env{'form.scantron_maxbubble'} =
 7438: 	$total_lines;
 7439:     return $env{'form.scantron_maxbubble'};
 7440: }
 7441: 
 7442: sub scantron_validate_missingbubbles {
 7443:     my ($r,$currentphase) = @_;
 7444:     #get student info
 7445:     my $classlist=&Apache::loncoursedata::get_classlist();
 7446:     my %idmap=&username_to_idmap($classlist);
 7447: 
 7448:     #get scantron line setup
 7449:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7450:     my ($scanlines,$scan_data)=&scantron_getfile();
 7451:     my $nav_error;
 7452:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
 7453:     if ($nav_error) {
 7454:         return(1,$currentphase);
 7455:     }
 7456:     if (!$max_bubble) { $max_bubble=2**31; }
 7457:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7458: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7459: 	if ($line=~/^[\s\cz]*$/) { next; }
 7460: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7461: 						 $scan_data);
 7462: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 7463: 	my @to_correct;
 7464: 	
 7465: 	# Probably here's where the error is...
 7466: 
 7467: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 7468:             my $lastbubble;
 7469:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 7470:                my $question = $1;
 7471:                my $subquestion = $2;
 7472:                if (!defined($first_bubble_line{$question -1})) { next; }
 7473:                my $first = $first_bubble_line{$question-1};
 7474:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7475:                my $subcount = 1;
 7476:                while ($subcount<$subquestion) {
 7477:                    $first += $subans[$subcount-1];
 7478:                    $subcount ++;
 7479:                }
 7480:                my $count = $subans[$subquestion-1];
 7481:                $lastbubble = $first + $count;
 7482:             } else {
 7483:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
 7484:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
 7485:             }
 7486:             if ($lastbubble > $max_bubble) { next; }
 7487: 	    push(@to_correct,$missing);
 7488: 	}
 7489: 	if (@to_correct) {
 7490: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7491: 				     $line,'missingbubble',\@to_correct);
 7492: 	    return (1,$currentphase);
 7493: 	}
 7494: 
 7495:     }
 7496:     return (0,$currentphase+1);
 7497: }
 7498: 
 7499: 
 7500: sub scantron_process_students {
 7501:     my ($r,$symb) = @_;
 7502: 
 7503:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7504:     if (!$symb) {
 7505: 	return '';
 7506:     }
 7507:     my $default_form_data=&defaultFormData($symb);
 7508: 
 7509:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7510:     my ($scanlines,$scan_data)=&scantron_getfile();
 7511:     my $classlist=&Apache::loncoursedata::get_classlist();
 7512:     my %idmap=&username_to_idmap($classlist);
 7513:     my $navmap=Apache::lonnavmaps::navmap->new();
 7514:     unless (ref($navmap)) {
 7515:         $r->print(&navmap_errormsg());
 7516:         return '';
 7517:     }  
 7518:     my $map=$navmap->getResourceByUrl($sequence);
 7519:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7520:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
 7521:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 7522:                             \%grader_randomlists_by_symb);
 7523:     my $resource_error;
 7524:     foreach my $resource (@resources) {
 7525:         my $ressymb;
 7526:         if (ref($resource)) {
 7527:             $ressymb = $resource->symb();
 7528:         } else {
 7529:             $resource_error = 1;
 7530:             last;
 7531:         }
 7532:         my ($analysis,$parts) =
 7533:             &scantron_partids_tograde($resource,$env{'request.course.id'},
 7534:                                       $env{'user.name'},$env{'user.domain'},1);
 7535:         $grader_partids_by_symb{$ressymb} = $parts;
 7536:         if (ref($analysis) eq 'HASH') {
 7537:             if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 7538:                 $grader_randomlists_by_symb{$ressymb} = 
 7539:                     $analysis->{'parts_withrandomlist'};
 7540:             }
 7541:         }
 7542:     }
 7543:     if ($resource_error) {
 7544:         $r->print(&navmap_errormsg());
 7545:         return '';
 7546:     }
 7547: 
 7548:     my ($uname,$udom);
 7549:     my $result= <<SCANTRONFORM;
 7550: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 7551:   <input type="hidden" name="command" value="scantron_configphase" />
 7552:   $default_form_data
 7553: SCANTRONFORM
 7554:     $r->print($result);
 7555: 
 7556:     my @delayqueue;
 7557:     my (%completedstudents,%scandata);
 7558:     
 7559:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 7560:     my $count=&get_todo_count($scanlines,$scan_data);
 7561:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet Status',
 7562:  				    'Bubblesheet Progress',$count,
 7563: 				    'inline',undef,'scantronupload');
 7564:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 7565: 					  'Processing first student');
 7566:     $r->print('<br />');
 7567:     my $start=&Time::HiRes::time();
 7568:     my $i=-1;
 7569:     my $started;
 7570: 
 7571:     my $nav_error;
 7572:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
 7573:     if ($nav_error) {
 7574:         $r->print(&navmap_errormsg());
 7575:         return '';
 7576:     }
 7577: 
 7578:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 7579:     # the user and return.
 7580: 
 7581:     if ($ssi_error) {
 7582: 	$r->print("</form>");
 7583: 	&ssi_print_error($r);
 7584:         &Apache::lonnet::remove_lock($lock);
 7585: 	return '';		# Dunno why the other returns return '' rather than just returning.
 7586:     }
 7587: 
 7588:     my %lettdig = &letter_to_digits();
 7589:     my $numletts = scalar(keys(%lettdig));
 7590: 
 7591:     while ($i<$scanlines->{'count'}) {
 7592:  	($uname,$udom)=('','');
 7593:  	$i++;
 7594:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7595:  	if ($line=~/^[\s\cz]*$/) { next; }
 7596: 	if ($started) {
 7597: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 7598: 						     'last student');
 7599: 	}
 7600: 	$started=1;
 7601:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7602:  						 $scan_data);
 7603:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 7604:  					      \%idmap,$i)) {
 7605:   	    &scantron_add_delay(\@delayqueue,$line,
 7606:  				'Unable to find a student that matches',1);
 7607:  	    next;
 7608:   	}
 7609:  	if (exists $completedstudents{$uname}) {
 7610:  	    &scantron_add_delay(\@delayqueue,$line,
 7611:  				'Student '.$uname.' has multiple sheets',2);
 7612:  	    next;
 7613:  	}
 7614:   	($uname,$udom)=split(/:/,$uname);
 7615: 
 7616:         my (%partids_by_symb,$res_error);
 7617:         foreach my $resource (@resources) {
 7618:             my $ressymb;
 7619:             if (ref($resource)) {
 7620:                 $ressymb = $resource->symb();
 7621:             } else {
 7622:                 $res_error = 1;
 7623:                 last;
 7624:             }
 7625:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 7626:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 7627:                 my ($analysis,$parts) =
 7628:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom);
 7629:                 $partids_by_symb{$ressymb} = $parts;
 7630:             } else {
 7631:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
 7632:             }
 7633:         }
 7634: 
 7635:         if ($res_error) {
 7636:             &scantron_add_delay(\@delayqueue,$line,
 7637:                                 'An error occurred while grading student '.$uname,2);
 7638:             next;
 7639:         }
 7640: 
 7641: 	&Apache::lonxml::clear_problem_counter();
 7642:   	&Apache::lonnet::appenv($scan_record);
 7643: 
 7644: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 7645: 	    &scantron_putfile($scanlines,$scan_data);
 7646: 	}
 7647: 	
 7648:         my $scancode;
 7649:         if ((exists($scan_record->{'scantron.CODE'})) &&
 7650:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 7651:             $scancode = $scan_record->{'scantron.CODE'};
 7652:         } else {
 7653:             $scancode = '';
 7654:         }
 7655: 
 7656:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 7657:                                    \@resources,\%partids_by_symb) eq 'ssi_error') {
 7658:             $ssi_error = 0; # So end of handler error message does not trigger.
 7659:             $r->print("</form>");
 7660:             &ssi_print_error($r);
 7661:             &Apache::lonnet::remove_lock($lock);
 7662:             return '';      # Why return ''?  Beats me.
 7663:         }
 7664: 
 7665: 	$completedstudents{$uname}={'line'=>$line};
 7666:         if ($env{'form.verifyrecord'}) {
 7667:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 7668:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 7669:             chomp($studentdata);
 7670:             $studentdata =~ s/\r$//;
 7671:             my $studentrecord = '';
 7672:             my $counter = -1;
 7673:             foreach my $resource (@resources) {
 7674:                 my $ressymb = $resource->symb();
 7675:                 ($counter,my $recording) =
 7676:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 7677:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
 7678:                                              \%scantron_config,\%lettdig,$numletts);
 7679:                 $studentrecord .= $recording;
 7680:             }
 7681:             if ($studentrecord ne $studentdata) {
 7682:                 &Apache::lonxml::clear_problem_counter();
 7683:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 7684:                                            \@resources,\%partids_by_symb) eq 'ssi_error') {
 7685:                     $ssi_error = 0; # So end of handler error message does not trigger.
 7686:                     $r->print("</form>");
 7687:                     &ssi_print_error($r);
 7688:                     &Apache::lonnet::remove_lock($lock);
 7689:                     delete($completedstudents{$uname});
 7690:                     return '';
 7691:                 }
 7692:                 $counter = -1;
 7693:                 $studentrecord = '';
 7694:                 foreach my $resource (@resources) {
 7695:                     my $ressymb = $resource->symb();
 7696:                     ($counter,my $recording) =
 7697:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 7698:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 7699:                                                  \%scantron_config,\%lettdig,$numletts);
 7700:                     $studentrecord .= $recording;
 7701:                 }
 7702:                 if ($studentrecord ne $studentdata) {
 7703:                     $r->print('<p><span class="LC_error">');
 7704:                     if ($scancode eq '') {
 7705:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2].',
 7706:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 7707:                     } else {
 7708:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2] and CODE: [_3].',
 7709:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 7710:                     }
 7711:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 7712:                               &Apache::loncommon::start_data_table_header_row()."\n".
 7713:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 7714:                               &Apache::loncommon::end_data_table_header_row()."\n".
 7715:                               &Apache::loncommon::start_data_table_row().
 7716:                               '<td>'.&mt('Bubble Sheet').'</td>'.
 7717:                               '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
 7718:                               &Apache::loncommon::end_data_table_row().
 7719:                               &Apache::loncommon::start_data_table_row().
 7720:                               '<td>Stored submissions</td>'.
 7721:                               '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
 7722:                               &Apache::loncommon::end_data_table_row().
 7723:                               &Apache::loncommon::end_data_table().'</p>');
 7724:                 } else {
 7725:                     $r->print('<br /><span class="LC_warning">'.
 7726:                              &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 />'.
 7727:                              &mt("As a consequence, this user's submission history records two tries.").
 7728:                                  '</span><br />');
 7729:                 }
 7730:             }
 7731:         }
 7732:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 7733:     } continue {
 7734: 	&Apache::lonxml::clear_problem_counter();
 7735: 	&Apache::lonnet::delenv('scantron.');
 7736:     }
 7737:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 7738:     &Apache::lonnet::remove_lock($lock);
 7739: #    my $lasttime = &Time::HiRes::time()-$start;
 7740: #    $r->print("<p>took $lasttime</p>");
 7741: 
 7742:     $r->print("</form>");
 7743:     return '';
 7744: }
 7745: 
 7746: sub graders_resources_pass {
 7747:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb) = @_;
 7748:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
 7749:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
 7750:         foreach my $resource (@{$resources}) {
 7751:             my $ressymb = $resource->symb();
 7752:             my ($analysis,$parts) =
 7753:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
 7754:                                           $env{'user.name'},$env{'user.domain'},1);
 7755:             $grader_partids_by_symb->{$ressymb} = $parts;
 7756:             if (ref($analysis) eq 'HASH') {
 7757:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 7758:                     $grader_randomlists_by_symb->{$ressymb} =
 7759:                         $analysis->{'parts_withrandomlist'};
 7760:                 }
 7761:             }
 7762:         }
 7763:     }
 7764:     return;
 7765: }
 7766: 
 7767: sub grade_student_bubbles {
 7768:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts) = @_;
 7769:     if (ref($resources) eq 'ARRAY') {
 7770:         my $count = 0;
 7771:         foreach my $resource (@{$resources}) {
 7772:             my $ressymb = $resource->symb();
 7773:             my %form = ('submitted'      => 'scantron',
 7774:                         'grade_target'   => 'grade',
 7775:                         'grade_username' => $uname,
 7776:                         'grade_domain'   => $udom,
 7777:                         'grade_courseid' => $env{'request.course.id'},
 7778:                         'grade_symb'     => $ressymb,
 7779:                         'CODE'           => $scancode
 7780:                        );
 7781:             if (ref($parts) eq 'HASH') {
 7782:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 7783:                     foreach my $part (@{$parts->{$ressymb}}) {
 7784:                         $form{'scantron_questnum_start.'.$part} =
 7785:                             1+$env{'form.scantron.first_bubble_line.'.$count};
 7786:                         $count++;
 7787:                     }
 7788:                 }
 7789:             }
 7790:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 7791:             return 'ssi_error' if ($ssi_error);
 7792:             last if (&Apache::loncommon::connection_aborted($r));
 7793:         }
 7794:     }
 7795:     return;
 7796: }
 7797: 
 7798: sub scantron_upload_scantron_data {
 7799:     my ($r,$symb)=@_;
 7800:     my $dom = $env{'request.role.domain'};
 7801:     my $domdesc = &Apache::lonnet::domain($dom,'description');
 7802:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
 7803:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 7804: 							  'domainid',
 7805: 							  'coursename',$dom);
 7806:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
 7807:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
 7808:     my $default_form_data=&defaultFormData($symb);
 7809:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
 7810:     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.");
 7811:     $r->print(&Apache::lonhtmlcommon::scripttag('
 7812:     function checkUpload(formname) {
 7813: 	if (formname.upfile.value == "") {
 7814: 	    alert("'.$nofile_alert.'");
 7815: 	    return false;
 7816: 	}
 7817:         if (formname.courseid.value == "") {
 7818:             alert("'.$nocourseid_alert.'");
 7819:             return false;
 7820:         }
 7821: 	formname.submit();
 7822:     }
 7823: 
 7824:     function ToSyllabus() {
 7825:         var cdom = '."'$dom'".';
 7826:         var cnum = document.rules.courseid.value;
 7827:         if (cdom == "" || cdom == null) {
 7828:             return;
 7829:         }
 7830:         if (cnum == "" || cnum == null) {
 7831:            return;
 7832:         }
 7833:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
 7834:                             "height=350,width=350,scrollbars=yes,menubar=no");
 7835:         return;
 7836:     }
 7837: 
 7838: '));
 7839:     $r->print('
 7840: <h3>'.&mt('Send scanned bubblesheet data to a course').'</h3>
 7841: 
 7842: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 7843: '.$default_form_data.
 7844:   &Apache::lonhtmlcommon::start_pick_box().
 7845:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
 7846:   '<input name="courseid" type="text" size="30" />'.$select_link.
 7847:   &Apache::lonhtmlcommon::row_closure().
 7848:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
 7849:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
 7850:   &Apache::lonhtmlcommon::row_closure().
 7851:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
 7852:   '<input name="domainid" type="hidden" />'.$domdesc.
 7853:   &Apache::lonhtmlcommon::row_closure().
 7854:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
 7855:   '<input type="file" name="upfile" size="50" />'.
 7856:   &Apache::lonhtmlcommon::row_closure(1).
 7857:   &Apache::lonhtmlcommon::end_pick_box().'<br />
 7858: 
 7859: <input name="command" value="scantronupload_save" type="hidden" />
 7860: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 7861: </form>
 7862: ');
 7863:     return '';
 7864: }
 7865: 
 7866: 
 7867: sub scantron_upload_scantron_data_save {
 7868:     my($r,$symb)=@_;
 7869:     my $doanotherupload=
 7870: 	'<br /><form action="/adm/grades" method="post">'."\n".
 7871: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 7872: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 7873: 	'</form>'."\n";
 7874:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 7875: 	!&Apache::lonnet::allowed('usc',
 7876: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 7877: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
 7878: 	unless ($symb) {
 7879: 	    $r->print($doanotherupload);
 7880: 	}
 7881: 	return '';
 7882:     }
 7883:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 7884:     my $uploadedfile;
 7885:     $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
 7886:     if (length($env{'form.upfile'}) < 2) {
 7887:         $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>'));
 7888:     } else {
 7889:         my $result = 
 7890:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
 7891:                                             $env{'form.courseid'},$env{'form.domainid'});
 7892: 	if ($result =~ m{^/uploaded/}) {
 7893: 	    $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
 7894:                           '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
 7895: 			  '<span class="LC_filename">'.$result.'</span>'));
 7896:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
 7897:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
 7898:                                                        $env{'form.courseid'},$uploadedfile));
 7899: 	} else {
 7900: 	    $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
 7901:                           '<span class="LC_error">','</span>',$result,
 7902: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 7903: 	}
 7904:     }
 7905:     if ($symb) {
 7906: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
 7907:     } else {
 7908: 	$r->print($doanotherupload);
 7909:     }
 7910:     return '';
 7911: }
 7912: 
 7913: sub validate_uploaded_scantron_file {
 7914:     my ($cdom,$cname,$fname) = @_;
 7915:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
 7916:     my @lines;
 7917:     if ($scanlines ne '-1') {
 7918:         @lines=split("\n",$scanlines,-1);
 7919:     }
 7920:     my $output;
 7921:     if (@lines) {
 7922:         my (%counts,$max_match_format);
 7923:         my ($max_match_count,$max_match_pct) = (0,0);
 7924:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
 7925:         my %idmap = &username_to_idmap($classlist);
 7926:         foreach my $key (keys(%idmap)) {
 7927:             my $lckey = lc($key);
 7928:             $idmap{$lckey} = $idmap{$key};
 7929:         }
 7930:         my %unique_formats;
 7931:         my @formatlines = &get_scantronformat_file();
 7932:         foreach my $line (@formatlines) {
 7933:             chomp($line);
 7934:             my @config = split(/:/,$line);
 7935:             my $idstart = $config[5];
 7936:             my $idlength = $config[6];
 7937:             if (($idstart ne '') && ($idlength > 0)) {
 7938:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
 7939:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
 7940:                 } else {
 7941:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
 7942:                 }
 7943:             }
 7944:         }
 7945:         foreach my $key (keys(%unique_formats)) {
 7946:             my ($idstart,$idlength) = split(':',$key);
 7947:             %{$counts{$key}} = (
 7948:                                'found'   => 0,
 7949:                                'total'   => 0,
 7950:                               );
 7951:             foreach my $line (@lines) {
 7952:                 next if ($line =~ /^#/);
 7953:                 next if ($line =~ /^[\s\cz]*$/);
 7954:                 my $id = substr($line,$idstart-1,$idlength);
 7955:                 $id = lc($id);
 7956:                 if (exists($idmap{$id})) {
 7957:                     $counts{$key}{'found'} ++;
 7958:                 }
 7959:                 $counts{$key}{'total'} ++;
 7960:             }
 7961:             if ($counts{$key}{'total'}) {
 7962:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
 7963:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
 7964:                     $max_match_pct = $percent_match;
 7965:                     $max_match_format = $key;
 7966:                     $max_match_count = $counts{$key}{'total'};
 7967:                 }
 7968:             }
 7969:         }
 7970:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
 7971:             my $format_descs;
 7972:             my $numwithformat = @{$unique_formats{$max_match_format}};
 7973:             for (my $i=0; $i<$numwithformat; $i++) {
 7974:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
 7975:                 if ($i<$numwithformat-2) {
 7976:                     $format_descs .= '"<i>'.$desc.'</i>", ';
 7977:                 } elsif ($i==$numwithformat-2) {
 7978:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
 7979:                 } elsif ($i==$numwithformat-1) {
 7980:                     $format_descs .= '"<i>'.$desc.'</i>"';
 7981:                 }
 7982:             }
 7983:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
 7984:             $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).
 7985:                        '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
 7986:                        '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
 7987:                        '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
 7988:                                   '<i>'.$cdom.'</i>').'</li>'.
 7989:                        '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
 7990:                        '<li>'.&mt('The course roster is not up to date').'</li>'.
 7991:                        '</ul>';
 7992:         }
 7993:     } else {
 7994:         $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
 7995:     }
 7996:     return $output;
 7997: }
 7998: 
 7999: sub valid_file {
 8000:     my ($requested_file)=@_;
 8001:     foreach my $filename (sort(&scantron_filenames())) {
 8002: 	if ($requested_file eq $filename) { return 1; }
 8003:     }
 8004:     return 0;
 8005: }
 8006: 
 8007: sub scantron_download_scantron_data {
 8008:     my ($r,$symb)=@_;
 8009:     my $default_form_data=&defaultFormData($symb);
 8010:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 8011:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8012:     my $file=$env{'form.scantron_selectfile'};
 8013:     if (! &valid_file($file)) {
 8014: 	$r->print('
 8015: 	<p>
 8016: 	    '.&mt('The requested file name was invalid.').'
 8017:         </p>
 8018: ');
 8019: 	return;
 8020:     }
 8021:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 8022:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 8023:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 8024:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 8025:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 8026:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 8027:     $r->print('
 8028:     <p>
 8029: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
 8030: 	      '<a href="'.$orig.'">','</a>').'
 8031:     </p>
 8032:     <p>
 8033: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 8034: 	      '<a href="'.$corrected.'">','</a>').'
 8035:     </p>
 8036:     <p>
 8037: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 8038: 	      '<a href="'.$skipped.'">','</a>').'
 8039:     </p>
 8040: ');
 8041:     return '';
 8042: }
 8043: 
 8044: sub checkscantron_results {
 8045:     my ($r,$symb) = @_;
 8046:     if (!$symb) {return '';}
 8047:     my $cid = $env{'request.course.id'};
 8048:     my %lettdig = &letter_to_digits();
 8049:     my $numletts = scalar(keys(%lettdig));
 8050:     my $cnum = $env{'course.'.$cid.'.num'};
 8051:     my $cdom = $env{'course.'.$cid.'.domain'};
 8052:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8053:     my %record;
 8054:     my %scantron_config =
 8055:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
 8056:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
 8057:     my $classlist=&Apache::loncoursedata::get_classlist();
 8058:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 8059:     my $navmap=Apache::lonnavmaps::navmap->new();
 8060:     unless (ref($navmap)) {
 8061:         $r->print(&navmap_errormsg());
 8062:         return '';
 8063:     }
 8064:     my $map=$navmap->getResourceByUrl($sequence);
 8065:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8066:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
 8067:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,                             \%grader_randomlists_by_symb);
 8068: 
 8069:     my ($uname,$udom);
 8070:     my (%scandata,%lastname,%bylast);
 8071:     $r->print('
 8072: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 8073: 
 8074:     my @delayqueue;
 8075:     my %completedstudents;
 8076: 
 8077:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
 8078:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet/Submissions Comparison Status',
 8079:                                     'Progress of Bubblesheet Data/Submission Records Comparison',$count,
 8080:                                     'inline',undef,'checkscantron');
 8081:     my ($username,$domain,$started);
 8082:     my $nav_error;
 8083:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
 8084:     if ($nav_error) {
 8085:         $r->print(&navmap_errormsg());
 8086:         return '';
 8087:     }
 8088: 
 8089:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 8090:                                           'Processing first student');
 8091:     my $start=&Time::HiRes::time();
 8092:     my $i=-1;
 8093: 
 8094:     while ($i<$scanlines->{'count'}) {
 8095:         ($username,$domain,$uname)=('','','');
 8096:         $i++;
 8097:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 8098:         if ($line=~/^[\s\cz]*$/) { next; }
 8099:         if ($started) {
 8100:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 8101:                                                      'last student');
 8102:         }
 8103:         $started=1;
 8104:         my $scan_record=
 8105:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 8106:                                                      $scan_data);
 8107:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
 8108:                                                               \%idmap,$i)) {
 8109:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 8110:                                 'Unable to find a student that matches',1);
 8111:             next;
 8112:         }
 8113:         if (exists $completedstudents{$uname}) {
 8114:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 8115:                                 'Student '.$uname.' has multiple sheets',2);
 8116:             next;
 8117:         }
 8118:         my $pid = $scan_record->{'scantron.ID'};
 8119:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 8120:         push(@{$bylast{$lastname{$pid}}},$pid);
 8121:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 8122:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 8123:         chomp($scandata{$pid});
 8124:         $scandata{$pid} =~ s/\r$//;
 8125:         ($username,$domain)=split(/:/,$uname);
 8126:         my $counter = -1;
 8127:         foreach my $resource (@resources) {
 8128:             my $parts;
 8129:             my $ressymb = $resource->symb();
 8130:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 8131:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 8132:                 (my $analysis,$parts) =
 8133:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$username,$domain);
 8134:             } else {
 8135:                 $parts = $grader_partids_by_symb{$ressymb};
 8136:             }
 8137:             ($counter,my $recording) =
 8138:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
 8139:                                          $scandata{$pid},$parts,
 8140:                                          \%scantron_config,\%lettdig,$numletts);
 8141:             $record{$pid} .= $recording;
 8142:         }
 8143:     }
 8144:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 8145:     $r->print('<br />');
 8146:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 8147:     $passed = 0;
 8148:     $failed = 0;
 8149:     $numstudents = 0;
 8150:     foreach my $last (sort(keys(%bylast))) {
 8151:         if (ref($bylast{$last}) eq 'ARRAY') {
 8152:             foreach my $pid (sort(@{$bylast{$last}})) {
 8153:                 my $showscandata = $scandata{$pid};
 8154:                 my $showrecord = $record{$pid};
 8155:                 $showscandata =~ s/\s/&nbsp;/g;
 8156:                 $showrecord =~ s/\s/&nbsp;/g;
 8157:                 if ($scandata{$pid} eq $record{$pid}) {
 8158:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 8159:                     $okstudents .= '<tr class="'.$css_class.'">'.
 8160: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 8161: '</tr>'."\n".
 8162: '<tr class="'.$css_class.'">'."\n".
 8163: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
 8164:                     $passed ++;
 8165:                 } else {
 8166:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
 8167:                     $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".
 8168: '</tr>'."\n".
 8169: '<tr class="'.$css_class.'">'."\n".
 8170: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
 8171: '</tr>'."\n";
 8172:                     $failed ++;
 8173:                 }
 8174:                 $numstudents ++;
 8175:             }
 8176:         }
 8177:     }
 8178:     $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>');
 8179:     $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>');
 8180:     if ($passed) {
 8181:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
 8182:         $r->print(&Apache::loncommon::start_data_table()."\n".
 8183:                  &Apache::loncommon::start_data_table_header_row()."\n".
 8184:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 8185:                  &Apache::loncommon::end_data_table_header_row()."\n".
 8186:                  $okstudents."\n".
 8187:                  &Apache::loncommon::end_data_table().'<br />');
 8188:     }
 8189:     if ($failed) {
 8190:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
 8191:         $r->print(&Apache::loncommon::start_data_table()."\n".
 8192:                  &Apache::loncommon::start_data_table_header_row()."\n".
 8193:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 8194:                  &Apache::loncommon::end_data_table_header_row()."\n".
 8195:                  $badstudents."\n".
 8196:                  &Apache::loncommon::end_data_table()).'<br />'.
 8197:                  &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.');  
 8198:     }
 8199:     $r->print('</form><br />');
 8200:     return;
 8201: }
 8202: 
 8203: sub verify_scantron_grading {
 8204:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
 8205:         $scantron_config,$lettdig,$numletts) = @_;
 8206:     my ($record,%expected,%startpos);
 8207:     return ($counter,$record) if (!ref($resource));
 8208:     return ($counter,$record) if (!$resource->is_problem());
 8209:     my $symb = $resource->symb();
 8210:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
 8211:     foreach my $part_id (@{$partids}) {
 8212:         $counter ++;
 8213:         $expected{$part_id} = 0;
 8214:         if ($env{"form.scantron.sub_bubblelines.$counter"}) {
 8215:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
 8216:             foreach my $item (@sub_lines) {
 8217:                 $expected{$part_id} += $item;
 8218:             }
 8219:         } else {
 8220:             $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
 8221:         }
 8222:         $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
 8223:     }
 8224:     if ($symb) {
 8225:         my %recorded;
 8226:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
 8227:         if ($returnhash{'version'}) {
 8228:             my %lasthash=();
 8229:             my $version;
 8230:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 8231:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 8232:                     $lasthash{$key}=$returnhash{$version.':'.$key};
 8233:                 }
 8234:             }
 8235:             foreach my $key (keys(%lasthash)) {
 8236:                 if ($key =~ /\.scantron$/) {
 8237:                     my $value = &unescape($lasthash{$key});
 8238:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
 8239:                     if ($value eq '') {
 8240:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
 8241:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
 8242:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8243:                             }
 8244:                         }
 8245:                     } else {
 8246:                         my @tocheck;
 8247:                         my @items = split(//,$value);
 8248:                         if (($scantron_config->{'Qon'} eq 'letter') ||
 8249:                             ($scantron_config->{'Qon'} eq 'number')) {
 8250:                             if (@items < $expected{$part_id}) {
 8251:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
 8252:                                 my @singles = split(//,$fragment);
 8253:                                 foreach my $pos (@singles) {
 8254:                                     if ($pos eq ' ') {
 8255:                                         push(@tocheck,$pos);
 8256:                                     } else {
 8257:                                         my $next = shift(@items);
 8258:                                         push(@tocheck,$next);
 8259:                                     }
 8260:                                 }
 8261:                             } else {
 8262:                                 @tocheck = @items;
 8263:                             }
 8264:                             foreach my $letter (@tocheck) {
 8265:                                 if ($scantron_config->{'Qon'} eq 'letter') {
 8266:                                     if ($letter !~ /^[A-J]$/) {
 8267:                                         $letter = $scantron_config->{'Qoff'};
 8268:                                     }
 8269:                                     $recorded{$part_id} .= $letter;
 8270:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
 8271:                                     my $digit;
 8272:                                     if ($letter !~ /^[A-J]$/) {
 8273:                                         $digit = $scantron_config->{'Qoff'};
 8274:                                     } else {
 8275:                                         $digit = $lettdig->{$letter};
 8276:                                     }
 8277:                                     $recorded{$part_id} .= $digit;
 8278:                                 }
 8279:                             }
 8280:                         } else {
 8281:                             @tocheck = @items;
 8282:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
 8283:                                 my $curr_sub = shift(@tocheck);
 8284:                                 my $digit;
 8285:                                 if ($curr_sub =~ /^[A-J]$/) {
 8286:                                     $digit = $lettdig->{$curr_sub}-1;
 8287:                                 }
 8288:                                 if ($curr_sub eq 'J') {
 8289:                                     $digit += scalar($numletts);
 8290:                                 }
 8291:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 8292:                                     if ($j == $digit) {
 8293:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
 8294:                                     } else {
 8295:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8296:                                     }
 8297:                                 }
 8298:                             }
 8299:                         }
 8300:                     }
 8301:                 }
 8302:             }
 8303:         }
 8304:         foreach my $part_id (@{$partids}) {
 8305:             if ($recorded{$part_id} eq '') {
 8306:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
 8307:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 8308:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8309:                     }
 8310:                 }
 8311:             }
 8312:             $record .= $recorded{$part_id};
 8313:         }
 8314:     }
 8315:     return ($counter,$record);
 8316: }
 8317: 
 8318: sub letter_to_digits { 
 8319:     my %lettdig = (
 8320:                     A => 1,
 8321:                     B => 2,
 8322:                     C => 3,
 8323:                     D => 4,
 8324:                     E => 5,
 8325:                     F => 6,
 8326:                     G => 7,
 8327:                     H => 8,
 8328:                     I => 9,
 8329:                     J => 0,
 8330:                   );
 8331:     return %lettdig;
 8332: }
 8333: 
 8334: 
 8335: #-------- end of section for handling grading scantron forms -------
 8336: #
 8337: #-------------------------------------------------------------------
 8338: 
 8339: #-------------------------- Menu interface -------------------------
 8340: #
 8341: #--- Href with symb and command ---
 8342: 
 8343: sub href_symb_cmd {
 8344:     my ($symb,$cmd)=@_;
 8345:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&command='.$cmd;
 8346: }
 8347: 
 8348: sub grading_menu {
 8349:     my ($request,$symb) = @_;
 8350:     if (!$symb) {return '';}
 8351: 
 8352:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 8353:                   'command'=>'individual');
 8354:     
 8355:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8356: 
 8357:     $fields{'command'}='ungraded';
 8358:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8359: 
 8360:     $fields{'command'}='table';
 8361:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8362: 
 8363:     $fields{'command'}='all_for_one';
 8364:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8365: 
 8366:     $fields{'command'}='downloadfilesselect';
 8367:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8368: 
 8369:     $fields{'command'} = 'csvform';
 8370:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8371:     
 8372:     $fields{'command'} = 'processclicker';
 8373:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8374:     
 8375:     $fields{'command'} = 'scantron_selectphase';
 8376:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8377: 
 8378:     $fields{'command'} = 'initialverifyreceipt';
 8379:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8380:     
 8381:     my @menu = ({	categorytitle=>'Hand Grading',
 8382:             items =>[
 8383:                         {	linktext => 'Select individual students to grade',
 8384:                     		url => $url1a,
 8385:                     		permission => 'F',
 8386:                     		icon => 'grade_students.png',
 8387:                     		linktitle => 'Grade current resource for a selection of students.'
 8388:                         }, 
 8389:                         {       linktext => 'Grade ungraded submissions.',
 8390:                                 url => $url1b,
 8391:                                 permission => 'F',
 8392:                                 icon => 'ungrade_sub.png',
 8393:                                 linktitle => 'Grade all submissions that have not been graded yet.'
 8394:                         },
 8395: 
 8396:                         {       linktext => 'Grading table',
 8397:                                 url => $url1c,
 8398:                                 permission => 'F',
 8399:                                 icon => 'grading_table.png',
 8400:                                 linktitle => 'Grade current resource for all students.'
 8401:                         },
 8402:                         {       linktext => 'Grade page/folder for one student',
 8403:                                 url => $url1d,
 8404:                                 permission => 'F',
 8405:                                 icon => 'grade_PageFolder.png',
 8406:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
 8407:                         },
 8408:                         {       linktext => 'Download submissions',
 8409:                                 url => $url1e,
 8410:                                 permission => 'F',
 8411:                                 icon => 'download_sub.png',
 8412:                                 linktitle => 'Download all students submissions.'
 8413:                         }]},
 8414:                          { categorytitle=>'Automated Grading',
 8415:                items =>[
 8416: 
 8417:                 	    {	linktext => 'Upload Scores',
 8418:                     		url => $url2,
 8419:                     		permission => 'F',
 8420:                     		icon => 'uploadscores.png',
 8421:                     		linktitle => 'Specify a file containing the class scores for current resource.'
 8422:                 	    },
 8423:                 	    {	linktext => 'Process Clicker',
 8424:                     		url => $url3,
 8425:                     		permission => 'F',
 8426:                     		icon => 'addClickerInfoFile.png',
 8427:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
 8428:                 	    },
 8429:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
 8430:                     		url => $url4,
 8431:                     		permission => 'F',
 8432:                     		icon => 'bubblesheet.png',
 8433:                     		linktitle => 'Grade scantron exams, upload/download scantron data files, and review previously graded scantron exams.'
 8434:                 	    },
 8435:                             {   linktext => 'Verify Receipt Number',
 8436:                                 url => $url5,
 8437:                                 permission => 'F',
 8438:                                 icon => 'receipt_number.png',
 8439:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
 8440:                             }
 8441: 
 8442:                     ]
 8443:             });
 8444: 
 8445:     # Create the menu
 8446:     my $Str;
 8447:     $Str .= '<form method="post" action="" name="gradingMenu">';
 8448:     $Str .= '<input type="hidden" name="command" value="" />'.
 8449:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 8450: 
 8451:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
 8452:     return $Str;    
 8453: }
 8454: 
 8455: 
 8456: sub ungraded {
 8457:     my ($request)=@_;
 8458:     &submit_options($request);
 8459: }
 8460: 
 8461: sub submit_options_sequence {
 8462:     my ($request,$symb) = @_;
 8463:     if (!$symb) {return '';}
 8464:     &commonJSfunctions($request);
 8465:     my $result;
 8466: 
 8467:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8468:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 8469:     $result.=&selectfield(0).
 8470:             '<input type="hidden" name="command" value="pickStudentPage" />
 8471:             <div>
 8472:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 8473:             </div>
 8474:         </div>
 8475:   </form>';
 8476:     return $result;
 8477: }
 8478: 
 8479: sub submit_options_table {
 8480:     my ($request,$symb) = @_;
 8481:     if (!$symb) {return '';}
 8482:     &commonJSfunctions($request);
 8483:     my $result;
 8484: 
 8485:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8486:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 8487: 
 8488:     $result.=&selectfield(0).
 8489:             '<input type="hidden" name="command" value="viewgrades" />
 8490:             <div>
 8491:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 8492:             </div>
 8493:         </div>
 8494:   </form>';
 8495:     return $result;
 8496: }
 8497: 
 8498: sub submit_options_download {
 8499:     my ($request,$symb) = @_;
 8500:     if (!$symb) {return '';}
 8501: 
 8502:     &commonJSfunctions($request);
 8503: 
 8504:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8505:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 8506:     $result.='
 8507: <h2>
 8508:   '.&mt('Select Students for Which to Download Submissions').'
 8509: </h2>'.&selectfield(1).'
 8510:                 <input type="hidden" name="command" value="downloadfileslink" /> 
 8511:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 8512:             </div>
 8513:           </div>
 8514: 
 8515: 
 8516:   </form>';
 8517:     return $result;
 8518: }
 8519: 
 8520: #--- Displays the submissions first page -------
 8521: sub submit_options {
 8522:     my ($request,$symb) = @_;
 8523:     if (!$symb) {return '';}
 8524: 
 8525:     &commonJSfunctions($request);
 8526:     my $result;
 8527: 
 8528:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8529: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 8530:     $result.=&selectfield(1).'
 8531:                 <input type="hidden" name="command" value="submission" /> 
 8532: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
 8533:             </div>
 8534:           </div>
 8535: 
 8536: 
 8537:   </form>';
 8538:     return $result;
 8539: }
 8540: 
 8541: sub selectfield {
 8542:    my ($full)=@_;
 8543:    my %options = 
 8544:           (&Apache::lonlocal::texthash(
 8545:              'yes'       => 'with submissions',
 8546:              'queued'    => 'in grading queue',
 8547:              'graded'    => 'with ungraded submissions',
 8548:              'incorrect' => 'with incorrect submissions',
 8549:              'all'       => 'with any status'),
 8550:              'select_form_order' => ['yes','queued','graded','incorrect','all']);
 8551:    my $result='<div class="LC_columnSection">
 8552:   
 8553:     <fieldset>
 8554:       <legend>
 8555:        '.&mt('Sections').'
 8556:       </legend>
 8557:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
 8558:     </fieldset>
 8559:   
 8560:     <fieldset>
 8561:       <legend>
 8562:         '.&mt('Groups').'
 8563:       </legend>
 8564:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
 8565:     </fieldset>
 8566:   
 8567:     <fieldset>
 8568:       <legend>
 8569:         '.&mt('Access Status').'
 8570:       </legend>
 8571:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
 8572:     </fieldset>';
 8573:     if ($full) {
 8574:        $result.='
 8575:     <fieldset>
 8576:       <legend>
 8577:         '.&mt('Submission Status').'
 8578:       </legend>'.
 8579:        &Apache::loncommon::select_form('all','submitonly',\%options).
 8580:    '</fieldset>';
 8581:     }
 8582:     $result.='</div><br />';
 8583:     return $result;
 8584: }
 8585: 
 8586: sub reset_perm {
 8587:     undef(%perm);
 8588: }
 8589: 
 8590: sub init_perm {
 8591:     &reset_perm();
 8592:     foreach my $test_perm ('vgr','mgr','opa') {
 8593: 
 8594: 	my $scope = $env{'request.course.id'};
 8595: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
 8596: 
 8597: 	    $scope .= '/'.$env{'request.course.sec'};
 8598: 	    if ( $perm{$test_perm}=
 8599: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
 8600: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
 8601: 	    } else {
 8602: 		delete($perm{$test_perm});
 8603: 	    }
 8604: 	}
 8605:     }
 8606: }
 8607: 
 8608: sub gather_clicker_ids {
 8609:     my %clicker_ids;
 8610: 
 8611:     my $classlist = &Apache::loncoursedata::get_classlist();
 8612: 
 8613:     # Set up a couple variables.
 8614:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
 8615:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
 8616:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
 8617: 
 8618:     foreach my $student (keys(%$classlist)) {
 8619:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
 8620:         my $username = $classlist->{$student}->[$username_idx];
 8621:         my $domain   = $classlist->{$student}->[$domain_idx];
 8622:         my $clickers =
 8623: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
 8624:         foreach my $id (split(/\,/,$clickers)) {
 8625:             $id=~s/^[\#0]+//;
 8626:             $id=~s/[\-\:]//g;
 8627:             if (exists($clicker_ids{$id})) {
 8628: 		$clicker_ids{$id}.=','.$username.':'.$domain;
 8629:             } else {
 8630: 		$clicker_ids{$id}=$username.':'.$domain;
 8631:             }
 8632:         }
 8633:     }
 8634:     return %clicker_ids;
 8635: }
 8636: 
 8637: sub gather_adv_clicker_ids {
 8638:     my %clicker_ids;
 8639:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 8640:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8641:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
 8642:     foreach my $element (sort(keys(%coursepersonnel))) {
 8643:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
 8644:             my ($puname,$pudom)=split(/\:/,$person);
 8645:             my $clickers =
 8646: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
 8647:             foreach my $id (split(/\,/,$clickers)) {
 8648: 		$id=~s/^[\#0]+//;
 8649:                 $id=~s/[\-\:]//g;
 8650: 		if (exists($clicker_ids{$id})) {
 8651: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
 8652: 		} else {
 8653: 		    $clicker_ids{$id}=$puname.':'.$pudom;
 8654: 		}
 8655:             }
 8656:         }
 8657:     }
 8658:     return %clicker_ids;
 8659: }
 8660: 
 8661: sub clicker_grading_parameters {
 8662:     return ('gradingmechanism' => 'scalar',
 8663:             'upfiletype' => 'scalar',
 8664:             'specificid' => 'scalar',
 8665:             'pcorrect' => 'scalar',
 8666:             'pincorrect' => 'scalar');
 8667: }
 8668: 
 8669: sub process_clicker {
 8670:     my ($r,$symb)=@_;
 8671:     if (!$symb) {return '';}
 8672:     my $result=&checkforfile_js();
 8673:     $result.=&Apache::loncommon::start_data_table().
 8674:              &Apache::loncommon::start_data_table_header_row().
 8675:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
 8676:              &Apache::loncommon::end_data_table_header_row().
 8677:              &Apache::loncommon::start_data_table_row()."<td>\n";
 8678: # Attempt to restore parameters from last session, set defaults if not present
 8679:     my %Saveable_Parameters=&clicker_grading_parameters();
 8680:     &Apache::loncommon::restore_course_settings('grades_clicker',
 8681:                                                  \%Saveable_Parameters);
 8682:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
 8683:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
 8684:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
 8685:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
 8686: 
 8687:     my %checked;
 8688:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
 8689:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
 8690:           $checked{$gradingmechanism}=' checked="checked"';
 8691:        }
 8692:     }
 8693: 
 8694:     my $upload=&mt("Evaluate File");
 8695:     my $type=&mt("Type");
 8696:     my $attendance=&mt("Award points just for participation");
 8697:     my $personnel=&mt("Correctness determined from response by course personnel");
 8698:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
 8699:     my $given=&mt("Correctness determined from given list of answers").' '.
 8700:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
 8701:     my $pcorrect=&mt("Percentage points for correct solution");
 8702:     my $pincorrect=&mt("Percentage points for incorrect solution");
 8703:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
 8704: 						   {'iclicker' => 'i>clicker',
 8705:                                                     'interwrite' => 'interwrite PRS'});
 8706:     $symb = &Apache::lonenc::check_encrypt($symb);
 8707:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
 8708: function sanitycheck() {
 8709: // Accept only integer percentages
 8710:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
 8711:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
 8712: // Find out grading choice
 8713:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8714:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
 8715:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
 8716:       }
 8717:    }
 8718: // By default, new choice equals user selection
 8719:    newgradingchoice=gradingchoice;
 8720: // Not good to give more points for false answers than correct ones
 8721:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
 8722:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
 8723:    }
 8724: // If new choice is attendance only, and old choice was correctness-based, restore defaults
 8725:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
 8726:       document.forms.gradesupload.pcorrect.value=100;
 8727:       document.forms.gradesupload.pincorrect.value=100;
 8728:    }
 8729: // If the values are different, cannot be attendance only
 8730:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
 8731:        (gradingchoice=='attendance')) {
 8732:        newgradingchoice='personnel';
 8733:    }
 8734: // Change grading choice to new one
 8735:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8736:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
 8737:          document.forms.gradesupload.gradingmechanism[i].checked=true;
 8738:       } else {
 8739:          document.forms.gradesupload.gradingmechanism[i].checked=false;
 8740:       }
 8741:    }
 8742: // Remember the old state
 8743:    document.forms.gradesupload.waschecked.value=newgradingchoice;
 8744: }
 8745: ENDUPFORM
 8746:     $result.= <<ENDUPFORM;
 8747: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 8748: <input type="hidden" name="symb" value="$symb" />
 8749: <input type="hidden" name="command" value="processclickerfile" />
 8750: <input type="file" name="upfile" size="50" />
 8751: <br /><label>$type: $selectform</label>
 8752: ENDUPFORM
 8753:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
 8754:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
 8755:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
 8756: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
 8757: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
 8758: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
 8759: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
 8760: <br />&nbsp;&nbsp;&nbsp;
 8761: <input type="text" name="givenanswer" size="50" />
 8762: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
 8763: ENDGRADINGFORM
 8764:          $result.='</td>'.&Apache::loncommon::end_data_table_row().
 8765:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
 8766:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
 8767: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
 8768: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 8769: </form>'
 8770: ENDPERCFORM
 8771:     $result.='</td>'.
 8772:              &Apache::loncommon::end_data_table_row().
 8773:              &Apache::loncommon::end_data_table();
 8774:     return $result;
 8775: }
 8776: 
 8777: sub process_clicker_file {
 8778:     my ($r,$symb)=@_;
 8779:     if (!$symb) {return '';}
 8780: 
 8781:     my %Saveable_Parameters=&clicker_grading_parameters();
 8782:     &Apache::loncommon::store_course_settings('grades_clicker',
 8783:                                               \%Saveable_Parameters);
 8784:     my $result='';
 8785:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
 8786: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
 8787: 	return $result;
 8788:     }
 8789:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
 8790:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
 8791:         return $result;
 8792:     }
 8793:     my $foundgiven=0;
 8794:     if ($env{'form.gradingmechanism'} eq 'given') {
 8795:         $env{'form.givenanswer'}=~s/^\s*//gs;
 8796:         $env{'form.givenanswer'}=~s/\s*$//gs;
 8797:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-]+/\,/g;
 8798:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
 8799:         my @answers=split(/\,/,$env{'form.givenanswer'});
 8800:         $foundgiven=$#answers+1;
 8801:     }
 8802:     my %clicker_ids=&gather_clicker_ids();
 8803:     my %correct_ids;
 8804:     if ($env{'form.gradingmechanism'} eq 'personnel') {
 8805: 	%correct_ids=&gather_adv_clicker_ids();
 8806:     }
 8807:     if ($env{'form.gradingmechanism'} eq 'specific') {
 8808: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
 8809: 	   $correct_id=~tr/a-z/A-Z/;
 8810: 	   $correct_id=~s/\s//gs;
 8811: 	   $correct_id=~s/^[\#0]+//;
 8812:            $correct_id=~s/[\-\:]//g;
 8813:            if ($correct_id) {
 8814: 	      $correct_ids{$correct_id}='specified';
 8815:            }
 8816:         }
 8817:     }
 8818:     if ($env{'form.gradingmechanism'} eq 'attendance') {
 8819: 	$result.=&mt('Score based on attendance only');
 8820:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
 8821:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
 8822:     } else {
 8823: 	my $number=0;
 8824: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
 8825: 	foreach my $id (sort(keys(%correct_ids))) {
 8826: 	    $result.='<br /><tt>'.$id.'</tt> - ';
 8827: 	    if ($correct_ids{$id} eq 'specified') {
 8828: 		$result.=&mt('specified');
 8829: 	    } else {
 8830: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
 8831: 		$result.=&Apache::loncommon::plainname($uname,$udom);
 8832: 	    }
 8833: 	    $number++;
 8834: 	}
 8835:         $result.="</p>\n";
 8836: 	if ($number==0) {
 8837: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
 8838: 	    return $result;
 8839: 	}
 8840:     }
 8841:     if (length($env{'form.upfile'}) < 2) {
 8842:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
 8843: 		     '<span class="LC_error">',
 8844: 		     '</span>',
 8845: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
 8846:         return $result;
 8847:     }
 8848: 
 8849: # Were able to get all the info needed, now analyze the file
 8850: 
 8851:     $result.=&Apache::loncommon::studentbrowser_javascript();
 8852:     $symb = &Apache::lonenc::check_encrypt($symb);
 8853:     $result.=&Apache::loncommon::start_data_table().
 8854:              &Apache::loncommon::start_data_table_header_row().
 8855:              '<th>'.&mt('Evaluate clicker file').'</th>'.
 8856:              &Apache::loncommon::end_data_table_header_row().
 8857:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
 8858: <td>
 8859: <form method="post" action="/adm/grades" name="clickeranalysis">
 8860: <input type="hidden" name="symb" value="$symb" />
 8861: <input type="hidden" name="command" value="assignclickergrades" />
 8862: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
 8863: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
 8864: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
 8865: ENDHEADER
 8866:     if ($env{'form.gradingmechanism'} eq 'given') {
 8867:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
 8868:     } 
 8869:     my %responses;
 8870:     my @questiontitles;
 8871:     my $errormsg='';
 8872:     my $number=0;
 8873:     if ($env{'form.upfiletype'} eq 'iclicker') {
 8874: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
 8875:     }
 8876:     if ($env{'form.upfiletype'} eq 'interwrite') {
 8877:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
 8878:     }
 8879:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
 8880:              '<input type="hidden" name="number" value="'.$number.'" />'.
 8881:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
 8882:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
 8883:              '<br />';
 8884:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
 8885:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
 8886:        return $result;
 8887:     } 
 8888: # Remember Question Titles
 8889: # FIXME: Possibly need delimiter other than ":"
 8890:     for (my $i=0;$i<$number;$i++) {
 8891:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
 8892:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
 8893:     }
 8894:     my $correct_count=0;
 8895:     my $student_count=0;
 8896:     my $unknown_count=0;
 8897: # Match answers with usernames
 8898: # FIXME: Possibly need delimiter other than ":"
 8899:     foreach my $id (keys(%responses)) {
 8900:        if ($correct_ids{$id}) {
 8901:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
 8902:           $correct_count++;
 8903:        } elsif ($clicker_ids{$id}) {
 8904:           if ($clicker_ids{$id}=~/\,/) {
 8905: # More than one user with the same clicker!
 8906:              $result.="</td>".&Apache::loncommon::end_data_table_row().
 8907:                            &Apache::loncommon::start_data_table_row()."<td>".
 8908:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
 8909:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 8910:                            "<select name='multi".$id."'>";
 8911:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
 8912:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
 8913:              }
 8914:              $result.='</select>';
 8915:              $unknown_count++;
 8916:           } else {
 8917: # Good: found one and only one user with the right clicker
 8918:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
 8919:              $student_count++;
 8920:           }
 8921:        } else {
 8922:           $result.="</td>".&Apache::loncommon::end_data_table_row().
 8923:                            &Apache::loncommon::start_data_table_row()."<td>".
 8924:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
 8925:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 8926:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
 8927:                    "\n".&mt("Domain").": ".
 8928:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
 8929:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
 8930:           $unknown_count++;
 8931:        }
 8932:     }
 8933:     $result.='<hr />'.
 8934:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
 8935:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
 8936:        if ($correct_count==0) {
 8937:           $errormsg.="Found no correct answers answers for grading!";
 8938:        } elsif ($correct_count>1) {
 8939:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
 8940:        }
 8941:     }
 8942:     if ($number<1) {
 8943:        $errormsg.="Found no questions.";
 8944:     }
 8945:     if ($errormsg) {
 8946:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
 8947:     } else {
 8948:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
 8949:     }
 8950:     $result.='</form></td>'.
 8951:              &Apache::loncommon::end_data_table_row().
 8952:              &Apache::loncommon::end_data_table();
 8953:     return $result;
 8954: }
 8955: 
 8956: sub iclicker_eval {
 8957:     my ($questiontitles,$responses)=@_;
 8958:     my $number=0;
 8959:     my $errormsg='';
 8960:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 8961:         my %components=&Apache::loncommon::record_sep($line);
 8962:         my @entries=map {$components{$_}} (sort(keys(%components)));
 8963: 	if ($entries[0] eq 'Question') {
 8964: 	    for (my $i=3;$i<$#entries;$i+=6) {
 8965: 		$$questiontitles[$number]=$entries[$i];
 8966: 		$number++;
 8967: 	    }
 8968: 	}
 8969: 	if ($entries[0]=~/^\#/) {
 8970: 	    my $id=$entries[0];
 8971: 	    my @idresponses;
 8972: 	    $id=~s/^[\#0]+//;
 8973: 	    for (my $i=0;$i<$number;$i++) {
 8974: 		my $idx=3+$i*6;
 8975: 		push(@idresponses,$entries[$idx]);
 8976: 	    }
 8977: 	    $$responses{$id}=join(',',@idresponses);
 8978: 	}
 8979:     }
 8980:     return ($errormsg,$number);
 8981: }
 8982: 
 8983: sub interwrite_eval {
 8984:     my ($questiontitles,$responses)=@_;
 8985:     my $number=0;
 8986:     my $errormsg='';
 8987:     my $skipline=1;
 8988:     my $questionnumber=0;
 8989:     my %idresponses=();
 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[1] eq 'Time') { $skipline=0; next; }
 8994:         if ($entries[1] eq 'Response') { $skipline=1; }
 8995:         next if $skipline;
 8996:         if ($entries[0]!=$questionnumber) {
 8997:            $questionnumber=$entries[0];
 8998:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
 8999:            $number++;
 9000:         }
 9001:         my $id=$entries[4];
 9002:         $id=~s/^[\#0]+//;
 9003:         $id=~s/^v\d*\://i;
 9004:         $id=~s/[\-\:]//g;
 9005:         $idresponses{$id}[$number]=$entries[6];
 9006:     }
 9007:     foreach my $id (keys(%idresponses)) {
 9008:        $$responses{$id}=join(',',@{$idresponses{$id}});
 9009:        $$responses{$id}=~s/^\s*\,//;
 9010:     }
 9011:     return ($errormsg,$number);
 9012: }
 9013: 
 9014: sub assign_clicker_grades {
 9015:     my ($r,$symb)=@_;
 9016:     if (!$symb) {return '';}
 9017: # See which part we are saving to
 9018:     my $res_error;
 9019:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 9020:     if ($res_error) {
 9021:         return &navmap_errormsg();
 9022:     }
 9023: # FIXME: This should probably look for the first handgradeable part
 9024:     my $part=$$partlist[0];
 9025: # Start screen output
 9026:     my $result=&Apache::loncommon::start_data_table().
 9027:              &Apache::loncommon::start_data_table_header_row().
 9028:              '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
 9029:              &Apache::loncommon::end_data_table_header_row().
 9030:              &Apache::loncommon::start_data_table_row().'<td>';
 9031: # Get correct result
 9032: # FIXME: Possibly need delimiter other than ":"
 9033:     my @correct=();
 9034:     my $gradingmechanism=$env{'form.gradingmechanism'};
 9035:     my $number=$env{'form.number'};
 9036:     if ($gradingmechanism ne 'attendance') {
 9037:        foreach my $key (keys(%env)) {
 9038:           if ($key=~/^form\.correct\:/) {
 9039:              my @input=split(/\,/,$env{$key});
 9040:              for (my $i=0;$i<=$#input;$i++) {
 9041:                  if (($correct[$i]) && ($input[$i]) &&
 9042:                      ($correct[$i] ne $input[$i])) {
 9043:                     $result.='<br /><span class="LC_warning">'.
 9044:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
 9045:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
 9046:                  } elsif ($input[$i]) {
 9047:                     $correct[$i]=$input[$i];
 9048:                  }
 9049:              }
 9050:           }
 9051:        }
 9052:        for (my $i=0;$i<$number;$i++) {
 9053:           if (!$correct[$i]) {
 9054:              $result.='<br /><span class="LC_error">'.
 9055:                       &mt('No correct result given for question "[_1]"!',
 9056:                           $env{'form.question:'.$i}).'</span>';
 9057:           }
 9058:        }
 9059:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
 9060:     }
 9061: # Start grading
 9062:     my $pcorrect=$env{'form.pcorrect'};
 9063:     my $pincorrect=$env{'form.pincorrect'};
 9064:     my $storecount=0;
 9065:     my %users=();
 9066:     foreach my $key (keys(%env)) {
 9067:        my $user='';
 9068:        if ($key=~/^form\.student\:(.*)$/) {
 9069:           $user=$1;
 9070:        }
 9071:        if ($key=~/^form\.unknown\:(.*)$/) {
 9072:           my $id=$1;
 9073:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
 9074:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
 9075:           } elsif ($env{'form.multi'.$id}) {
 9076:              $user=$env{'form.multi'.$id};
 9077:           }
 9078:        }
 9079:        if ($user) {
 9080:           if ($users{$user}) {
 9081:              $result.='<br /><span class="LC_warning">'.
 9082:                       &mt("More than one entry found for <tt>[_1]</tt>!",$user).
 9083:                       '</span><br />';
 9084:           }
 9085:           $users{$user}=1; 
 9086:           my @answer=split(/\,/,$env{$key});
 9087:           my $sum=0;
 9088:           my $realnumber=$number;
 9089:           for (my $i=0;$i<$number;$i++) {
 9090:              if  ($correct[$i] eq '-') {
 9091:                 $realnumber--;
 9092:              } elsif ($answer[$i]) {
 9093:                 if ($gradingmechanism eq 'attendance') {
 9094:                    $sum+=$pcorrect;
 9095:                 } elsif ($correct[$i] eq '*') {
 9096:                    $sum+=$pcorrect;
 9097:                 } else {
 9098:                    if ($answer[$i] eq $correct[$i]) {
 9099:                       $sum+=$pcorrect;
 9100:                    } else {
 9101:                       $sum+=$pincorrect;
 9102:                    }
 9103:                 }
 9104:              }
 9105:           }
 9106:           my $ave=$sum/(100*$realnumber);
 9107: # Store
 9108:           my ($username,$domain)=split(/\:/,$user);
 9109:           my %grades=();
 9110:           $grades{"resource.$part.solved"}='correct_by_override';
 9111:           $grades{"resource.$part.awarded"}=$ave;
 9112:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 9113:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
 9114:                                                  $env{'request.course.id'},
 9115:                                                  $domain,$username);
 9116:           if ($returncode ne 'ok') {
 9117:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
 9118:           } else {
 9119:              $storecount++;
 9120:           }
 9121:        }
 9122:     }
 9123: # We are done
 9124:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
 9125:              '</td>'.
 9126:              &Apache::loncommon::end_data_table_row().
 9127:              &Apache::loncommon::end_data_table();
 9128:     return $result;
 9129: }
 9130: 
 9131: sub navmap_errormsg {
 9132:     return '<div class="LC_error">'.
 9133:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
 9134:            &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>').
 9135:            '</div>';
 9136: }
 9137: 
 9138: sub startpage {
 9139:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag) = @_;
 9140:     unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
 9141:     $r->print(&Apache::loncommon::start_page('Grading',undef,
 9142:                                           {'bread_crumbs' => $crumbs}));
 9143:     $r->print('<h3>'.$$crumbs[-1]{'text'}.'</h3>');
 9144:     unless ($nodisplayflag) {
 9145:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag));
 9146:     }
 9147: }
 9148: 
 9149: sub select_problem {
 9150:     my ($r)=@_;
 9151:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
 9152:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1));
 9153:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
 9154:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
 9155: }
 9156: 
 9157: sub handler {
 9158:     my $request=$_[0];
 9159:     &reset_caches();
 9160:     if ($env{'browser.mathml'}) {
 9161: 	&Apache::loncommon::content_type($request,'text/xml');
 9162:     } else {
 9163: 	&Apache::loncommon::content_type($request,'text/html');
 9164:     }
 9165:     $request->send_http_header;
 9166:     return '' if $request->header_only;
 9167:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
 9168: 
 9169: # see what command we need to execute
 9170: 
 9171:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
 9172:     my $command=$commands[0];
 9173: 
 9174:     if ($#commands > 0) {
 9175: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
 9176:     }
 9177: 
 9178: # see what the symb is
 9179: 
 9180:     my $symb=$env{'form.symb'};
 9181:     unless ($symb) {
 9182:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
 9183:        $symb=&Apache::lonnet::symbread($url);
 9184:     }
 9185:     &Apache::lonenc::check_decrypt(\$symb);                             
 9186: 
 9187:     $ssi_error = 0;
 9188:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
 9189: #
 9190: # Not called from a resource, but inside a course
 9191: #    
 9192:         &startpage($request,undef,[],1,1);
 9193:         &select_problem($request);
 9194:     } else {
 9195: 	&init_perm();
 9196: 	if ($command eq 'submission' && $perm{'vgr'}) {
 9197:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}]);
 9198: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
 9199: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
 9200:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
 9201:                                        {href=>'',text=>'Select student'}],1,1);
 9202: 	    &pickStudentPage($request,$symb);
 9203: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
 9204:             &startpage($request,$symb,
 9205:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
 9206:                                        {href=>'',text=>'Select student'},
 9207:                                        {href=>'',text=>'Grade student'}],1,1);
 9208: 	    &displayPage($request,$symb);
 9209: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
 9210:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
 9211:                                        {href=>'',text=>'Select student'},
 9212:                                        {href=>'',text=>'Grade student'},
 9213:                                        {href=>'',text=>'Store grades'}],1,1);
 9214: 	    &updateGradeByPage($request,$symb);
 9215: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
 9216:             &startpage($request,$symb,[{href=>'',text=>'...'},
 9217:                                        {href=>'',text=>'Modify grades'}]);
 9218: 	    &processGroup($request,$symb);
 9219: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
 9220:             &startpage($request,$symb);
 9221: 	    $request->print(&grading_menu($request,$symb));
 9222: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
 9223:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
 9224: 	    $request->print(&submit_options($request,$symb));
 9225:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
 9226:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}]);
 9227:             $request->print(&listStudents($request,$symb,'graded'));
 9228:         } elsif ($command eq 'table' && $perm{'vgr'}) {
 9229:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
 9230:             $request->print(&submit_options_table($request,$symb));
 9231:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
 9232:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
 9233:             $request->print(&submit_options_sequence($request,$symb));
 9234: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
 9235:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
 9236: 	    $request->print(&viewgrades($request,$symb));
 9237: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
 9238:             &startpage($request,$symb,[{href=>'',text=>'...'},
 9239:                                        {href=>'',text=>'Store grades'}]);
 9240: 	    $request->print(&processHandGrade($request,$symb));
 9241: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
 9242:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
 9243:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
 9244:                                                                              text=>"Modify grades"},
 9245:                                        {href=>'', text=>"Store grades"}]);
 9246: 	    $request->print(&editgrades($request,$symb));
 9247:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
 9248:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
 9249:             $request->print(&initialverifyreceipt($request,$symb));
 9250: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
 9251:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
 9252:                                        {href=>'',text=>'Verification Result'}]);
 9253: 	    $request->print(&verifyreceipt($request,$symb));
 9254:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
 9255:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
 9256:             $request->print(&process_clicker($request,$symb));
 9257:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
 9258:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
 9259:                                        {href=>'', text=>'Process clicker file'}]);
 9260:             $request->print(&process_clicker_file($request,$symb));
 9261:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
 9262:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
 9263:                                        {href=>'', text=>'Process clicker file'},
 9264:                                        {href=>'', text=>'Store grades'}]);
 9265:             $request->print(&assign_clicker_grades($request,$symb));
 9266: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
 9267:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
 9268: 	    $request->print(&upcsvScores_form($request,$symb));
 9269: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
 9270:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
 9271: 	    $request->print(&csvupload($request,$symb));
 9272: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
 9273:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
 9274: 	    $request->print(&csvuploadmap($request,$symb));
 9275: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
 9276: 	    if ($env{'form.associate'} ne 'Reverse Association') {
 9277:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
 9278: 		$request->print(&csvuploadoptions($request,$symb));
 9279: 	    } else {
 9280: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
 9281: 		    $env{'form.upfile_associate'} = 'reverse';
 9282: 		} else {
 9283: 		    $env{'form.upfile_associate'} = 'forward';
 9284: 		}
 9285:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
 9286: 		$request->print(&csvuploadmap($request,$symb));
 9287: 	    }
 9288: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
 9289:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
 9290: 	    $request->print(&csvuploadassign($request,$symb));
 9291: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
 9292:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9293: 	    $request->print(&scantron_selectphase($request,undef,$symb));
 9294:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
 9295:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9296:  	    $request->print(&scantron_do_warning($request,$symb));
 9297: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
 9298:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9299: 	    $request->print(&scantron_validate_file($request,$symb));
 9300: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
 9301:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9302: 	    $request->print(&scantron_process_students($request,$symb));
 9303:  	} elsif ($command eq 'scantronupload' && 
 9304:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9305: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9306:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9307:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
 9308:  	} elsif ($command eq 'scantronupload_save' &&
 9309:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9310: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9311:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9312:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
 9313:  	} elsif ($command eq 'scantron_download' &&
 9314: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 9315:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9316:  	    $request->print(&scantron_download_scantron_data($request,$symb));
 9317:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
 9318:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9319:             $request->print(&checkscantron_results($request,$symb));
 9320:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
 9321:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}]);
 9322:             $request->print(&submit_options_download($request,$symb));
 9323:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
 9324:             &startpage($request,$symb,
 9325:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
 9326:     {href=>'', text=>'Download submissions'}]);
 9327:             &submit_download_link($request,$symb);
 9328: 	} elsif ($command) {
 9329:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
 9330: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
 9331: 	}
 9332:     }
 9333:     if ($ssi_error) {
 9334: 	&ssi_print_error($request);
 9335:     }
 9336:     $request->print(&Apache::loncommon::end_page());
 9337:     &reset_caches();
 9338:     return '';
 9339: }
 9340: 
 9341: 1;
 9342: 
 9343: __END__;
 9344: 
 9345: 
 9346: =head1 NAME
 9347: 
 9348: Apache::grades
 9349: 
 9350: =head1 SYNOPSIS
 9351: 
 9352: Handles the viewing of grades.
 9353: 
 9354: This is part of the LearningOnline Network with CAPA project
 9355: described at http://www.lon-capa.org.
 9356: 
 9357: =head1 OVERVIEW
 9358: 
 9359: Do an ssi with retries:
 9360: While I'd love to factor out this with the vesrion in lonprintout,
 9361: 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
 9362: I'm not quite ready to invent (e.g. an ssi_with_retry object).
 9363: 
 9364: At least the logic that drives this has been pulled out into loncommon.
 9365: 
 9366: 
 9367: 
 9368: ssi_with_retries - Does the server side include of a resource.
 9369:                      if the ssi call returns an error we'll retry it up to
 9370:                      the number of times requested by the caller.
 9371:                      If we still have a proble, no text is appended to the
 9372:                      output and we set some global variables.
 9373:                      to indicate to the caller an SSI error occurred.  
 9374:                      All of this is supposed to deal with the issues described
 9375:                      in LonCAPA BZ 5631 see:
 9376:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
 9377:                      by informing the user that this happened.
 9378: 
 9379: Parameters:
 9380:   resource   - The resource to include.  This is passed directly, without
 9381:                interpretation to lonnet::ssi.
 9382:   form       - The form hash parameters that guide the interpretation of the resource
 9383:                
 9384:   retries    - Number of retries allowed before giving up completely.
 9385: Returns:
 9386:   On success, returns the rendered resource identified by the resource parameter.
 9387: Side Effects:
 9388:   The following global variables can be set:
 9389:    ssi_error                - If an unrecoverable error occurred this becomes true.
 9390:                               It is up to the caller to initialize this to false
 9391:                               if desired.
 9392:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
 9393:                               of the resource that could not be rendered by the ssi
 9394:                               call.
 9395:    ssi_error_message   - The error string fetched from the ssi response
 9396:                               in the event of an error.
 9397: 
 9398: 
 9399: =head1 HANDLER SUBROUTINE
 9400: 
 9401: ssi_with_retries()
 9402: 
 9403: =head1 SUBROUTINES
 9404: 
 9405: =over
 9406: 
 9407: =item scantron_get_correction() : 
 9408: 
 9409:    Builds the interface screen to interact with the operator to fix a
 9410:    specific error condition in a specific scanline
 9411: 
 9412:  Arguments:
 9413:     $r           - Apache request object
 9414:     $i           - number of the current scanline
 9415:     $scan_record - hash ref as returned from &scantron_parse_scanline()
 9416:     $scan_config - hash ref as returned from &get_scantron_config()
 9417:     $line        - full contents of the current scanline
 9418:     $error       - error condition, valid values are
 9419:                    'incorrectCODE', 'duplicateCODE',
 9420:                    'doublebubble', 'missingbubble',
 9421:                    'duplicateID', 'incorrectID'
 9422:     $arg         - extra information needed
 9423:        For errors:
 9424:          - duplicateID   - paper number that this studentID was seen before on
 9425:          - duplicateCODE - array ref of the paper numbers this CODE was
 9426:                            seen on before
 9427:          - incorrectCODE - current incorrect CODE 
 9428:          - doublebubble  - array ref of the bubble lines that have double
 9429:                            bubble errors
 9430:          - missingbubble - array ref of the bubble lines that have missing
 9431:                            bubble errors
 9432: 
 9433: =item  scantron_get_maxbubble() : 
 9434: 
 9435:    Arguments:
 9436:        $nav_error  - Reference to scalar which is a flag to indicate a
 9437:                       failure to retrieve a navmap object.
 9438:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
 9439:        calling routine should trap the error condition and display the warning
 9440:        found in &navmap_errormsg().
 9441: 
 9442:    Returns the maximum number of bubble lines that are expected to
 9443:    occur. Does this by walking the selected sequence rendering the
 9444:    resource and then checking &Apache::lonxml::get_problem_counter()
 9445:    for what the current value of the problem counter is.
 9446: 
 9447:    Caches the results to $env{'form.scantron_maxbubble'},
 9448:    $env{'form.scantron.bubble_lines.n'}, 
 9449:    $env{'form.scantron.first_bubble_line.n'} and
 9450:    $env{"form.scantron.sub_bubblelines.n"}
 9451:    which are the total number of bubble, lines, the number of bubble
 9452:    lines for response n and number of the first bubble line for response n,
 9453:    and a comma separated list of numbers of bubble lines for sub-questions
 9454:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
 9455: 
 9456: 
 9457: =item  scantron_validate_missingbubbles() : 
 9458: 
 9459:    Validates all scanlines in the selected file to not have any
 9460:     answers that don't have bubbles that have not been verified
 9461:     to be bubble free.
 9462: 
 9463: =item  scantron_process_students() : 
 9464: 
 9465:    Routine that does the actual grading of the bubble sheet information.
 9466: 
 9467:    The parsed scanline hash is added to %env 
 9468: 
 9469:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
 9470:    foreach resource , with the form data of
 9471: 
 9472: 	'submitted'     =>'scantron' 
 9473: 	'grade_target'  =>'grade',
 9474: 	'grade_username'=> username of student
 9475: 	'grade_domain'  => domain of student
 9476: 	'grade_courseid'=> of course
 9477: 	'grade_symb'    => symb of resource to grade
 9478: 
 9479:     This triggers a grading pass. The problem grading code takes care
 9480:     of converting the bubbled letter information (now in %env) into a
 9481:     valid submission.
 9482: 
 9483: =item  scantron_upload_scantron_data() :
 9484: 
 9485:     Creates the screen for adding a new bubble sheet data file to a course.
 9486: 
 9487: =item  scantron_upload_scantron_data_save() : 
 9488: 
 9489:    Adds a provided bubble information data file to the course if user
 9490:    has the correct privileges to do so. 
 9491: 
 9492: =item  valid_file() :
 9493: 
 9494:    Validates that the requested bubble data file exists in the course.
 9495: 
 9496: =item  scantron_download_scantron_data() : 
 9497: 
 9498:    Shows a list of the three internal files (original, corrected,
 9499:    skipped) for a specific bubble sheet data file that exists in the
 9500:    course.
 9501: 
 9502: =item  scantron_validate_ID() : 
 9503: 
 9504:    Validates all scanlines in the selected file to not have any
 9505:    invalid or underspecified student/employee IDs
 9506: 
 9507: =item navmap_errormsg() :
 9508: 
 9509:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
 9510:    Should be called whenever the request to instantiate a navmap object fails.  
 9511: 
 9512: =back
 9513: 
 9514: =cut

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