File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.736: download - view: text, annotated - select for diffs
Tue Jun 9 21:22:48 2015 UTC (8 years, 11 months ago) by damieng
Branches: MAIN
CVS tags: HEAD
fixed bug 6782, and escaped most localized messages used in Javascript blocks to make sure bugs like that do not happen again

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.736 2015/06/09 21:22:48 damieng Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: 
   30: 
   31: package Apache::grades;
   32: use strict;
   33: use Apache::style;
   34: use Apache::lonxml;
   35: use Apache::lonnet;
   36: use Apache::loncommon;
   37: use Apache::lonhtmlcommon;
   38: use Apache::lonnavmaps;
   39: use Apache::lonhomework;
   40: use Apache::lonpickcode;
   41: use Apache::loncoursedata;
   42: use Apache::lonmsg();
   43: use Apache::Constants qw(:common :http);
   44: use Apache::lonlocal;
   45: use Apache::lonenc;
   46: use Apache::lonstathelpers;
   47: use Apache::lonquickgrades;
   48: use Apache::bridgetask();
   49: use String::Similarity;
   50: use LONCAPA;
   51: 
   52: use POSIX qw(floor);
   53: 
   54: 
   55: 
   56: my %perm=();
   57: my %old_essays=();
   58: 
   59: #  These variables are used to recover from ssi errors
   60: 
   61: my $ssi_retries = 5;
   62: my $ssi_error;
   63: my $ssi_error_resource;
   64: my $ssi_error_message;
   65: 
   66: 
   67: sub ssi_with_retries {
   68:     my ($resource, $retries, %form) = @_;
   69:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
   70:     if ($response->is_error) {
   71: 	$ssi_error          = 1;
   72: 	$ssi_error_resource = $resource;
   73: 	$ssi_error_message  = $response->code . " " . $response->message;
   74:     }
   75: 
   76:     return $content;
   77: 
   78: }
   79: #
   80: #  Prodcuces an ssi retry failure error message to the user:
   81: #
   82: 
   83: sub ssi_print_error {
   84:     my ($r) = @_;
   85:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
   86:     $r->print('
   87: <br />
   88: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
   89: <p>
   90: '.&mt('Unable to retrieve a resource from a server:').'<br />
   91: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
   92: '.&mt('Error:').' '.$ssi_error_message.'
   93: </p>
   94: <p>'.
   95: &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 />'.
   96: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
   97: '</p>');
   98:     return;
   99: }
  100: 
  101: #
  102: # --- Retrieve the parts from the metadata file.---
  103: # Returns an array of everything that the resources stores away
  104: #
  105: 
  106: sub getpartlist {
  107:     my ($symb,$errorref) = @_;
  108: 
  109:     my $navmap   = Apache::lonnavmaps::navmap->new();
  110:     unless (ref($navmap)) {
  111:         if (ref($errorref)) { 
  112:             $$errorref = 'navmap';
  113:             return;
  114:         }
  115:     }
  116:     my $res      = $navmap->getBySymb($symb);
  117:     my $partlist = $res->parts();
  118:     my $url      = $res->src();
  119:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
  120: 
  121:     my @stores;
  122:     foreach my $part (@{ $partlist }) {
  123: 	foreach my $key (@metakeys) {
  124: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
  125: 	}
  126:     }
  127:     return @stores;
  128: }
  129: 
  130: #--- Format fullname, username:domain if different for display
  131: #--- Use anywhere where the student names are listed
  132: sub nameUserString {
  133:     my ($type,$fullname,$uname,$udom) = @_;
  134:     if ($type eq 'header') {
  135: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
  136:     } else {
  137: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
  138: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
  139:     }
  140: }
  141: 
  142: #--- Get the partlist and the response type for a given problem. ---
  143: #--- Indicate if a response type is coded handgraded or not. ---
  144: #--- Sets response_error pointer to "1" if navmaps object broken ---
  145: sub response_type {
  146:     my ($symb,$response_error) = @_;
  147: 
  148:     my $navmap = Apache::lonnavmaps::navmap->new();
  149:     unless (ref($navmap)) {
  150:         if (ref($response_error)) {
  151:             $$response_error = 1;
  152:         }
  153:         return;
  154:     }
  155:     my $res = $navmap->getBySymb($symb);
  156:     unless (ref($res)) {
  157:         $$response_error = 1;
  158:         return;
  159:     }
  160:     my $partlist = $res->parts();
  161:     my %vPart = 
  162: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
  163:     my (%response_types,%handgrade);
  164:     foreach my $part (@{ $partlist }) {
  165: 	next if (%vPart && !exists($vPart{$part}));
  166: 
  167: 	my @types = $res->responseType($part);
  168: 	my @ids = $res->responseIds($part);
  169: 	for (my $i=0; $i < scalar(@ids); $i++) {
  170: 	    $response_types{$part}{$ids[$i]} = $types[$i];
  171: 	    $handgrade{$part.'_'.$ids[$i]} = 
  172: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
  173: 				     '.handgrade',$symb);
  174: 	}
  175:     }
  176:     return ($partlist,\%handgrade,\%response_types);
  177: }
  178: 
  179: sub flatten_responseType {
  180:     my ($responseType) = @_;
  181:     my @part_response_id =
  182: 	map { 
  183: 	    my $part = $_;
  184: 	    map {
  185: 		[$part,$_]
  186: 		} sort(keys(%{ $responseType->{$part} }));
  187: 	} sort(keys(%$responseType));
  188:     return @part_response_id;
  189: }
  190: 
  191: sub get_display_part {
  192:     my ($partID,$symb)=@_;
  193:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
  194:     if (defined($display) and $display ne '') {
  195:         $display.= ' (<span class="LC_internal_info">'
  196:                   .&mt('Part ID: [_1]',$partID).'</span>)';
  197:     } else {
  198: 	$display=$partID;
  199:     }
  200:     return $display;
  201: }
  202: 
  203: sub reset_caches {
  204:     &reset_analyze_cache();
  205:     &reset_perm();
  206:     &reset_old_essays();
  207: }
  208: 
  209: {
  210:     my %analyze_cache;
  211:     my %analyze_cache_formkeys;
  212: 
  213:     sub reset_analyze_cache {
  214: 	undef(%analyze_cache);
  215:         undef(%analyze_cache_formkeys);
  216:     }
  217: 
  218:     sub get_analyze {
  219: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash,$type,$trial,$rndseed,$bubbles_per_row)=@_;
  220: 	my $key = "$symb\0$uname\0$udom";
  221:         if ($type eq 'randomizetry') {
  222:             if ($trial ne '') {
  223:                 $key .= "\0".$trial;
  224:             }
  225:         }
  226: 	if (exists($analyze_cache{$key})) {
  227:             my $getupdate = 0;
  228:             if (ref($add_to_hash) eq 'HASH') {
  229:                 foreach my $item (keys(%{$add_to_hash})) {
  230:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
  231:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
  232:                             $getupdate = 1;
  233:                             last;
  234:                         }
  235:                     } else {
  236:                         $getupdate = 1;
  237:                     }
  238:                 }
  239:             }
  240:             if (!$getupdate) {
  241:                 return $analyze_cache{$key};
  242:             }
  243:         }
  244: 
  245: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
  246: 	$url=&Apache::lonnet::clutter($url);
  247:         my %form = ('grade_target'      => 'analyze',
  248:                     'grade_domain'      => $udom,
  249:                     'grade_symb'        => $symb,
  250:                     'grade_courseid'    =>  $env{'request.course.id'},
  251:                     'grade_username'    => $uname,
  252:                     'grade_noincrement' => $no_increment);
  253:         if ($bubbles_per_row ne '') {
  254:             $form{'bubbles_per_row'} = $bubbles_per_row;
  255:         }
  256:         if ($type eq 'randomizetry') {
  257:             $form{'grade_questiontype'} = $type;
  258:             if ($rndseed ne '') {
  259:                 $form{'grade_rndseed'} = $rndseed;
  260:             }
  261:         }
  262:         if (ref($add_to_hash)) {
  263:             %form = (%form,%{$add_to_hash});
  264:         }
  265: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
  266: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
  267: 	my %analyze=&Apache::lonnet::str2hash($subresult);
  268:         if (ref($add_to_hash) eq 'HASH') {
  269:             $analyze_cache_formkeys{$key} = $add_to_hash;
  270:         } else {
  271:             $analyze_cache_formkeys{$key} = {};
  272:         }
  273: 	return $analyze_cache{$key} = \%analyze;
  274:     }
  275: 
  276:     sub get_order {
  277: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment,$type,$trial,$rndseed)=@_;
  278: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment,undef,$type,$trial,$rndseed);
  279: 	return $analyze->{"$partid.$respid.shown"};
  280:     }
  281: 
  282:     sub get_radiobutton_correct_foil {
  283: 	my ($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed)=@_;
  284: 	my $analyze = &get_analyze($symb,$uname,$udom,undef,undef,$type,$trial,$rndseed);
  285:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom,undef,$type,$trial,$rndseed);
  286:         if (ref($foils) eq 'ARRAY') {
  287: 	    foreach my $foil (@{$foils}) {
  288: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
  289: 		    return $foil;
  290: 	        }
  291: 	    }
  292: 	}
  293:     }
  294: 
  295:     sub scantron_partids_tograde {
  296:         my ($resource,$cid,$uname,$udom,$check_for_randomlist,$bubbles_per_row) = @_;
  297:         my (%analysis,@parts);
  298:         if (ref($resource)) {
  299:             my $symb = $resource->symb();
  300:             my $add_to_form;
  301:             if ($check_for_randomlist) {
  302:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
  303:             }
  304:             my $analyze = 
  305:                 &get_analyze($symb,$uname,$udom,undef,$add_to_form,
  306:                              undef,undef,undef,$bubbles_per_row);
  307:             if (ref($analyze) eq 'HASH') {
  308:                 %analysis = %{$analyze};
  309:             }
  310:             if (ref($analysis{'parts'}) eq 'ARRAY') {
  311:                 foreach my $part (@{$analysis{'parts'}}) {
  312:                     my ($id,$respid) = split(/\./,$part);
  313:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
  314:                         push(@parts,$part);
  315:                     }
  316:                 }
  317:             }
  318:         }
  319:         return (\%analysis,\@parts);
  320:     }
  321: 
  322: }
  323: 
  324: #--- Clean response type for display
  325: #--- Currently filters option/rank/radiobutton/match/essay/Task
  326: #        response types only.
  327: sub cleanRecord {
  328:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
  329: 	$uname,$udom,$type,$trial,$rndseed) = @_;
  330:     my $grayFont = '<span class="LC_internal_info">';
  331:     if ($response =~ /^(option|rank)$/) {
  332: 	my %answer=&Apache::lonnet::str2hash($answer);
  333:         my @answer = %answer;
  334:         %answer = map {&HTML::Entities::encode($_, '"<>&')}  @answer;
  335: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  336: 	my ($toprow,$bottomrow);
  337: 	foreach my $foil (@$order) {
  338: 	    if ($grading{$foil} == 1) {
  339: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
  340: 	    } else {
  341: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
  342: 	    }
  343: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  344: 	}
  345: 	return '<blockquote><table border="1">'.
  346: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  347: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  348: 	    $bottomrow.'</tr></table></blockquote>';
  349:     } elsif ($response eq 'match') {
  350: 	my %answer=&Apache::lonnet::str2hash($answer);
  351:         my @answer = %answer;
  352:         %answer = map {&HTML::Entities::encode($_, '"<>&')}  @answer;
  353: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  354: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
  355: 	my ($toprow,$middlerow,$bottomrow);
  356: 	foreach my $foil (@$order) {
  357: 	    my $item=shift(@items);
  358: 	    if ($grading{$foil} == 1) {
  359: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
  360: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
  361: 	    } else {
  362: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
  363: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
  364: 	    }
  365: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  366: 	}
  367: 	return '<blockquote><table border="1">'.
  368: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  369: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
  370: 	    $middlerow.'</tr>'.
  371: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  372: 	    $bottomrow.'</tr></table></blockquote>';
  373:     } elsif ($response eq 'radiobutton') {
  374: 	my %answer=&Apache::lonnet::str2hash($answer);
  375:         my @answer = %answer;
  376:         %answer = map {&HTML::Entities::encode($_, '"<>&')}  @answer;
  377: 	my ($toprow,$bottomrow);
  378: 	my $correct = 
  379: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
  380: 	foreach my $foil (@$order) {
  381: 	    if (exists($answer{$foil})) {
  382: 		if ($foil eq $correct) {
  383: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
  384: 		} else {
  385: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
  386: 		}
  387: 	    } else {
  388: 		$toprow.='<td>'.&mt('false').'</td>';
  389: 	    }
  390: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  391: 	}
  392: 	return '<blockquote><table border="1">'.
  393: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  394: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  395: 	    $bottomrow.'</tr></table></blockquote>';
  396:     } elsif ($response eq 'essay') {
  397: 	if (! exists ($env{'form.'.$symb})) {
  398: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
  399: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
  400: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
  401: 
  402: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
  403: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
  404: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
  405: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
  406: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
  407: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
  408: 	}
  409: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
  410: 
  411:     } elsif ( $response eq 'organic') {
  412:         my $result=&mt('Smile representation: [_1]',
  413:                            '"<tt>'.&HTML::Entities::encode($answer, '"<>&').'</tt>"');
  414: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
  415: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
  416: 	return $result;
  417:     } elsif ( $response eq 'Task') {
  418: 	if ( $answer eq 'SUBMITTED') {
  419: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
  420: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
  421: 	    return $result;
  422: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
  423: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
  424: 			       keys(%{$record}));
  425: 	    return join('<br />',($version,@matches));
  426: 			       
  427: 			       
  428: 	} else {
  429: 	    my $result =
  430: 		'<p>'
  431: 		.&mt('Overall result: [_1]',
  432: 		     $record->{$version."resource.$respid.$partid.status"})
  433: 		.'</p>';
  434: 	    
  435: 	    $result .= '<ul>';
  436: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
  437: 			     keys(%{$record}));
  438: 	    foreach my $grade (sort(@grade)) {
  439: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
  440: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
  441: 				     $dim, $record->{$grade}).
  442: 			  '</li>';
  443: 	    }
  444: 	    $result.='</ul>';
  445: 	    return $result;
  446: 	}
  447:     } elsif ( $response =~ m/(?:numerical|formula|custom)/) {
  448:         # Respect multiple input fields, see Bug #5409
  449: 	$answer = 
  450: 	    &Apache::loncommon::format_previous_attempt_value('submission',
  451: 							      $answer);
  452: 	return $answer;
  453:     }
  454:     return &HTML::Entities::encode($answer, '"<>&');
  455: }
  456: 
  457: #-- A couple of common js functions
  458: sub commonJSfunctions {
  459:     my $request = shift;
  460:     $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
  461:     function radioSelection(radioButton) {
  462: 	var selection=null;
  463: 	if (radioButton.length > 1) {
  464: 	    for (var i=0; i<radioButton.length; i++) {
  465: 		if (radioButton[i].checked) {
  466: 		    return radioButton[i].value;
  467: 		}
  468: 	    }
  469: 	} else {
  470: 	    if (radioButton.checked) return radioButton.value;
  471: 	}
  472: 	return selection;
  473:     }
  474: 
  475:     function pullDownSelection(selectOne) {
  476: 	var selection="";
  477: 	if (selectOne.length > 1) {
  478: 	    for (var i=0; i<selectOne.length; i++) {
  479: 		if (selectOne[i].selected) {
  480: 		    return selectOne[i].value;
  481: 		}
  482: 	    }
  483: 	} else {
  484:             // only one value it must be the selected one
  485: 	    return selectOne.value;
  486: 	}
  487:     }
  488: COMMONJSFUNCTIONS
  489: }
  490: 
  491: #--- Dumps the class list with usernames,list of sections,
  492: #--- section, ids and fullnames for each user.
  493: sub getclasslist {
  494:     my ($getsec,$filterlist,$getgroup) = @_;
  495:     my @getsec;
  496:     my @getgroup;
  497:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  498:     if (!ref($getsec)) {
  499: 	if ($getsec ne '' && $getsec ne 'all') {
  500: 	    @getsec=($getsec);
  501: 	}
  502:     } else {
  503: 	@getsec=@{$getsec};
  504:     }
  505:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
  506:     if (!ref($getgroup)) {
  507: 	if ($getgroup ne '' && $getgroup ne 'all') {
  508: 	    @getgroup=($getgroup);
  509: 	}
  510:     } else {
  511: 	@getgroup=@{$getgroup};
  512:     }
  513:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
  514: 
  515:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
  516:     # Bail out if we were unable to get the classlist
  517:     return if (! defined($classlist));
  518:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
  519:     #
  520:     my %sections;
  521:     my %fullnames;
  522:     foreach my $student (keys(%$classlist)) {
  523:         my $end      = 
  524:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
  525:         my $start    = 
  526:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
  527:         my $id       = 
  528:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
  529:         my $section  = 
  530:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
  531:         my $fullname = 
  532:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
  533:         my $status   = 
  534:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
  535:         my $group   = 
  536:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
  537: 	# filter students according to status selected
  538: 	if ($filterlist && (!($stu_status =~ /Any/))) {
  539: 	    if (!($stu_status =~ $status)) {
  540: 		delete($classlist->{$student});
  541: 		next;
  542: 	    }
  543: 	}
  544: 	# filter students according to groups selected
  545: 	my @stu_groups = split(/,/,$group);
  546: 	if (@getgroup) {
  547: 	    my $exclude = 1;
  548: 	    foreach my $grp (@getgroup) {
  549: 	        foreach my $stu_group (@stu_groups) {
  550: 	            if ($stu_group eq $grp) {
  551: 	                $exclude = 0;
  552:     	            } 
  553: 	        }
  554:     	        if (($grp eq 'none') && !$group) {
  555:         	        $exclude = 0;
  556:         	}
  557: 	    }
  558: 	    if ($exclude) {
  559: 	        delete($classlist->{$student});
  560: 	    }
  561: 	}
  562: 	$section = ($section ne '' ? $section : 'none');
  563: 	if (&canview($section)) {
  564: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
  565: 		$sections{$section}++;
  566: 		if ($classlist->{$student}) {
  567: 		    $fullnames{$student}=$fullname;
  568: 		}
  569: 	    } else {
  570: 		delete($classlist->{$student});
  571: 	    }
  572: 	} else {
  573: 	    delete($classlist->{$student});
  574: 	}
  575:     }
  576:     my %seen = ();
  577:     my @sections = sort(keys(%sections));
  578:     return ($classlist,\@sections,\%fullnames);
  579: }
  580: 
  581: sub canmodify {
  582:     my ($sec)=@_;
  583:     if ($perm{'mgr'}) {
  584: 	if (!defined($perm{'mgr_section'})) {
  585: 	    # can modify whole class
  586: 	    return 1;
  587: 	} else {
  588: 	    if ($sec eq $perm{'mgr_section'}) {
  589: 		#can modify the requested section
  590: 		return 1;
  591: 	    } else {
  592: 		# can't modify the request section
  593: 		return 0;
  594: 	    }
  595: 	}
  596:     }
  597:     #can't modify
  598:     return 0;
  599: }
  600: 
  601: sub canview {
  602:     my ($sec)=@_;
  603:     if ($perm{'vgr'}) {
  604: 	if (!defined($perm{'vgr_section'})) {
  605: 	    # can modify whole class
  606: 	    return 1;
  607: 	} else {
  608: 	    if ($sec eq $perm{'vgr_section'}) {
  609: 		#can modify the requested section
  610: 		return 1;
  611: 	    } else {
  612: 		# can't modify the request section
  613: 		return 0;
  614: 	    }
  615: 	}
  616:     }
  617:     #can't modify
  618:     return 0;
  619: }
  620: 
  621: #--- Retrieve the grade status of a student for all the parts
  622: sub student_gradeStatus {
  623:     my ($symb,$udom,$uname,$partlist) = @_;
  624:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
  625:     my %partstatus = ();
  626:     foreach (@$partlist) {
  627: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
  628: 	$status              = 'nothing' if ($status eq '');
  629: 	$partstatus{$_}      = $status;
  630: 	my $subkey           = "resource.$_.submitted_by";
  631: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
  632:     }
  633:     return %partstatus;
  634: }
  635: 
  636: # hidden form and javascript that calls the form
  637: # Use by verifyscript and viewgrades
  638: # Shows a student's view of problem and submission
  639: sub jscriptNform {
  640:     my ($symb) = @_;
  641:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  642:     my $jscript= &Apache::lonhtmlcommon::scripttag(
  643: 	'    function viewOneStudent(user,domain) {'."\n".
  644: 	'	document.onestudent.student.value = user;'."\n".
  645: 	'	document.onestudent.userdom.value = domain;'."\n".
  646: 	'	document.onestudent.submit();'."\n".
  647: 	'    }'."\n".
  648: 	"\n");
  649:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
  650: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  651: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
  652: 	'<input type="hidden" name="command" value="submission" />'."\n".
  653: 	'<input type="hidden" name="student" value="" />'."\n".
  654: 	'<input type="hidden" name="userdom" value="" />'."\n".
  655: 	'</form>'."\n";
  656:     return $jscript;
  657: }
  658: 
  659: 
  660: 
  661: # Given the score (as a number [0-1] and the weight) what is the final
  662: # point value? This function will round to the nearest tenth, third,
  663: # or quarter if one of those is within the tolerance of .00001.
  664: sub compute_points {
  665:     my ($score, $weight) = @_;
  666:     
  667:     my $tolerance = .00001;
  668:     my $points = $score * $weight;
  669: 
  670:     # Check for nearness to 1/x.
  671:     my $check_for_nearness = sub {
  672:         my ($factor) = @_;
  673:         my $num = ($points * $factor) + $tolerance;
  674:         my $floored_num = floor($num);
  675:         if ($num - $floored_num < 2 * $tolerance * $factor) {
  676:             return $floored_num / $factor;
  677:         }
  678:         return $points;
  679:     };
  680: 
  681:     $points = $check_for_nearness->(10);
  682:     $points = $check_for_nearness->(3);
  683:     $points = $check_for_nearness->(4);
  684:     
  685:     return $points;
  686: }
  687: 
  688: #------------------ End of general use routines --------------------
  689: 
  690: #
  691: # Find most similar essay
  692: #
  693: 
  694: sub most_similar {
  695:     my ($uname,$udom,$symb,$uessay)=@_;
  696: 
  697:     unless ($symb) { return ''; }
  698: 
  699:     unless (ref($old_essays{$symb}) eq 'HASH') { return ''; }
  700: 
  701: # ignore spaces and punctuation
  702: 
  703:     $uessay=~s/\W+/ /gs;
  704: 
  705: # ignore empty submissions (occuring when only files are sent)
  706: 
  707:     unless ($uessay=~/\w+/s) { return ''; }
  708: 
  709: # these will be returned. Do not care if not at least 50 percent similar
  710:     my $limit=0.6;
  711:     my $sname='';
  712:     my $sdom='';
  713:     my $scrsid='';
  714:     my $sessay='';
  715: # go through all essays ...
  716:     foreach my $tkey (keys(%{$old_essays{$symb}})) {
  717: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
  718: # ... except the same student
  719:         next if (($tname eq $uname) && ($tdom eq $udom));
  720: 	my $tessay=$old_essays{$symb}{$tkey};
  721: 	$tessay=~s/\W+/ /gs;
  722: # String similarity gives up if not even limit
  723: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
  724: # Found one
  725: 	if ($tsimilar>$limit) {
  726: 	    $limit=$tsimilar;
  727: 	    $sname=$tname;
  728: 	    $sdom=$tdom;
  729: 	    $scrsid=$tcrsid;
  730: 	    $sessay=$old_essays{$symb}{$tkey};
  731: 	}
  732:     }
  733:     if ($limit>0.6) {
  734:        return ($sname,$sdom,$scrsid,$sessay,$limit);
  735:     } else {
  736:        return ('','','','',0);
  737:     }
  738: }
  739: 
  740: #-------------------------------------------------------------------
  741: 
  742: #------------------------------------ Receipt Verification Routines
  743: #
  744: 
  745: sub initialverifyreceipt {
  746:    my ($request,$symb) = @_;
  747:    &commonJSfunctions($request);
  748:    return '<form name="gradingMenu" action=""><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
  749:         &Apache::lonnet::recprefix($env{'request.course.id'}).
  750:         '-<input type="text" name="receipt" size="4" />'.
  751:         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  752:         '<input type="hidden" name="command" value="verify" />'.
  753:         "</form>\n";
  754: }
  755: 
  756: #--- Check whether a receipt number is valid.---
  757: sub verifyreceipt {
  758:     my ($request,$symb)  = @_;
  759: 
  760:     my $courseid = $env{'request.course.id'};
  761:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
  762: 	$env{'form.receipt'};
  763:     $receipt     =~ s/[^\-\d]//g;
  764: 
  765:     my $title.=
  766: 	'<h3><span class="LC_info">'.
  767: 	&mt('Verifying Receipt Number [_1]',$receipt).
  768: 	'</span></h3>'."\n";
  769: 
  770:     my ($string,$contents,$matches) = ('','',0);
  771:     my (undef,undef,$fullname) = &getclasslist('all','0');
  772:     
  773:     my $receiptparts=0;
  774:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
  775: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
  776:     my $parts=['0'];
  777:     if ($receiptparts) {
  778:         my $res_error; 
  779:         ($parts)=&response_type($symb,\$res_error);
  780:         if ($res_error) {
  781:             return &navmap_errormsg();
  782:         } 
  783:     }
  784:     
  785:     my $header = 
  786: 	&Apache::loncommon::start_data_table().
  787: 	&Apache::loncommon::start_data_table_header_row().
  788: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
  789: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
  790: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
  791:     if ($receiptparts) {
  792: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
  793:     }
  794:     $header.=
  795: 	&Apache::loncommon::end_data_table_header_row();
  796: 
  797:     foreach (sort 
  798: 	     {
  799: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  800: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  801: 		 }
  802: 		 return $a cmp $b;
  803: 	     } (keys(%$fullname))) {
  804: 	my ($uname,$udom)=split(/\:/);
  805: 	foreach my $part (@$parts) {
  806: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
  807: 		$contents.=
  808: 		    &Apache::loncommon::start_data_table_row().
  809: 		    '<td>&nbsp;'."\n".
  810: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
  811: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
  812: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
  813: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
  814: 		if ($receiptparts) {
  815: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
  816: 		}
  817: 		$contents.= 
  818: 		    &Apache::loncommon::end_data_table_row()."\n";
  819: 		
  820: 		$matches++;
  821: 	    }
  822: 	}
  823:     }
  824:     if ($matches == 0) {
  825:         $string = $title
  826:                  .'<p class="LC_warning">'
  827:                  .&mt('No match found for the above receipt number.')
  828:                  .'</p>';
  829:     } else {
  830: 	$string = &jscriptNform($symb).$title.
  831: 	    '<p>'.
  832: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
  833: 	    '</p>'.
  834: 	    $header.
  835: 	    $contents.
  836: 	    &Apache::loncommon::end_data_table()."\n";
  837:     }
  838:     return $string;
  839: }
  840: 
  841: #--- This is called by a number of programs.
  842: #--- Called from the Grading Menu - View/Grade an individual student
  843: #--- Also called directly when one clicks on the subm button 
  844: #    on the problem page.
  845: sub listStudents {
  846:     my ($request,$symb,$submitonly) = @_;
  847: 
  848:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
  849:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
  850:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
  851:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
  852:     unless ($submitonly) {
  853:        $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
  854:     }
  855: 
  856:     my $result='';
  857:     my $res_error;
  858:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
  859: 
  860:     my %js_lt = &Apache::lonlocal::texthash (
  861: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
  862: 		'single'   => 'Please select the student before clicking on the Next button.',
  863: 	     );
  864:     &js_escape(\%js_lt);
  865:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
  866:     function checkSelect(checkBox) {
  867: 	var ctr=0;
  868: 	var sense="";
  869: 	if (checkBox.length > 1) {
  870: 	    for (var i=0; i<checkBox.length; i++) {
  871: 		if (checkBox[i].checked) {
  872: 		    ctr++;
  873: 		}
  874: 	    }
  875: 	    sense = '$js_lt{'multiple'}';
  876: 	} else {
  877: 	    if (checkBox.checked) {
  878: 		ctr = 1;
  879: 	    }
  880: 	    sense = '$js_lt{'single'}';
  881: 	}
  882: 	if (ctr == 0) {
  883: 	    alert(sense);
  884: 	    return false;
  885: 	}
  886: 	document.gradesub.submit();
  887:     }
  888: 
  889:     function reLoadList(formname) {
  890: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
  891: 	formname.command.value = 'submission';
  892: 	formname.submit();
  893:     }
  894: LISTJAVASCRIPT
  895: 
  896:     &commonJSfunctions($request);
  897:     $request->print($result);
  898: 
  899:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
  900: 	"\n";
  901: 	
  902:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
  903:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
  904:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
  905:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
  906:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
  907:                   .&Apache::lonhtmlcommon::row_closure();
  908:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
  909:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
  910:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
  911:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
  912:                   .&Apache::lonhtmlcommon::row_closure();
  913: 
  914:     my $submission_options;
  915:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  916:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
  917:     $env{'form.Status'} = $saveStatus;
  918:     $submission_options.=
  919:         '<span class="LC_nobreak">'.
  920:         '<label><input type="radio" name="lastSub" value="lastonly" /> '.
  921:         &mt('last submission').' </label></span>'."\n".
  922:         '<span class="LC_nobreak">'.
  923:         '<label><input type="radio" name="lastSub" value="last" /> '.
  924:         &mt('last submission with details').' </label></span>'."\n".
  925:         '<span class="LC_nobreak">'.
  926:         '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.
  927:         &mt('all submissions').'</label></span>'."\n".
  928:         '<span class="LC_nobreak">'.
  929:         '<label><input type="radio" name="lastSub" value="all" /> '.
  930:         &mt('all submissions with details').'</label></span>';
  931:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
  932:                   .$submission_options
  933:                   .&Apache::lonhtmlcommon::row_closure();
  934: 
  935:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
  936:                   .'<select name="increment">'
  937:                   .'<option value="1">'.&mt('Whole Points').'</option>'
  938:                   .'<option value=".5">'.&mt('Half Points').'</option>'
  939:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
  940:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
  941:                   .'</select>'
  942:                   .&Apache::lonhtmlcommon::row_closure();
  943: 
  944:     $gradeTable .= 
  945:         &build_section_inputs().
  946: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
  947: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  948: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
  949: 
  950:     if (exists($env{'form.Status'})) {
  951: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
  952:     } else {
  953:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
  954:                       .&Apache::lonhtmlcommon::StatusOptions(
  955:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
  956:                       .&Apache::lonhtmlcommon::row_closure();
  957:     }
  958: 
  959:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
  960:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
  961:                   .&Apache::lonhtmlcommon::row_closure(1)
  962:                   .&Apache::lonhtmlcommon::end_pick_box();
  963: 
  964:     $gradeTable .= '<p>'
  965:                   .&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"
  966:                   .'<input type="hidden" name="command" value="processGroup" />'
  967:                   .'</p>';
  968: 
  969: # checkall buttons
  970:     $gradeTable.=&check_script('gradesub', 'stuinfo');
  971:     $gradeTable.='<input type="button" '."\n".
  972:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
  973:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
  974:     $gradeTable.=&check_buttons();
  975:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
  976:     $gradeTable.= &Apache::loncommon::start_data_table().
  977: 	&Apache::loncommon::start_data_table_header_row();
  978:     my $loop = 0;
  979:     while ($loop < 2) {
  980: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
  981: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
  982: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
  983: 	    foreach my $part (sort(@$partlist)) {
  984: 		my $display_part=
  985: 		    &get_display_part((split(/_/,$part))[0],$symb);
  986: 		$gradeTable.=
  987: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
  988: 	    }
  989: 	} elsif ($submitonly eq 'queued') {
  990: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
  991: 	}
  992: 	$loop++;
  993: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
  994:     }
  995:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
  996: 
  997:     my $ctr = 0;
  998:     foreach my $student (sort 
  999: 			 {
 1000: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 1001: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 1002: 			     }
 1003: 			     return $a cmp $b;
 1004: 			 }
 1005: 			 (keys(%$fullname))) {
 1006: 	my ($uname,$udom) = split(/:/,$student);
 1007: 
 1008: 	my %status = ();
 1009: 
 1010: 	if ($submitonly eq 'queued') {
 1011: 	    my %queue_status = 
 1012: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 1013: 							$udom,$uname);
 1014: 	    next if (!defined($queue_status{'gradingqueue'}));
 1015: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
 1016: 	}
 1017: 
 1018: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1019: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
 1020: 	    my $submitted = 0;
 1021: 	    my $graded = 0;
 1022: 	    my $incorrect = 0;
 1023: 	    foreach (keys(%status)) {
 1024: 		$submitted = 1 if ($status{$_} ne 'nothing');
 1025: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
 1026: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
 1027: 		
 1028: 		my ($foo,$partid,$foo1) = split(/\./,$_);
 1029: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 1030: 		    $submitted = 0;
 1031: 		    my ($part)=split(/\./,$partid);
 1032: 		    $gradeTable.='<input type="hidden" name="'.
 1033: 			$student.':'.$part.':submitted_by" value="'.
 1034: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
 1035: 		}
 1036: 	    }
 1037: 	    
 1038: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 1039: 				     $submitonly eq 'incorrect' ||
 1040: 				     $submitonly eq 'graded'));
 1041: 	    next if (!$graded && ($submitonly eq 'graded'));
 1042: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 1043: 	}
 1044: 
 1045: 	$ctr++;
 1046: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
 1047:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
 1048: 	if ( $perm{'vgr'} eq 'F' ) {
 1049: 	    if ($ctr%2 ==1) {
 1050: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
 1051: 	    }
 1052: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
 1053:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
 1054:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
 1055: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
 1056: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
 1057: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
 1058: 
 1059: 	    if ($submitonly ne 'all') {
 1060: 		foreach (sort(keys(%status))) {
 1061: 		    next if ($_ =~ /^resource.*?submitted_by$/);
 1062: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
 1063: 		}
 1064: 	    }
 1065: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
 1066: 	    if ($ctr%2 ==0) {
 1067: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
 1068: 	    }
 1069: 	}
 1070:     }
 1071:     if ($ctr%2 ==1) {
 1072: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
 1073: 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1074: 		foreach (@$partlist) {
 1075: 		    $gradeTable.='<td>&nbsp;</td>';
 1076: 		}
 1077: 	    } elsif ($submitonly eq 'queued') {
 1078: 		$gradeTable.='<td>&nbsp;</td>';
 1079: 	    }
 1080: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
 1081:     }
 1082: 
 1083:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
 1084:         '<input type="button" '.
 1085:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
 1086:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
 1087:     if ($ctr == 0) {
 1088: 	my $num_students=(scalar(keys(%$fullname)));
 1089: 	if ($num_students eq 0) {
 1090: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
 1091: 	} else {
 1092: 	    my $submissions='submissions';
 1093: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
 1094: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
 1095: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
 1096: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
 1097: 		&mt('No '.$submissions.' found for this resource for any students. ([quant,_1,student] checked for '.$submissions.')',
 1098: 		    $num_students).
 1099: 		'</span><br />';
 1100: 	}
 1101:     } elsif ($ctr == 1) {
 1102: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
 1103:     }
 1104:     $request->print($gradeTable);
 1105:     return '';
 1106: }
 1107: 
 1108: #---- Called from the listStudents routine
 1109: 
 1110: sub check_script {
 1111:     my ($form, $type)=@_;
 1112:     my $chkallscript= &Apache::lonhtmlcommon::scripttag('
 1113:     function checkall() {
 1114:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1115:             ele = document.forms.'.$form.'.elements[i];
 1116:             if (ele.name == "'.$type.'") {
 1117:             document.forms.'.$form.'.elements[i].checked=true;
 1118:                                        }
 1119:         }
 1120:     }
 1121: 
 1122:     function checksec() {
 1123:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1124:             ele = document.forms.'.$form.'.elements[i];
 1125:            string = document.forms.'.$form.'.chksec.value;
 1126:            if
 1127:           (ele.value.indexOf(":::SECTION"+string)>0) {
 1128:               document.forms.'.$form.'.elements[i].checked=true;
 1129:             }
 1130:         }
 1131:     }
 1132: 
 1133: 
 1134:     function uncheckall() {
 1135:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1136:             ele = document.forms.'.$form.'.elements[i];
 1137:             if (ele.name == "'.$type.'") {
 1138:             document.forms.'.$form.'.elements[i].checked=false;
 1139:                                        }
 1140:         }
 1141:     }
 1142: 
 1143: '."\n");
 1144:     return $chkallscript;
 1145: }
 1146: 
 1147: sub check_buttons {
 1148:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
 1149:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
 1150:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
 1151:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
 1152:     return $buttons;
 1153: }
 1154: 
 1155: #     Displays the submissions for one student or a group of students
 1156: sub processGroup {
 1157:     my ($request,$symb)  = @_;
 1158:     my $ctr        = 0;
 1159:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1160:     my $total      = scalar(@stuchecked)-1;
 1161: 
 1162:     foreach my $student (@stuchecked) {
 1163: 	my ($uname,$udom,$fullname) = split(/:/,$student);
 1164: 	$env{'form.student'}        = $uname;
 1165: 	$env{'form.userdom'}        = $udom;
 1166: 	$env{'form.fullname'}       = $fullname;
 1167: 	&submission($request,$ctr,$total,$symb);
 1168: 	$ctr++;
 1169:     }
 1170:     return '';
 1171: }
 1172: 
 1173: #------------------------------------------------------------------------------------
 1174: #
 1175: #-------------------------- Next few routines handles grading by student, essentially
 1176: #                           handles essay response type problem/part
 1177: #
 1178: #--- Javascript to handle the submission page functionality ---
 1179: sub sub_page_js {
 1180:     my $request = shift;
 1181:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 1182:     &js_escape(\$alertmsg);
 1183:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1184:     function updateRadio(formname,id,weight) {
 1185: 	var gradeBox = formname["GD_BOX"+id];
 1186: 	var radioButton = formname["RADVAL"+id];
 1187: 	var oldpts = formname["oldpts"+id].value;
 1188: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
 1189: 	gradeBox.value = pts;
 1190: 	var resetbox = false;
 1191: 	if (isNaN(pts) || pts < 0) {
 1192: 	    alert("$alertmsg"+pts);
 1193: 	    for (var i=0; i<radioButton.length; i++) {
 1194: 		if (radioButton[i].checked) {
 1195: 		    gradeBox.value = i;
 1196: 		    resetbox = true;
 1197: 		}
 1198: 	    }
 1199: 	    if (!resetbox) {
 1200: 		formtextbox.value = "";
 1201: 	    }
 1202: 	    return;
 1203: 	}
 1204: 
 1205: 	if (pts > weight) {
 1206: 	    var resp = confirm("You entered a value ("+pts+
 1207: 			       ") greater than the weight for the part. Accept?");
 1208: 	    if (resp == false) {
 1209: 		gradeBox.value = oldpts;
 1210: 		return;
 1211: 	    }
 1212: 	}
 1213: 
 1214: 	for (var i=0; i<radioButton.length; i++) {
 1215: 	    radioButton[i].checked=false;
 1216: 	    if (pts == i && pts != "") {
 1217: 		radioButton[i].checked=true;
 1218: 	    }
 1219: 	}
 1220: 	updateSelect(formname,id);
 1221: 	formname["stores"+id].value = "0";
 1222:     }
 1223: 
 1224:     function writeBox(formname,id,pts) {
 1225: 	var gradeBox = formname["GD_BOX"+id];
 1226: 	if (checkSolved(formname,id) == 'update') {
 1227: 	    gradeBox.value = pts;
 1228: 	} else {
 1229: 	    var oldpts = formname["oldpts"+id].value;
 1230: 	    gradeBox.value = oldpts;
 1231: 	    var radioButton = formname["RADVAL"+id];
 1232: 	    for (var i=0; i<radioButton.length; i++) {
 1233: 		radioButton[i].checked=false;
 1234: 		if (i == oldpts) {
 1235: 		    radioButton[i].checked=true;
 1236: 		}
 1237: 	    }
 1238: 	}
 1239: 	formname["stores"+id].value = "0";
 1240: 	updateSelect(formname,id);
 1241: 	return;
 1242:     }
 1243: 
 1244:     function clearRadBox(formname,id) {
 1245: 	if (checkSolved(formname,id) == 'noupdate') {
 1246: 	    updateSelect(formname,id);
 1247: 	    return;
 1248: 	}
 1249: 	gradeSelect = formname["GD_SEL"+id];
 1250: 	for (var i=0; i<gradeSelect.length; i++) {
 1251: 	    if (gradeSelect[i].selected) {
 1252: 		var selectx=i;
 1253: 	    }
 1254: 	}
 1255: 	var stores = formname["stores"+id];
 1256: 	if (selectx == stores.value) { return };
 1257: 	var gradeBox = formname["GD_BOX"+id];
 1258: 	gradeBox.value = "";
 1259: 	var radioButton = formname["RADVAL"+id];
 1260: 	for (var i=0; i<radioButton.length; i++) {
 1261: 	    radioButton[i].checked=false;
 1262: 	}
 1263: 	stores.value = selectx;
 1264:     }
 1265: 
 1266:     function checkSolved(formname,id) {
 1267: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
 1268: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
 1269: 	    if (!reply) {return "noupdate";}
 1270: 	    formname.overRideScore.value = 'yes';
 1271: 	}
 1272: 	return "update";
 1273:     }
 1274: 
 1275:     function updateSelect(formname,id) {
 1276: 	formname["GD_SEL"+id][0].selected = true;
 1277: 	return;
 1278:     }
 1279: 
 1280: //=========== Check that a point is assigned for all the parts  ============
 1281:     function checksubmit(formname,val,total,parttot) {
 1282: 	formname.gradeOpt.value = val;
 1283: 	if (val == "Save & Next") {
 1284: 	    for (i=0;i<=total;i++) {
 1285: 		for (j=0;j<parttot;j++) {
 1286: 		    var partid = formname["partid"+i+"_"+j].value;
 1287: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1288: 			var points = formname["GD_BOX"+i+"_"+partid].value;
 1289: 			if (points == "") {
 1290: 			    var name = formname["name"+i].value;
 1291: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
 1292: 			    var resp = confirm("You did not assign a score for "+studentID+
 1293: 					       ", part "+partid+". Continue?");
 1294: 			    if (resp == false) {
 1295: 				formname["GD_BOX"+i+"_"+partid].focus();
 1296: 				return false;
 1297: 			    }
 1298: 			}
 1299: 		    }
 1300: 		}
 1301: 	    }
 1302: 	}
 1303: 	formname.submit();
 1304:     }
 1305: 
 1306: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1307:     function checkSubmitPage(formname,total) {
 1308: 	noscore = new Array(100);
 1309: 	var ptr = 0;
 1310: 	for (i=1;i<total;i++) {
 1311: 	    var partid = formname["q_"+i].value;
 1312: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1313: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1314: 		var status = formname["solved"+i+"_"+partid].value;
 1315: 		if (points == "" && status != "correct_by_student") {
 1316: 		    noscore[ptr] = i;
 1317: 		    ptr++;
 1318: 		}
 1319: 	    }
 1320: 	}
 1321: 	if (ptr != 0) {
 1322: 	    var sense = ptr == 1 ? ": " : "s: ";
 1323: 	    var prolist = "";
 1324: 	    if (ptr == 1) {
 1325: 		prolist = noscore[0];
 1326: 	    } else {
 1327: 		var i = 0;
 1328: 		while (i < ptr-1) {
 1329: 		    prolist += noscore[i]+", ";
 1330: 		    i++;
 1331: 		}
 1332: 		prolist += "and "+noscore[i];
 1333: 	    }
 1334: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1335: 	    if (resp == false) {
 1336: 		return false;
 1337: 	    }
 1338: 	}
 1339: 
 1340: 	formname.submit();
 1341:     }
 1342: SUBJAVASCRIPT
 1343: }
 1344: 
 1345: #--- javascript for essay type problem --
 1346: sub sub_page_kw_js {
 1347:     my $request = shift;
 1348:     my $iconpath = $request->dir_config('lonIconsURL');
 1349:     &commonJSfunctions($request);
 1350: 
 1351:     my $inner_js_msg_central= (<<INNERJS);
 1352: <script type="text/javascript">
 1353:     function checkInput() {
 1354:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1355:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1356:       var usrctr = document.msgcenter.usrctr.value;
 1357:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1358:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1359: 
 1360:       var msgchk = "";
 1361:       if (document.msgcenter.subchk.checked) {
 1362:          msgchk = "msgsub,";
 1363:       }
 1364:       var includemsg = 0;
 1365:       for (var i=1; i<=nmsg; i++) {
 1366:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1367:           var frmmsg = document.msgcenter["msg"+i];
 1368:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1369:           var showflg = opener.document.SCORE["shownOnce"+i];
 1370:           showflg.value = "1";
 1371:           var chkbox = document.msgcenter["msgn"+i];
 1372:           if (chkbox.checked) {
 1373:              msgchk += "savemsg"+i+",";
 1374:              includemsg = 1;
 1375:           }
 1376:       }
 1377:       if (document.msgcenter.newmsgchk.checked) {
 1378:          msgchk += "newmsg"+usrctr;
 1379:          includemsg = 1;
 1380:       }
 1381:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1382:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1383:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1384:       includemsg.value = msgchk;
 1385: 
 1386:       self.close()
 1387: 
 1388:     }
 1389: </script>
 1390: INNERJS
 1391: 
 1392:     my $inner_js_highlight_central= (<<INNERJS);
 1393: <script type="text/javascript">
 1394:     function updateChoice(flag) {
 1395:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1396:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1397:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1398:       opener.document.SCORE.refresh.value = "on";
 1399:       if (opener.document.SCORE.keywords.value!=""){
 1400:          opener.document.SCORE.submit();
 1401:       }
 1402:       self.close()
 1403:     }
 1404: </script>
 1405: INNERJS
 1406: 
 1407:     my $start_page_msg_central = 
 1408:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1409: 				       {'js_ready'  => 1,
 1410: 					'only_body' => 1,
 1411: 					'bgcolor'   =>'#FFFFFF',});
 1412:     my $end_page_msg_central = 
 1413: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1414: 
 1415: 
 1416:     my $start_page_highlight_central = 
 1417:         &Apache::loncommon::start_page('Highlight Central',
 1418: 				       $inner_js_highlight_central,
 1419: 				       {'js_ready'  => 1,
 1420: 					'only_body' => 1,
 1421: 					'bgcolor'   =>'#FFFFFF',});
 1422:     my $end_page_highlight_central = 
 1423: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1424: 
 1425:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1426:     $docopen=~s/^document\.//;
 1427:     my %js_lt = &Apache::lonlocal::texthash(
 1428:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
 1429:                 plse => 'Please select a word or group of words from document and then click this link.',
 1430:                 adds => 'Add selection to keyword list? Edit if desired.',
 1431:                 col1 => 'red',
 1432:                 col2 => 'green',
 1433:                 col3 => 'blue',
 1434:                 siz1 => 'normal',
 1435:                 siz2 => '+1',
 1436:                 siz3 => '+2',
 1437:                 sty1 => 'normal',
 1438:                 sty2 => 'italic',
 1439:                 sty3 => 'bold',
 1440:              );
 1441:     my %html_js_lt = &Apache::lonlocal::texthash(
 1442:                 comp => 'Compose Message for: ',
 1443:                 incl => 'Include',
 1444:                 type => 'Type',
 1445:                 subj => 'Subject',
 1446:                 mesa => 'Message',
 1447:                 new  => 'New',
 1448:                 save => 'Save',
 1449:                 canc => 'Cancel',
 1450:                 kehi => 'Keyword Highlight Options',
 1451:                 txtc => 'Text Color',
 1452:                 font => 'Font Size',
 1453:                 fnst => 'Font Style',
 1454:              );
 1455:     &js_escape(\%js_lt);
 1456:     &html_escape(\%html_js_lt);
 1457:     &js_escape(\%html_js_lt);
 1458:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1459: 
 1460: //===================== Show list of keywords ====================
 1461:   function keywords(formname) {
 1462:     var nret = prompt("$js_lt{'keyw'}",formname.keywords.value);
 1463:     if (nret==null) return;
 1464:     formname.keywords.value = nret;
 1465: 
 1466:     if (formname.keywords.value != "") {
 1467: 	formname.refresh.value = "on";
 1468: 	formname.submit();
 1469:     }
 1470:     return;
 1471:   }
 1472: 
 1473: //===================== Script to view submitted by ==================
 1474:   function viewSubmitter(submitter) {
 1475:     document.SCORE.refresh.value = "on";
 1476:     document.SCORE.NCT.value = "1";
 1477:     document.SCORE.unamedom0.value = submitter;
 1478:     document.SCORE.submit();
 1479:     return;
 1480:   }
 1481: 
 1482: //===================== Script to add keyword(s) ==================
 1483:   function getSel() {
 1484:     if (document.getSelection) txt = document.getSelection();
 1485:     else if (document.selection) txt = document.selection.createRange().text;
 1486:     else return;
 1487:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1488:     if (cleantxt=="") {
 1489: 	alert("$js_lt{'plse'}");
 1490: 	return;
 1491:     }
 1492:     var nret = prompt("$js_lt{'adds'}",cleantxt);
 1493:     if (nret==null) return;
 1494:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1495:     if (document.SCORE.keywords.value != "") {
 1496: 	document.SCORE.refresh.value = "on";
 1497: 	document.SCORE.submit();
 1498:     }
 1499:     return;
 1500:   }
 1501: 
 1502: //====================== Script for composing message ==============
 1503:    // preload images
 1504:    img1 = new Image();
 1505:    img1.src = "$iconpath/mailbkgrd.gif";
 1506:    img2 = new Image();
 1507:    img2.src = "$iconpath/mailto.gif";
 1508: 
 1509:   function msgCenter(msgform,usrctr,fullname) {
 1510:     var Nmsg  = msgform.savemsgN.value;
 1511:     savedMsgHeader(Nmsg,usrctr,fullname);
 1512:     var subject = msgform.msgsub.value;
 1513:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1514:     re = /msgsub/;
 1515:     var shwsel = "";
 1516:     if (re.test(msgchk)) { shwsel = "checked" }
 1517:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1518:     displaySubject(checkEntities(subject),shwsel);
 1519:     for (var i=1; i<=Nmsg; i++) {
 1520: 	var testmsg = "savemsg"+i+",";
 1521: 	re = new RegExp(testmsg,"g");
 1522: 	shwsel = "";
 1523: 	if (re.test(msgchk)) { shwsel = "checked" }
 1524: 	var message = document.SCORE["savemsg"+i].value;
 1525: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1526: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1527: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1528:     }
 1529:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1530:     shwsel = "";
 1531:     re = /newmsg/;
 1532:     if (re.test(msgchk)) { shwsel = "checked" }
 1533:     newMsg(newmsg,shwsel);
 1534:     msgTail(); 
 1535:     return;
 1536:   }
 1537: 
 1538:   function checkEntities(strx) {
 1539:     if (strx.length == 0) return strx;
 1540:     var orgStr = ["&", "<", ">", '"']; 
 1541:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1542:     var counter = 0;
 1543:     while (counter < 4) {
 1544: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1545: 	counter++;
 1546:     }
 1547:     return strx;
 1548:   }
 1549: 
 1550:   function strReplace(strx, orgStr, newStr) {
 1551:     return strx.split(orgStr).join(newStr);
 1552:   }
 1553: 
 1554:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1555:     var height = 70*Nmsg+250;
 1556:     if (height > 600) {
 1557: 	height = 600;
 1558:     }
 1559:     var xpos = (screen.width-600)/2;
 1560:     xpos = (xpos < 0) ? '0' : xpos;
 1561:     var ypos = (screen.height-height)/2-30;
 1562:     ypos = (ypos < 0) ? '0' : ypos;
 1563: 
 1564:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
 1565:     pWin.focus();
 1566:     pDoc = pWin.document;
 1567:     pDoc.$docopen;
 1568:     pDoc.write('$start_page_msg_central');
 1569: 
 1570:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1571:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1572:     pDoc.write("<h1>&nbsp;$html_js_lt{'comp'}\"+fullname+\"<\\/h1>");
 1573: 
 1574:     pDoc.write('<table style="border:1px solid black;"><tr>');
 1575:     pDoc.write("<td><b>$html_js_lt{'incl'}<\\/b><\\/td><td><b>$html_js_lt{'type'}<\\/b><\\/td><td><b>$html_js_lt{'mesa'}<\\/td><\\/tr>");
 1576: }
 1577:     function displaySubject(msg,shwsel) {
 1578:     pDoc = pWin.document;
 1579:     pDoc.write("<tr>");
 1580:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1581:     pDoc.write("<td>$html_js_lt{'subj'}<\\/td>");
 1582:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"40\\" maxlength=\\"80\\"><\\/td><\\/tr>");
 1583: }
 1584: 
 1585:   function displaySavedMsg(ctr,msg,shwsel) {
 1586:     pDoc = pWin.document;
 1587:     pDoc.write("<tr>");
 1588:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1589:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
 1590:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
 1591: }
 1592: 
 1593:   function newMsg(newmsg,shwsel) {
 1594:     pDoc = pWin.document;
 1595:     pDoc.write("<tr>");
 1596:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1597:     pDoc.write("<td align=\\"center\\">$html_js_lt{'new'}<\\/td>");
 1598:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
 1599: }
 1600: 
 1601:   function msgTail() {
 1602:     pDoc = pWin.document;
 1603:     //pDoc.write("<\\/table>");
 1604:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1605:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1606:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
 1607:     pDoc.write("<\\/form>");
 1608:     pDoc.write('$end_page_msg_central');
 1609:     pDoc.close();
 1610: }
 1611: 
 1612: //====================== Script for keyword highlight options ==============
 1613:   function kwhighlight() {
 1614:     var kwclr    = document.SCORE.kwclr.value;
 1615:     var kwsize   = document.SCORE.kwsize.value;
 1616:     var kwstyle  = document.SCORE.kwstyle.value;
 1617:     var redsel = "";
 1618:     var grnsel = "";
 1619:     var blusel = "";
 1620:     var txtcol1 = "$js_lt{'col1'}";
 1621:     var txtcol2 = "$js_lt{'col2'}";
 1622:     var txtcol3 = "$js_lt{'col3'}";
 1623:     var txtsiz1 = "$js_lt{'siz1'}";
 1624:     var txtsiz2 = "$js_lt{'siz2'}";
 1625:     var txtsiz3 = "$js_lt{'siz3'}";
 1626:     var txtsty1 = "$js_lt{'sty1'}";
 1627:     var txtsty2 = "$js_lt{'sty2'}";
 1628:     var txtsty3 = "$js_lt{'sty3'}";
 1629:     if (kwclr=="red")   {var redsel="checked='checked'"};
 1630:     if (kwclr=="green") {var grnsel="checked='checked'"};
 1631:     if (kwclr=="blue")  {var blusel="checked='checked'"};
 1632:     var sznsel = "";
 1633:     var sz1sel = "";
 1634:     var sz2sel = "";
 1635:     if (kwsize=="0")  {var sznsel="checked='checked'"};
 1636:     if (kwsize=="+1") {var sz1sel="checked='checked'"};
 1637:     if (kwsize=="+2") {var sz2sel="checked='checked'"};
 1638:     var synsel = "";
 1639:     var syisel = "";
 1640:     var sybsel = "";
 1641:     if (kwstyle=="")    {var synsel="checked='checked'"};
 1642:     if (kwstyle=="<i>") {var syisel="checked='checked'"};
 1643:     if (kwstyle=="<b>") {var sybsel="checked='checked'"};
 1644:     highlightCentral();
 1645:     highlightbody('red',txtcol1,redsel,'0',txtsiz1,sznsel,'',txtsty1,synsel);
 1646:     highlightbody('green',txtcol2,grnsel,'+1',txtsiz2,sz1sel,'<i>',txtsty2,syisel);
 1647:     highlightbody('blue',txtcol3,blusel,'+2',txtsiz3,sz2sel,'<b>',txtsty3,sybsel);
 1648:     highlightend();
 1649:     return;
 1650:   }
 1651: 
 1652:   function highlightCentral() {
 1653: //    if (window.hwdWin) window.hwdWin.close();
 1654:     var xpos = (screen.width-400)/2;
 1655:     xpos = (xpos < 0) ? '0' : xpos;
 1656:     var ypos = (screen.height-330)/2-30;
 1657:     ypos = (ypos < 0) ? '0' : ypos;
 1658: 
 1659:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1660:     hwdWin.focus();
 1661:     var hDoc = hwdWin.document;
 1662:     hDoc.$docopen;
 1663:     hDoc.write('$start_page_highlight_central');
 1664:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1665:     hDoc.write("<h1>$html_js_lt{'kehi'}<\\/h1>");
 1666: 
 1667:     hDoc.write('<table border="0" width="100%"><tr style="background-color:#A1D676">');
 1668:     hDoc.write("<th>$html_js_lt{'txtc'}<\\/th><th>$html_js_lt{'font'}<\\/th><th>$html_js_lt{'fnst'}<\\/th><\\/tr>");
 1669:   }
 1670: 
 1671:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1672:     var hDoc = hwdWin.document;
 1673:     hDoc.write("<tr>");
 1674:     hDoc.write("<td align=\\"left\\">");
 1675:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+" \\/>&nbsp;"+clrtxt+"<\\/td>");
 1676:     hDoc.write("<td align=\\"left\\">");
 1677:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+" \\/>&nbsp;"+sztxt+"<\\/td>");
 1678:     hDoc.write("<td align=\\"left\\">");
 1679:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+" \\/>&nbsp;"+sytxt+"<\\/td>");
 1680:     hDoc.write("<\\/tr>");
 1681:   }
 1682: 
 1683:   function highlightend() { 
 1684:     var hDoc = hwdWin.document;
 1685:     hDoc.write("<\\/table><br \\/>");
 1686:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\" \\/>&nbsp;&nbsp;");
 1687:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\" \\/><br /><br />");
 1688:     hDoc.write("<\\/form>");
 1689:     hDoc.write('$end_page_highlight_central');
 1690:     hDoc.close();
 1691:   }
 1692: 
 1693: SUBJAVASCRIPT
 1694: }
 1695: 
 1696: sub get_increment {
 1697:     my $increment = $env{'form.increment'};
 1698:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1699:         $increment != .1) {
 1700:         $increment = 1;
 1701:     }
 1702:     return $increment;
 1703: }
 1704: 
 1705: sub gradeBox_start {
 1706:     return (
 1707:         &Apache::loncommon::start_data_table()
 1708:        .&Apache::loncommon::start_data_table_header_row()
 1709:        .'<th>'.&mt('Part').'</th>'
 1710:        .'<th>'.&mt('Points').'</th>'
 1711:        .'<th>&nbsp;</th>'
 1712:        .'<th>'.&mt('Assign Grade').'</th>'
 1713:        .'<th>'.&mt('Weight').'</th>'
 1714:        .'<th>'.&mt('Grade Status').'</th>'
 1715:        .&Apache::loncommon::end_data_table_header_row()
 1716:     );
 1717: }
 1718: 
 1719: sub gradeBox_end {
 1720:     return (
 1721:         &Apache::loncommon::end_data_table()
 1722:     );
 1723: }
 1724: #--- displays the grading box, used in essay type problem and grading by page/sequence
 1725: sub gradeBox {
 1726:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 1727:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1728: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 1729:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 1730:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
 1731:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
 1732:     $wgt       = ($wgt > 0 ? $wgt : '1');
 1733:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 1734: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 1735:     my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 1736:     my $display_part= &get_display_part($partid,$symb);
 1737:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 1738: 				       [$partid]);
 1739:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 1740:     if ($last_resets{$partid}) {
 1741:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 1742:     }
 1743:     my $result=&Apache::loncommon::start_data_table_row();
 1744:     my $ctr = 0;
 1745:     my $thisweight = 0;
 1746:     my $increment = &get_increment();
 1747: 
 1748:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 1749:     while ($thisweight<=$wgt) {
 1750: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 1751:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 1752: 	    $thisweight.')" value="'.$thisweight.'" '.
 1753: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 1754: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 1755:         $thisweight += $increment;
 1756: 	$ctr++;
 1757:     }
 1758:     $radio.='</tr></table>';
 1759: 
 1760:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 1761: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 1762: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 1763: 	$wgt.')" /></td>'."\n";
 1764:     $line.='<td>/'.$wgt.' '.$wgtmsg.
 1765: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 1766: 	' </td>'."\n";
 1767:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
 1768: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 1769:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 1770: 	$line.='<option></option>'.
 1771: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
 1772:     } else {
 1773: 	$line.='<option selected="selected"></option>'.
 1774: 	    '<option value="excused" >'.&mt('excused').'</option>';
 1775:     }
 1776:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
 1777: 
 1778: 
 1779:     $result .= 
 1780: 	    '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
 1781:     $result.=&Apache::loncommon::end_data_table_row();
 1782:     $result.=&Apache::loncommon::start_data_table_row().'<td colspan="6">';
 1783:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 1784: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 1785: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 1786: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 1787:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 1788:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 1789:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 1790:         $aggtries.'" />'."\n";
 1791:     my $res_error;
 1792:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
 1793:     $result.='</td>'.&Apache::loncommon::end_data_table_row();
 1794:     if ($res_error) {
 1795:         return &navmap_errormsg();
 1796:     }
 1797:     return $result;
 1798: }
 1799: 
 1800: sub handback_box {
 1801:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
 1802:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error_pointer);
 1803:     my (@respids);
 1804:     my @part_response_id = &flatten_responseType($responseType);
 1805:     foreach my $part_response_id (@part_response_id) {
 1806:     	my ($part,$resp) = @{ $part_response_id };
 1807:         if ($part eq $partid) {
 1808:             push(@respids,$resp);
 1809:         }
 1810:     }
 1811:     my $result;
 1812:     foreach my $respid (@respids) {
 1813: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 1814: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 1815: 	next if (!@$files);
 1816: 	my $file_counter = 0;
 1817: 	foreach my $file (@$files) {
 1818: 	    if ($file =~ /\/portfolio\//) {
 1819:                 $file_counter++;
 1820:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 1821:     	        my ($name,$version,$ext) = &Apache::lonnet::file_name_version_ext($file_disp);
 1822:     	        $file_disp = "$name.$ext";
 1823:     	        $file = $file_path.$file_disp;
 1824:     	        $result.=&mt('Return commented version of [_1] to student.',
 1825:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 1826:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 1827:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
 1828: 	    }
 1829: 	}
 1830:         if ($file_counter) {
 1831:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
 1832:                        '<span class="LC_info">'.
 1833:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
 1834:         }
 1835:     }
 1836:     return $result;    
 1837: }
 1838: 
 1839: sub show_problem {
 1840:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 1841:     my $rendered;
 1842:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 1843:     &Apache::lonxml::remember_problem_counter();
 1844:     if ($mode eq 'both' or $mode eq 'text') {
 1845: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 1846: 						       $env{'request.course.id'},
 1847: 						       undef,\%form);
 1848:     }
 1849:     if ($removeform) {
 1850: 	$rendered=~s|<form(.*?)>||g;
 1851: 	$rendered=~s|</form>||g;
 1852: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 1853:     }
 1854:     my $companswer;
 1855:     if ($mode eq 'both' or $mode eq 'answer') {
 1856: 	&Apache::lonxml::restore_problem_counter();
 1857: 	$companswer=
 1858: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 1859: 						    $env{'request.course.id'},
 1860: 						    %form);
 1861:     }
 1862:     if ($removeform) {
 1863: 	$companswer=~s|<form(.*?)>||g;
 1864: 	$companswer=~s|</form>||g;
 1865: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 1866:     }
 1867:     my $renderheading = &mt('View of the problem');
 1868:     my $answerheading = &mt('Correct answer');
 1869:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 1870:         my $stu_fullname = $env{'form.fullname'};
 1871:         if ($stu_fullname eq '') {
 1872:             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
 1873:         }
 1874:         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
 1875:         if ($forwhom ne '') {
 1876:             $renderheading = &mt('View of the problem for[_1]',$forwhom);
 1877:             $answerheading = &mt('Correct answer for[_1]',$forwhom);
 1878:         }
 1879:     }
 1880:     $rendered=
 1881:         '<div class="LC_Box">'
 1882:        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
 1883:        .$rendered
 1884:        .'</div>';
 1885:     $companswer=
 1886:         '<div class="LC_Box">'
 1887:        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
 1888:        .$companswer
 1889:        .'</div>';
 1890:     my $result;
 1891:     if ($mode eq 'both') {
 1892:         $result=$rendered.$companswer;
 1893:     } elsif ($mode eq 'text') {
 1894:         $result=$rendered;
 1895:     } elsif ($mode eq 'answer') {
 1896:         $result=$companswer;
 1897:     }
 1898:     return $result;
 1899: }
 1900: 
 1901: sub files_exist {
 1902:     my ($r, $symb) = @_;
 1903:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1904: 
 1905:     foreach my $student (@students) {
 1906:         my ($uname,$udom,$fullname) = split(/:/,$student);
 1907:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 1908: 					      $udom,$uname);
 1909:         my ($string,$timestamp)= &get_last_submission(\%record);
 1910:         foreach my $submission (@$string) {
 1911:             my ($partid,$respid) =
 1912: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 1913:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 1914: 					   \%record);
 1915:             return 1 if (@$files);
 1916:         }
 1917:     }
 1918:     return 0;
 1919: }
 1920: 
 1921: sub download_all_link {
 1922:     my ($r,$symb) = @_;
 1923:     unless (&files_exist($r, $symb)) {
 1924:        $r->print(&mt('There are currently no submitted documents.'));
 1925:        return;
 1926:     }
 1927: 
 1928:     my $all_students = 
 1929: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 1930: 
 1931:     my $parts =
 1932: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 1933: 
 1934:     my $identifier = &Apache::loncommon::get_cgi_id();
 1935:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 1936:                              'cgi.'.$identifier.'.symb' => $symb,
 1937:                              'cgi.'.$identifier.'.parts' => $parts,});
 1938:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 1939: 	      &mt('Download All Submitted Documents').'</a>');
 1940:     return;
 1941: }
 1942: 
 1943: sub submit_download_link {
 1944:     my ($request,$symb) = @_;
 1945:     if (!$symb) { return ''; }
 1946: #FIXME: Figure out which type of problem this is and provide appropriate download
 1947:     &download_all_link($request,$symb);
 1948: }
 1949: 
 1950: sub build_section_inputs {
 1951:     my $section_inputs;
 1952:     if ($env{'form.section'} eq '') {
 1953:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 1954:     } else {
 1955:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 1956:         foreach my $section (@sections) {
 1957:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 1958:         }
 1959:     }
 1960:     return $section_inputs;
 1961: }
 1962: 
 1963: # --------------------------- show submissions of a student, option to grade 
 1964: sub submission {
 1965:     my ($request,$counter,$total,$symb) = @_;
 1966:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 1967:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 1968:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 1969:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 1970: 
 1971:     my $probtitle=&Apache::lonnet::gettitle($symb); 
 1972:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 1973: 
 1974:     if (!&canview($usec)) {
 1975:         $request->print(
 1976:             '<span class="LC_warning">'.
 1977:             &mt('Unable to view requested student.').
 1978:             ' '.&mt('([_1] in section [_2] in course id [_3])',
 1979:                         $uname.':'.$udom,$usec,$env{'request.course.id'}).
 1980:             '</span>');
 1981: 	return;
 1982:     }
 1983: 
 1984:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 1985:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 1986:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 1987:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 1988:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1989: 	'" src="'.$request->dir_config('lonIconsURL').
 1990: 	'/check.gif" height="16" border="0" />';
 1991: 
 1992:     # header info
 1993:     if ($counter == 0) {
 1994: 	&sub_page_js($request);
 1995: 	&sub_page_kw_js($request);
 1996: 
 1997: 	# option to display problem, only once else it cause problems 
 1998:         # with the form later since the problem has a form.
 1999: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 2000: 	    my $mode;
 2001: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 2002: 		$mode='both';
 2003: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 2004: 		$mode='text';
 2005: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 2006: 		$mode='answer';
 2007: 	    }
 2008: 	    &Apache::lonxml::clear_problem_counter();
 2009: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 2010: 	}
 2011: 
 2012: 	# kwclr is the only variable that is guaranteed not to be blank 
 2013:         # if this subroutine has been called once.
 2014: 	my %keyhash = ();
 2015: #	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
 2016:         if (1) {
 2017: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 2018: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 2019: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 2020: 
 2021: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2022: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 2023: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 2024: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 2025: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 2026: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
 2027: 		$keyhash{$symb.'_subject'} : $probtitle;
 2028: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 2029: 	}
 2030: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 2031: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 2032: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 2033: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 2034: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 2035: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 2036: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 2037: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 2038: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 2039: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 2040: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 2041: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 2042: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 2043: 			&build_section_inputs().
 2044: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 2045: 			'<input type="hidden" name="NCT"'.
 2046: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 2047: #	if ($env{'form.handgrade'} eq 'yes') {
 2048:         if (1) {
 2049: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 2050: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 2051: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 2052: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
 2053: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 2054: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 2055: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 2056: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
 2057: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
 2058: 	    }
 2059: 	}
 2060: 	
 2061: 	my ($cts,$prnmsg) = (1,'');
 2062: 	while ($cts <= $env{'form.savemsgN'}) {
 2063: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 2064: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 2065: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 2066: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 2067: 		'" />'."\n".
 2068: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 2069: 	    $cts++;
 2070: 	}
 2071: 	$request->print($prnmsg);
 2072: 
 2073: #	if ($env{'form.handgrade'} eq 'yes') {
 2074:         if (1) {
 2075: 
 2076:             my %lt = &Apache::lonlocal::texthash(
 2077:                           keyh => 'Keyword Highlighting for Essays',
 2078:                           keyw => 'Keyword Options',
 2079:                           list => 'List',
 2080:                           past => 'Paste Selection to List',
 2081:                           high => 'Highlight Attribute',
 2082:                      );    
 2083: #
 2084: # Print out the keyword options line
 2085: #
 2086: 	    $request->print(
 2087:                 '<div class="LC_columnSection">'
 2088:                .'<fieldset><legend>'.$lt{'keyh'}.'</legend>'
 2089:                .&Apache::lonhtmlcommon::funclist_from_array(
 2090:                     ['<a href="javascript:keywords(document.SCORE);" target="_self">'.$lt{'list'}.'</a>',
 2091:                      '<a href="#" onmousedown="javascript:getSel(); return false"
 2092:  class="page">'.$lt{'past'}.'</a>',
 2093:                      '<a href="javascript:kwhighlight();" target="_self">'.$lt{'high'}.'</a>'],
 2094:                     {legend => $lt{'keyw'}})
 2095:                .'</fieldset></div>'
 2096:             );
 2097: 
 2098: #
 2099: # Load the other essays for similarity check
 2100: #
 2101:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 2102: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 2103: 	    $apath=&escape($apath);
 2104: 	    $apath=~s/\W/\_/gs;
 2105:             &init_old_essays($symb,$apath,$adom,$aname);
 2106:         }
 2107:     }
 2108: 
 2109: # This is where output for one specific student would start
 2110:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
 2111:     $request->print(
 2112:         "\n\n"
 2113:        .'<div class="LC_grade_show_user'.$add_class.'">'
 2114:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
 2115:        ."\n"
 2116:     );
 2117: 
 2118:     # Show additional functions if allowed
 2119:     if ($perm{'vgr'}) {
 2120:         $request->print(
 2121:             &Apache::loncommon::track_student_link(
 2122:                 'View recent activity',
 2123:                 $uname,$udom,'check')
 2124:            .' '
 2125:         );
 2126:     }
 2127:     if ($perm{'opa'}) {
 2128:         $request->print(
 2129:             &Apache::loncommon::pprmlink(
 2130:                 &mt('Set/Change parameters'),
 2131:                 $uname,$udom,$symb,'check'));
 2132:     }
 2133: 
 2134:     # Show Problem
 2135:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2136: 	my $mode;
 2137: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2138: 	    $mode='both';
 2139: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2140: 	    $mode='text';
 2141: 	} elsif ($env{'form.vAns'} eq 'all') {
 2142: 	    $mode='answer';
 2143: 	}
 2144: 	&Apache::lonxml::clear_problem_counter();
 2145: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2146:     }
 2147: 
 2148:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2149:     my $res_error;
 2150:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2151:     if ($res_error) {
 2152:         $request->print(&navmap_errormsg());
 2153:         return;
 2154:     }
 2155: 
 2156:     # Display student info
 2157:     $request->print(($counter == 0 ? '' : '<br />'));
 2158: 
 2159:     my $result='<div class="LC_Box">'
 2160:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
 2161:     $result.='<input type="hidden" name="name'.$counter.
 2162:              '" value="'.$env{'form.fullname'}.'" />'."\n";
 2163: #    if ($env{'form.handgrade'} eq 'no') {
 2164:     if (1) {
 2165:         $result.='<p class="LC_info">'
 2166:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
 2167:                 ."</p>\n";
 2168:     }
 2169: 
 2170:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
 2171:     my $fullname;
 2172:     my $col_fullnames = [];
 2173: #    if ($env{'form.handgrade'} eq 'yes') {
 2174:     if (1) {
 2175: 	(my $sub_result,$fullname,$col_fullnames)=
 2176: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2177: 				 $counter);
 2178: 	$result.=$sub_result;
 2179:     }
 2180:     $request->print($result."\n");
 2181:     
 2182:     # print student answer/submission
 2183:     # Options are (1) Handgraded submission only
 2184:     #             (2) Last submission, includes submission that is not handgraded 
 2185:     #                  (for multi-response type part)
 2186:     #             (3) Last submission plus the parts info
 2187:     #             (4) The whole record for this student
 2188:     
 2189:     my ($string,$timestamp)= &get_last_submission(\%record);
 2190: 	
 2191:     my $lastsubonly;
 2192: 
 2193:     if ($$timestamp eq '') {
 2194:         $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
 2195:     } else {
 2196:         $lastsubonly =
 2197:             '<div class="LC_grade_submissions_body">'
 2198:            .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
 2199: 
 2200: 	my %seenparts;
 2201: 	my @part_response_id = &flatten_responseType($responseType);
 2202: 	foreach my $part (@part_response_id) {
 2203: 	    next if ($env{'form.lastSub'} eq 'hdgrade' 
 2204: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
 2205: 
 2206: 	    my ($partid,$respid) = @{ $part };
 2207: 	    my $display_part=&get_display_part($partid,$symb);
 2208: 	    if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2209: 		if (exists($seenparts{$partid})) { next; }
 2210: 		$seenparts{$partid}=1;
 2211:                 $request->print(
 2212:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2213:                     ' <b>'.&mt('Collaborative submission by: [_1]',
 2214:                                '<a href="javascript:viewSubmitter(\''.
 2215:                                $env{"form.$uname:$udom:$partid:submitted_by"}.
 2216:                                '\');" target="_self">'.
 2217:                                $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
 2218:                     '<br />');
 2219: 		next;
 2220: 		}
 2221: 	    my $responsetype = $responseType->{$partid}->{$respid};
 2222: 	    if (!exists($record{"resource.$partid.$respid.submission"})) {
 2223:                 $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
 2224:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2225:                     ' <span class="LC_internal_info">'.
 2226:                     '('.&mt('Response ID: [_1]',$respid).')'.
 2227:                     '</span>&nbsp; &nbsp;'.
 2228: 	       	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
 2229: 		next;
 2230: 	    }
 2231: 	    foreach my $submission (@$string) {
 2232: 		my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2233: 		if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2234: 		my ($ressub,$hide,$draft,$subval) = split(/:/,$submission,4);
 2235: 		# Similarity check
 2236:                 my $similar='';
 2237:                 my ($type,$trial,$rndseed);
 2238:                 if ($hide eq 'rand') {
 2239:                     $type = 'randomizetry';
 2240:                     $trial = $record{"resource.$partid.tries"};
 2241:                     $rndseed = $record{"resource.$partid.rndseed"};
 2242:                 }
 2243: 	        if ($env{'form.checkPlag'}) {
 2244:     		    my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2245: 		        &most_similar($uname,$udom,$symb,$subval);
 2246: 		    if ($osim) {
 2247: 			$osim=int($osim*100.0);
 2248: 			my %old_course_desc = 
 2249: 			    &Apache::lonnet::coursedescription($ocrsid,
 2250: 							{'one_time' => 1});
 2251: 
 2252:                         if ($hide eq 'anon') {
 2253:                             $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
 2254:                                      &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
 2255:                         } else {
 2256: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
 2257: 				&mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
 2258: 				    $osim,
 2259: 				    &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
 2260: 				        $old_course_desc{'description'},
 2261: 				        $old_course_desc{'num'},
 2262: 				        $old_course_desc{'domain'}).
 2263: 				    '</span></h3><blockquote><i>'.
 2264: 				    &keywords_highlight($oessay).
 2265: 				    '</i></blockquote><hr />';
 2266:                         }
 2267: 	            }
 2268: 		}
 2269: 		my $order=&get_order($partid,$respid,$symb,$uname,$udom,
 2270:                                      undef,$type,$trial,$rndseed);
 2271:                 if ($env{'form.lastSub'} eq 'lastonly' || $env{'form.lastSub'} eq 'datesub' || $env{'form.lastSub'} =~ /^(last|all)$/ || ($env{'form.lastSub'} eq 'hdgrade' && 
 2272: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
 2273: 		    my $display_part=&get_display_part($partid,$symb);
 2274:                     $lastsubonly.='<div class="LC_grade_submission_part">'.
 2275:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2276:                         ' <span class="LC_internal_info">'.
 2277:                         '('.&mt('Response ID: [_1]',$respid).')'.
 2278:                         '</span>&nbsp; &nbsp;';
 2279: 		    my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2280:                         
 2281: 		    if (@$files) {
 2282:                         if ($hide eq 'anon') {
 2283:                             $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
 2284:                         } else {
 2285:                             $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
 2286:                                         .'<br /><span class="LC_warning">';
 2287:                             if(@$files == 1) {
 2288:                                 $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
 2289:                             } else {
 2290:                                 $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
 2291:                             }
 2292:                             $lastsubonly .= '</span>';                         
 2293:                             foreach my $file (@$files) {
 2294:                                 &Apache::lonnet::allowuploaded('/adm/grades',$file);
 2295:                                 $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
 2296:                             }
 2297:                         }
 2298: 			$lastsubonly.='<br />';
 2299:                     }
 2300:                     if ($hide eq 'anon') {
 2301:                         $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>'; 
 2302:                     } else {
 2303:              	        $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>';
 2304:                         if ($draft) {
 2305:                             $lastsubonly.= ' <span class="LC_warning">'.&mt('Draft Copy').'</span>';
 2306:                         }
 2307:                         $subval =
 2308: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
 2309: 					 $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
 2310:                         if ($responsetype eq 'essay') {
 2311:                             $subval =~ s{\n}{<br />}g;
 2312:                         }
 2313:                         $lastsubonly.=$subval."\n";
 2314:                     }
 2315: 	            if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2316: 		    $lastsubonly.='</div>';
 2317: 		}
 2318:             }
 2319: 	}
 2320: 	$lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
 2321:     }
 2322:     $request->print($lastsubonly);
 2323:     if ($env{'form.lastSub'} eq 'datesub') {
 2324:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2325: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2326:   
 2327:     } 
 2328:     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2329:         my $identifier = (&canmodify($usec)? $counter : '');
 2330:         $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2331: 								 $env{'request.course.id'},
 2332: 								 $last,'.submission',
 2333: 								 'Apache::grades::keywords_highlight',
 2334:                                                                  $usec,$identifier));
 2335:     }
 2336:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2337: 	.$udom.'" />'."\n");
 2338:     # return if view submission with no grading option
 2339:     if (!&canmodify($usec)) {
 2340: 	$request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
 2341: 	return;
 2342:     } else {
 2343: 	$request->print('</div>'."\n");
 2344:     }
 2345: 
 2346:     # essay grading message center
 2347: #    if ($env{'form.handgrade'} eq 'yes') {
 2348:     if (1) {
 2349: 	my $result='<div class="LC_grade_message_center">';
 2350:     
 2351: 	$result.='<div class="LC_grade_message_center_header">'.
 2352: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
 2353: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2354: 	my $msgfor = $givenn.' '.$lastname;
 2355: 	if (scalar(@$col_fullnames) > 0) {
 2356: 	    my $lastone = pop(@$col_fullnames);
 2357: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2358: 	}
 2359: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2360: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2361: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
 2362: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2363: 	    ',\''.$msgfor.'\');" target="_self">'.
 2364: 	    &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
 2365: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2366: 	    ' <img src="'.$request->dir_config('lonIconsURL').
 2367: 	    '/mailbkgrd.gif" width="14" height="10" alt="" name="mailicon'.$counter.'" />'."\n".
 2368: 	    '<br />&nbsp;('.
 2369: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
 2370: 	$result.='</div></div>';
 2371: 	$request->print($result);
 2372:     }
 2373: 
 2374:     my %seen = ();
 2375:     my @partlist;
 2376:     my @gradePartRespid;
 2377:     my @part_response_id = &flatten_responseType($responseType);
 2378:     $request->print(
 2379:         '<div class="LC_Box">'
 2380:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
 2381:     );
 2382:     $request->print(&gradeBox_start());
 2383:     foreach my $part_response_id (@part_response_id) {
 2384:     	my ($partid,$respid) = @{ $part_response_id };
 2385: 	my $part_resp = join('_',@{ $part_response_id });
 2386: 	next if ($seen{$partid} > 0);
 2387: 	$seen{$partid}++;
 2388: 	next if ($$handgrade{$part_resp} ne 'yes' 
 2389: 		 && $env{'form.lastSub'} eq 'hdgrade');
 2390: 	push(@partlist,$partid);
 2391: 	push(@gradePartRespid,$partid.'.'.$respid);
 2392: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2393:     }
 2394:     $request->print(&gradeBox_end()); # </div>
 2395:     $request->print('</div>');
 2396: 
 2397:     $request->print('<div class="LC_grade_info_links">');
 2398:     $request->print('</div>');
 2399: 
 2400:     $result='<input type="hidden" name="partlist'.$counter.
 2401: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2402:     $result.='<input type="hidden" name="gradePartRespid'.
 2403: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2404:     my $ctr = 0;
 2405:     while ($ctr < scalar(@partlist)) {
 2406: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2407: 	    $partlist[$ctr].'" />'."\n";
 2408: 	$ctr++;
 2409:     }
 2410:     $request->print($result.''."\n");
 2411: 
 2412: # Done with printing info for one student
 2413: 
 2414:     $request->print('</div>');#LC_grade_show_user
 2415: 
 2416: 
 2417:     # print end of form
 2418:     if ($counter == $total) {
 2419:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
 2420: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2421: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
 2422: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2423: 	my $ntstu ='<select name="NTSTU">'.
 2424: 	    '<option>1</option><option>2</option>'.
 2425: 	    '<option>3</option><option>5</option>'.
 2426: 	    '<option>7</option><option>10</option></select>'."\n";
 2427: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2428: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2429:         $endform.=&mt('[_1]student(s)',$ntstu);
 2430: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2431: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2432: 	    '<input type="button" value="'.&mt('Next').'" '.
 2433: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2434:         $endform.='<span class="LC_warning">'.
 2435:                   &mt('(Next and Previous (student) do not save the scores.)').
 2436:                   '</span>'."\n" ;
 2437:         $endform.="<input type='hidden' value='".&get_increment().
 2438:             "' name='increment' />";
 2439: 	$endform.='</td></tr></table></form>';
 2440: 	$request->print($endform);
 2441:     }
 2442:     return '';
 2443: }
 2444: 
 2445: sub check_collaborators {
 2446:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2447:     my ($result,@col_fullnames);
 2448:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2449:     foreach my $part (keys(%$handgrade)) {
 2450: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2451: 					'.maxcollaborators',
 2452: 					$symb,$udom,$uname);
 2453: 	next if ($ncol <= 0);
 2454: 	$part =~ s/\_/\./g;
 2455: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2456: 	my (@good_collaborators, @bad_collaborators);
 2457: 	foreach my $possible_collaborator
 2458: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2459: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2460: 	    next if ($possible_collaborator eq '');
 2461: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
 2462: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2463: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2464: 	    # Doing this grep allows 'fuzzy' specification
 2465: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2466: 			       keys(%$classlist));
 2467: 	    if (! scalar(@matches)) {
 2468: 		push(@bad_collaborators, $possible_collaborator);
 2469: 	    } else {
 2470: 		push(@good_collaborators, @matches);
 2471: 	    }
 2472: 	}
 2473: 	if (scalar(@good_collaborators) != 0) {
 2474: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
 2475: 	    foreach my $name (@good_collaborators) {
 2476: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2477: 		push(@col_fullnames, $givenn.' '.$lastname);
 2478: 		$result.='<li>'.$fullname->{$name}.'</li>';
 2479: 	    }
 2480: 	    $result.='</ol><br />'."\n";
 2481: 	    my ($part)=split(/\./,$part);
 2482: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2483: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2484: 		"\n";
 2485: 	}
 2486: 	if (scalar(@bad_collaborators) > 0) {
 2487: 	    $result.='<div class="LC_warning">';
 2488: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2489: 	    $result .= '</div>';
 2490: 	}         
 2491: 	if (scalar(@bad_collaborators > $ncol)) {
 2492: 	    $result .= '<div class="LC_warning">';
 2493: 	    $result .= &mt('This student has submitted too many '.
 2494: 		'collaborators.  Maximum is [_1].',$ncol);
 2495: 	    $result .= '</div>';
 2496: 	}
 2497:     }
 2498:     return ($result,$fullname,\@col_fullnames);
 2499: }
 2500: 
 2501: #--- Retrieve the last submission for all the parts
 2502: sub get_last_submission {
 2503:     my ($returnhash)=@_;
 2504:     my (@string,$timestamp,%lasthidden);
 2505:     if ($$returnhash{'version'}) {
 2506: 	my %lasthash=();
 2507: 	my ($version);
 2508: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2509: 	    foreach my $key (sort(split(/\:/,
 2510: 					$$returnhash{$version.':keys'}))) {
 2511: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2512: 		$timestamp = 
 2513: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2514: 	    }
 2515: 	}
 2516:         my (%typeparts,%randombytry);
 2517:         my $showsurv = 
 2518:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
 2519:         foreach my $key (sort(keys(%lasthash))) {
 2520:             if ($key =~ /\.type$/) {
 2521:                 if (($lasthash{$key} eq 'anonsurvey') || 
 2522:                     ($lasthash{$key} eq 'anonsurveycred') ||
 2523:                     ($lasthash{$key} eq 'randomizetry')) {
 2524:                     my ($ign,@parts) = split(/\./,$key);
 2525:                     pop(@parts);
 2526:                     my $id = join('.',@parts);
 2527:                     if ($lasthash{$key} eq 'randomizetry') {
 2528:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
 2529:                     } else {
 2530:                         unless ($showsurv) {
 2531:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
 2532:                         }
 2533:                     }
 2534:                     delete($lasthash{$key});
 2535:                 }
 2536:             }
 2537:         }
 2538:         my @hidden = keys(%typeparts);
 2539:         my @randomize = keys(%randombytry);
 2540: 	foreach my $key (keys(%lasthash)) {
 2541: 	    next if ($key !~ /\.submission$/);
 2542:             my $hide;
 2543:             if (@hidden) {
 2544:                 foreach my $id (@hidden) {
 2545:                     if ($key =~ /^\Q$id\E/) {
 2546:                         $hide = 'anon';
 2547:                         last;
 2548:                     }
 2549:                 }
 2550:             }
 2551:             unless ($hide) {
 2552:                 if (@randomize) {
 2553:                     foreach my $id (@randomize) {
 2554:                         if ($key =~ /^\Q$id\E/) {
 2555:                             $hide = 'rand';
 2556:                             last;
 2557:                         }
 2558:                     }
 2559:                 }
 2560:             }
 2561: 	    my ($partid,$foo) = split(/submission$/,$key);
 2562: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ? 1 : 0;
 2563:             push(@string, join(':', $key, $hide, $draft, (
 2564:                 ref($lasthash{$key}) eq 'ARRAY' ?
 2565:                     join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
 2566: 	}
 2567:     }
 2568:     if (!@string) {
 2569: 	$string[0] =
 2570: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
 2571:     }
 2572:     return (\@string,\$timestamp);
 2573: }
 2574: 
 2575: #--- High light keywords, with style choosen by user.
 2576: sub keywords_highlight {
 2577:     my $string    = shift;
 2578:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2579:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2580:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2581:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2582:     foreach my $keyword (@keylist) {
 2583: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2584:     }
 2585:     return $string;
 2586: }
 2587: 
 2588: # For Tasks provide a mechanism to display previous version for one specific student
 2589: 
 2590: sub show_previous_task_version {
 2591:     my ($request,$symb) = @_;
 2592:     if ($symb eq '') {
 2593:         $request->print(
 2594:             '<span class="LC_error">'.
 2595:             &mt('Unable to handle ambiguous references.').
 2596:             '</span>');
 2597:         return '';
 2598:     }
 2599:     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
 2600:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 2601:     if (!&canview($usec)) {
 2602:         $request->print(
 2603:             '<span class="LC_warning">'.
 2604:             &mt('Unable to view previous version for requested student.').
 2605:             ' '.&mt('([_1] in section [_2] in course id [_3])',
 2606:                     $uname.':'.$udom,$usec,$env{'request.course.id'}).
 2607:             '</span>');
 2608:         return;
 2609:     }
 2610:     my $mode = 'both';
 2611:     my $isTask = ($symb =~/\.task$/);
 2612:     if ($isTask) {
 2613:         if ($env{'form.previousversion'} =~ /^\d+$/) {
 2614:             if ($env{'form.fullname'} eq '') {
 2615:                 $env{'form.fullname'} =
 2616:                     &Apache::loncommon::plainname($uname,$udom,'lastname');
 2617:             }
 2618:             my $probtitle=&Apache::lonnet::gettitle($symb);
 2619:             $request->print("\n\n".
 2620:                             '<div class="LC_grade_show_user">'.
 2621:                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 2622:                             '</h2>'."\n");
 2623:             &Apache::lonxml::clear_problem_counter();
 2624:             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
 2625:                             {'previousversion' => $env{'form.previousversion'} }));
 2626:             $request->print("\n</div>");
 2627:         }
 2628:     }
 2629:     return;
 2630: }
 2631: 
 2632: sub choose_task_version_form {
 2633:     my ($symb,$uname,$udom,$nomenu) = @_;
 2634:     my $isTask = ($symb =~/\.task$/);
 2635:     my ($current,$version,$result,$js,$displayed,$rowtitle);
 2636:     if ($isTask) {
 2637:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 2638:                                               $udom,$uname);
 2639:         if (($record{'resource.0.version'} eq '') ||
 2640:             ($record{'resource.0.version'} < 2)) {
 2641:             return ($record{'resource.0.version'},
 2642:                     $record{'resource.0.version'},$result,$js);
 2643:         } else {
 2644:             $current = $record{'resource.0.version'};
 2645:         }
 2646:         if ($env{'form.previousversion'}) {
 2647:             $displayed = $env{'form.previousversion'};
 2648:             $rowtitle = &mt('Choose another version:')
 2649:         } else {
 2650:             $displayed = $current;
 2651:             $rowtitle = &mt('Show earlier version:');
 2652:         }
 2653:         $result = '<div class="LC_left_float">';
 2654:         my $list;
 2655:         my $numversions = 0;
 2656:         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
 2657:             if ($i == $current) {
 2658:                 if (!$env{'form.previousversion'} || $nomenu) {
 2659:                     next;
 2660:                 } else {
 2661:                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
 2662:                     $numversions ++;
 2663:                 }
 2664:             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
 2665:                 unless ($i == $env{'form.previousversion'}) {
 2666:                     $numversions ++;
 2667:                 }
 2668:                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
 2669:             }
 2670:         }
 2671:         if ($numversions) {
 2672:             $symb = &HTML::Entities::encode($symb,'<>"&');
 2673:             $result .=
 2674:                 '<form name="getprev" method="post" action=""'.
 2675:                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
 2676:                 &Apache::loncommon::start_data_table().
 2677:                 &Apache::loncommon::start_data_table_row().
 2678:                 '<th align="left">'.$rowtitle.'</th>'.
 2679:                 '<td><select name="version">'.
 2680:                 '<option>'.&mt('Select').'</option>'.
 2681:                 $list.
 2682:                 '</select></td>'.
 2683:                 &Apache::loncommon::end_data_table_row();
 2684:             unless ($nomenu) {
 2685:                 $result .= &Apache::loncommon::start_data_table_row().
 2686:                 '<th align="left">'.&mt('Open in new window').'</th>'.
 2687:                 '<td><span class="LC_nobreak">'.
 2688:                 '<label><input type="radio" name="prevwin" value="1" />'.
 2689:                 &mt('Yes').'</label>'.
 2690:                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
 2691:                 '</span></td>'.
 2692:                 &Apache::loncommon::end_data_table_row();
 2693:             }
 2694:             $result .=
 2695:                 &Apache::loncommon::start_data_table_row().
 2696:                 '<th align="left">&nbsp;</th>'.
 2697:                 '<td>'.
 2698:                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
 2699:                 '</td>'.
 2700:                 &Apache::loncommon::end_data_table_row().
 2701:                 &Apache::loncommon::end_data_table().
 2702:                 '</form>';
 2703:             $js = &previous_display_javascript($nomenu,$current);
 2704:         } elsif ($displayed && $nomenu) {
 2705:             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
 2706:         } else {
 2707:             $result .= &mt('No previous versions to show for this student');
 2708:         }
 2709:         $result .= '</div>';
 2710:     }
 2711:     return ($current,$displayed,$result,$js);
 2712: }
 2713: 
 2714: sub previous_display_javascript {
 2715:     my ($nomenu,$current) = @_;
 2716:     my $js = <<"JSONE";
 2717: <script type="text/javascript">
 2718: // <![CDATA[
 2719: function previousVersion(uname,udom,symb) {
 2720:     var current = '$current';
 2721:     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
 2722:     var prevstr = new RegExp("^\\\\d+\$");
 2723:     if (!prevstr.test(version)) {
 2724:         return false;
 2725:     }
 2726:     var url = '';
 2727:     if (version == current) {
 2728:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
 2729:     } else {
 2730:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
 2731:     }
 2732: JSONE
 2733:     if ($nomenu) {
 2734:         $js .= <<"JSTWO";
 2735:     document.location.href = url;
 2736: JSTWO
 2737:     } else {
 2738:         $js .= <<"JSTHREE";
 2739:     var newwin = 0;
 2740:     for (var i=0; i<document.getprev.prevwin.length; i++) {
 2741:         if (document.getprev.prevwin[i].checked == true) {
 2742:             newwin = document.getprev.prevwin[i].value;
 2743:         }
 2744:     }
 2745:     if (newwin == 1) {
 2746:         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
 2747:         url = url+'&inhibitmenu=yes';
 2748:         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
 2749:             previousWin = window.open(url,'',options,1);
 2750:         } else {
 2751:             previousWin.location.href = url;
 2752:         }
 2753:         previousWin.focus();
 2754:         return false;
 2755:     } else {
 2756:         document.location.href = url;
 2757:         return false;
 2758:     }
 2759: JSTHREE
 2760:     }
 2761:     $js .= <<"ENDJS";
 2762:     return false;
 2763: }
 2764: // ]]>
 2765: </script>
 2766: ENDJS
 2767: 
 2768: }
 2769: 
 2770: #--- Called from submission routine
 2771: sub processHandGrade {
 2772:     my ($request,$symb) = @_;
 2773:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2774:     my $button = $env{'form.gradeOpt'};
 2775:     my $ngrade = $env{'form.NCT'};
 2776:     my $ntstu  = $env{'form.NTSTU'};
 2777:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2778:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 2779: 
 2780:     if ($button eq 'Save & Next') {
 2781: 	my $ctr = 0;
 2782: 	while ($ctr < $ngrade) {
 2783: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 2784: 	    my ($errorflag,$pts,$wgt,$numhidden) = 
 2785:                 &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 2786: 	    if ($errorflag eq 'no_score') {
 2787: 		$ctr++;
 2788: 		next;
 2789: 	    }
 2790: 	    if ($errorflag eq 'not_allowed') {
 2791: 		$request->print(
 2792:                     '<span class="LC_error">'
 2793:                    .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
 2794:                    .'</span>');
 2795: 		$ctr++;
 2796: 		next;
 2797: 	    }
 2798:             if ($numhidden) {
 2799:                 $request->print(
 2800:                     '<span class="LC_info">'
 2801:                    .&mt('For [_1]: [quant,_2,transaction] hidden',"$uname:$udom",$numhidden)
 2802:                    .'</span><br />');
 2803:             }
 2804: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 2805: 	    my ($subject,$message,$msgstatus) = ('','','');
 2806: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 2807:             my ($feedurl,$showsymb) =
 2808: 		&get_feedurl_and_symb($symb,$uname,$udom);
 2809: 	    my $messagetail;
 2810: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 2811: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 2812: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 2813: 		$subject.=' ['.$restitle.']';
 2814: 		my (@msgnum) = split(/,/,$includemsg);
 2815: 		foreach (@msgnum) {
 2816: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 2817: 		}
 2818: 		$message =&Apache::lonfeedback::clear_out_html($message);
 2819: 		if ($env{'form.withgrades'.$ctr}) {
 2820: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 2821: 		    $messagetail = " for <a href=\"".
 2822: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
 2823: 		}
 2824: 		$msgstatus = 
 2825:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 2826: 						     $message.$messagetail,
 2827:                                                      undef,$feedurl,undef,
 2828:                                                      undef,undef,$showsymb,
 2829:                                                      $restitle);
 2830: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
 2831: 				$msgstatus.'<br />');
 2832: 	    }
 2833: 	    if ($env{'form.collaborator'.$ctr}) {
 2834: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 2835: 		foreach my $collabstr (@collabstrs) {
 2836: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 2837: 		    foreach my $collaborator (@collaborators) {
 2838: 			my ($errorflag,$pts,$wgt) = 
 2839: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 2840: 					   $env{'form.unamedom'.$ctr},$part);
 2841: 			if ($errorflag eq 'not_allowed') {
 2842: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 2843: 			    next;
 2844: 			} elsif ($message ne '') {
 2845: 			    my ($baseurl,$showsymb) = 
 2846: 				&get_feedurl_and_symb($symb,$collaborator,
 2847: 						      $udom);
 2848: 			    if ($env{'form.withgrades'.$ctr}) {
 2849: 				$messagetail = " for <a href=\"".
 2850:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
 2851: 			    }
 2852: 			    $msgstatus = 
 2853: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 2854: 			}
 2855: 		    }
 2856: 		}
 2857: 	    }
 2858: 	    $ctr++;
 2859: 	}
 2860:     }
 2861: 
 2862: #    if ($env{'form.handgrade'} eq 'yes') {
 2863:     if (1) {
 2864: 	# Keywords sorted in alphabatical order
 2865: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2866: 	my %keyhash = ();
 2867: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 2868: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 2869: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 2870: 	$env{'form.keywords'} = join(' ',@keywords);
 2871: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 2872: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 2873: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 2874: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 2875: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 2876: 
 2877: 	# message center - Order of message gets changed. Blank line is eliminated.
 2878: 	# New messages are saved in env for the next student.
 2879: 	# All messages are saved in nohist_handgrade.db
 2880: 	my ($ctr,$idx) = (1,1);
 2881: 	while ($ctr <= $env{'form.savemsgN'}) {
 2882: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 2883: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 2884: 		$idx++;
 2885: 	    }
 2886: 	    $ctr++;
 2887: 	}
 2888: 	$ctr = 0;
 2889: 	while ($ctr < $ngrade) {
 2890: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 2891: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2892: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2893: 		$idx++;
 2894: 	    }
 2895: 	    $ctr++;
 2896: 	}
 2897: 	$env{'form.savemsgN'} = --$idx;
 2898: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 2899: 	my $putresult = &Apache::lonnet::put
 2900: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 2901:     }
 2902:     # Called by Save & Refresh from Highlight Attribute Window
 2903:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 2904:     if ($env{'form.refresh'} eq 'on') {
 2905: 	my ($ctr,$total) = (0,0);
 2906: 	while ($ctr < $ngrade) {
 2907: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 2908: 	    $ctr++;
 2909: 	}
 2910: 	$env{'form.NTSTU'}=$ngrade;
 2911: 	$ctr = 0;
 2912: 	while ($ctr < $total) {
 2913: 	    my $processUser = $env{'form.unamedom'.$ctr};
 2914: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2915: 	    $env{'form.fullname'} = $$fullname{$processUser};
 2916: 	    &submission($request,$ctr,$total-1,$symb);
 2917: 	    $ctr++;
 2918: 	}
 2919: 	return '';
 2920:     }
 2921: 
 2922:     # Get the next/previous one or group of students
 2923:     my $firststu = $env{'form.unamedom0'};
 2924:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 2925:     my $ctr = 2;
 2926:     while ($laststu eq '') {
 2927: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 2928: 	$ctr++;
 2929: 	$laststu = $firststu if ($ctr > $ngrade);
 2930:     }
 2931: 
 2932:     my (@parsedlist,@nextlist);
 2933:     my ($nextflg) = 0;
 2934:     foreach my $item (sort 
 2935: 	     {
 2936: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 2937: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 2938: 		 }
 2939: 		 return $a cmp $b;
 2940: 	     } (keys(%$fullname))) {
 2941: # FIXME: this is fishy, looks like the button label
 2942: 	if ($nextflg == 1 && $button =~ /Next$/) {
 2943: 	    push(@parsedlist,$item);
 2944: 	}
 2945: 	$nextflg = 1 if ($item eq $laststu);
 2946: 	if ($button eq 'Previous') {
 2947: 	    last if ($item eq $firststu);
 2948: 	    push(@parsedlist,$item);
 2949: 	}
 2950:     }
 2951:     $ctr = 0;
 2952: # FIXME: this is fishy, looks like the button label
 2953:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 2954:     my $res_error;
 2955:     my ($partlist) = &response_type($symb,\$res_error);
 2956:     if ($res_error) {
 2957:         $request->print(&navmap_errormsg());
 2958:         return;
 2959:     }
 2960:     foreach my $student (@parsedlist) {
 2961: 	my $submitonly=$env{'form.submitonly'};
 2962: 	my ($uname,$udom) = split(/:/,$student);
 2963: 	
 2964: 	if ($submitonly eq 'queued') {
 2965: 	    my %queue_status = 
 2966: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 2967: 							$udom,$uname);
 2968: 	    next if (!defined($queue_status{'gradingqueue'}));
 2969: 	}
 2970: 
 2971: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 2972: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2973: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 2974: 	    my $submitted = 0;
 2975: 	    my $ungraded = 0;
 2976: 	    my $incorrect = 0;
 2977: 	    foreach my $item (keys(%status)) {
 2978: 		$submitted = 1 if ($status{$item} ne 'nothing');
 2979: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 2980: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 2981: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 2982: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 2983: 		    $submitted = 0;
 2984: 		}
 2985: 	    }
 2986: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 2987: 				     $submitonly eq 'incorrect' ||
 2988: 				     $submitonly eq 'graded'));
 2989: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 2990: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 2991: 	}
 2992: 	push(@nextlist,$student) if ($ctr < $ntstu);
 2993: 	last if ($ctr == $ntstu);
 2994: 	$ctr++;
 2995:     }
 2996: 
 2997:     $ctr = 0;
 2998:     my $total = scalar(@nextlist)-1;
 2999: 
 3000:     foreach (sort(@nextlist)) {
 3001: 	my ($uname,$udom,$submitter) = split(/:/);
 3002: 	$env{'form.student'}  = $uname;
 3003: 	$env{'form.userdom'}  = $udom;
 3004: 	$env{'form.fullname'} = $$fullname{$_};
 3005: 	&submission($request,$ctr,$total,$symb);
 3006: 	$ctr++;
 3007:     }
 3008:     if ($total < 0) {
 3009: 	my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
 3010: 	$request->print($the_end);
 3011:     }
 3012:     return '';
 3013: }
 3014: 
 3015: #---- Save the score and award for each student, if changed
 3016: sub saveHandGrade {
 3017:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 3018:     my @version_parts;
 3019:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 3020: 					   $env{'request.course.id'});
 3021:     if (!&canmodify($usec)) { return('not_allowed'); }
 3022:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 3023:     my @parts_graded;
 3024:     my %newrecord  = ();
 3025:     my ($pts,$wgt,$totchg) = ('','',0);
 3026:     my %aggregate = ();
 3027:     my $aggregateflag = 0;
 3028:     if ($env{'form.HIDE'.$newflg}) {
 3029:         my ($version,$parts) = split(/:/,$env{'form.HIDE'.$newflg},2);
 3030:         my $numchgs = &makehidden($version,$parts,\%record,$symb,$domain,$stuname,1);
 3031:         $totchg += $numchgs;
 3032:     }
 3033:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 3034:     foreach my $new_part (@parts) {
 3035: 	#collaborator ($submi may vary for different parts
 3036: 	if ($submitter && $new_part ne $part) { next; }
 3037: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 3038: 	if ($dropMenu eq 'excused') {
 3039: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 3040: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 3041: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 3042: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 3043: 		}
 3044: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3045: 	    }
 3046: 	} elsif ($dropMenu eq 'reset status'
 3047: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 3048: 	    foreach my $key (keys(%record)) {
 3049: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 3050: 	    }
 3051: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3052: 		"$env{'user.name'}:$env{'user.domain'}";
 3053:             my $totaltries = $record{'resource.'.$part.'.tries'};
 3054: 
 3055:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 3056: 					       [$new_part]);
 3057:             my $aggtries =$totaltries;
 3058:             if ($last_resets{$new_part}) {
 3059:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 3060: 					   $new_part);
 3061:             }
 3062: 
 3063:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 3064:             if ($aggtries > 0) {
 3065:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3066:                 $aggregateflag = 1;
 3067:             }
 3068: 	} elsif ($dropMenu eq '') {
 3069: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 3070: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 3071: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 3072: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 3073: 		next;
 3074: 	    }
 3075: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 3076: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 3077: 	    my $partial= $pts/$wgt;
 3078: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 3079: 		#do not update score for part if not changed.
 3080:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 3081: 		next;
 3082: 	    } else {
 3083: 	        push(@parts_graded,$new_part);
 3084: 	    }
 3085: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 3086: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 3087: 	    }
 3088: 	    my $reckey = 'resource.'.$new_part.'.solved';
 3089: 	    if ($partial == 0) {
 3090: 		if ($record{$reckey} ne 'incorrect_by_override') {
 3091: 		    $newrecord{$reckey} = 'incorrect_by_override';
 3092: 		}
 3093: 	    } else {
 3094: 		if ($record{$reckey} ne 'correct_by_override') {
 3095: 		    $newrecord{$reckey} = 'correct_by_override';
 3096: 		}
 3097: 	    }	    
 3098: 	    if ($submitter && 
 3099: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 3100: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 3101: 	    }
 3102: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3103: 		"$env{'user.name'}:$env{'user.domain'}";
 3104: 	}
 3105: 	# unless problem has been graded, set flag to version the submitted files
 3106: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 3107: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 3108: 	        $dropMenu eq 'reset status')
 3109: 	   {
 3110: 	    push(@version_parts,$new_part);
 3111: 	}
 3112:     }
 3113:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3114:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3115: 
 3116:     if (%newrecord) {
 3117:         if (@version_parts) {
 3118:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 3119:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 3120: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 3121: 	    foreach my $new_part (@version_parts) {
 3122: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 3123: 				$new_part,\%newrecord);
 3124: 	    }
 3125:         }
 3126: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 3127: 				$env{'request.course.id'},$domain,$stuname);
 3128: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 3129: 				     $cdom,$cnum,$domain,$stuname);
 3130:     }
 3131:     if ($aggregateflag) {
 3132:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3133: 			      $cdom,$cnum);
 3134:     }
 3135:     return ('',$pts,$wgt,$totchg);
 3136: }
 3137: 
 3138: sub makehidden {
 3139:     my ($version,$parts,$record,$symb,$domain,$stuname,$tolog) = @_;
 3140:     return unless (ref($record) eq 'HASH');
 3141:     my %modified;
 3142:     my $numchanged = 0;
 3143:     if (exists($record->{$version.':keys'})) {
 3144:         my $partsregexp = $parts;
 3145:         $partsregexp =~ s/,/|/g;
 3146:         foreach my $key (split(/\:/,$record->{$version.':keys'})) {
 3147:             if ($key =~ /^resource\.(?:$partsregexp)\.([^\.]+)$/) {
 3148:                  my $item = $1;
 3149:                  unless (($item eq 'solved') || ($item =~ /^award(|msg|ed)$/)) {
 3150:                      $modified{$key} = $record->{$version.':'.$key};
 3151:                  }
 3152:             } elsif ($key =~ m{^(resource\.(?:$partsregexp)\.[^\.]+\.)(.+)$}) {
 3153:                 $modified{$1.'hidden'.$2} = $record->{$version.':'.$key};
 3154:             } elsif ($key =~ /^(ip|timestamp|host)$/) {
 3155:                 $modified{$key} = $record->{$version.':'.$key};
 3156:             }
 3157:         }
 3158:         if (keys(%modified)) {
 3159:             if (&Apache::lonnet::putstore($env{'request.course.id'},$symb,$version,\%modified,
 3160:                                           $domain,$stuname,$tolog) eq 'ok') {
 3161:                 $numchanged ++;
 3162:             }
 3163:         }
 3164:     }
 3165:     return $numchanged;
 3166: }
 3167: 
 3168: sub check_and_remove_from_queue {
 3169:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 3170:     my @ungraded_parts;
 3171:     foreach my $part (@{$parts}) {
 3172: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 3173: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 3174: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 3175: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 3176: 		) {
 3177: 	    push(@ungraded_parts, $part);
 3178: 	}
 3179:     }
 3180:     if ( !@ungraded_parts ) {
 3181: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 3182: 					       $cnum,$domain,$stuname);
 3183:     }
 3184: }
 3185: 
 3186: sub handback_files {
 3187:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 3188:     my $portfolio_root = '/userfiles/portfolio';
 3189:     my $res_error;
 3190:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3191:     if ($res_error) {
 3192:         $request->print('<br />'.&navmap_errormsg().'<br />');
 3193:         return;
 3194:     }
 3195:     my @handedback;
 3196:     my $file_msg;
 3197:     my @part_response_id = &flatten_responseType($responseType);
 3198:     foreach my $part_response_id (@part_response_id) {
 3199:     	my ($part_id,$resp_id) = @{ $part_response_id };
 3200: 	my $part_resp = join('_',@{ $part_response_id });
 3201:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
 3202:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
 3203:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3' 
 3204:                 if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
 3205:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
 3206:                     my ($directory,$answer_file) = 
 3207:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
 3208:                     my ($answer_name,$answer_ver,$answer_ext) =
 3209: 		        &Apache::lonnet::file_name_version_ext($answer_file);
 3210: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 3211:                     my $getpropath = 1;
 3212:                     my ($dir_list,$listerror) = 
 3213:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
 3214:                                                  $domain,$stuname,$getpropath);
 3215: 		    my $version = &Apache::lonnet::get_next_version($answer_name,$answer_ext,$dir_list);
 3216:                     # fix filename
 3217:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 3218:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 3219:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
 3220:             	                                $save_file_name);
 3221:                     if ($result !~ m|^/uploaded/|) {
 3222:                         $request->print('<br /><span class="LC_error">'.
 3223:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 3224:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
 3225:                                         '</span>');
 3226:                     } else {
 3227:                         # mark the file as read only
 3228:                         push(@handedback,$save_file_name);
 3229: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 3230: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 3231: 			}
 3232:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 3233: 			$file_msg.= '<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
 3234:                     }
 3235:                     $request->print('<br />'.&mt('[_1] will be the uploaded filename [_2]','<span class="LC_info">'.$fname.'</span>','<span class="LC_filename">'.$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter}.'</span>'));
 3236:                 }
 3237:             }
 3238:         }
 3239:     }
 3240:     if (@handedback > 0) {
 3241:         $request->print('<br />');
 3242:         my @what = ($symb,$env{'request.course.id'},'handback');
 3243:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
 3244:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});    
 3245:         my ($subject,$message);
 3246:         if (scalar(@handedback) == 1) {
 3247:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
 3248:             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
 3249:         } else {
 3250:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
 3251:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
 3252:         }
 3253:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
 3254:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
 3255:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
 3256:         my ($feedurl,$showsymb) =
 3257:             &get_feedurl_and_symb($symb,$domain,$stuname);
 3258:         my $restitle = &Apache::lonnet::gettitle($symb);
 3259:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
 3260:         my $msgstatus =
 3261:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
 3262:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
 3263:                  $restitle);
 3264:         if ($msgstatus) {
 3265:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
 3266:         }
 3267:     }
 3268:     return;
 3269: }
 3270: 
 3271: sub get_feedurl_and_symb {
 3272:     my ($symb,$uname,$udom) = @_;
 3273:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3274:     $url = &Apache::lonnet::clutter($url);
 3275:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 3276: 					$symb,$udom,$uname);
 3277:     if ($encrypturl =~ /^yes$/i) {
 3278: 	&Apache::lonenc::encrypted(\$url,1);
 3279: 	&Apache::lonenc::encrypted(\$symb,1);
 3280:     }
 3281:     return ($url,$symb);
 3282: }
 3283: 
 3284: sub get_submitted_files {
 3285:     my ($udom,$uname,$partid,$respid,$record) = @_;
 3286:     my @files;
 3287:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 3288:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 3289:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 3290:     	    push(@files,$file_url.$file);
 3291:         }
 3292:     }
 3293:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 3294:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 3295:     }
 3296:     return (\@files);
 3297: }
 3298: 
 3299: # ----------- Provides number of tries since last reset.
 3300: sub get_num_tries {
 3301:     my ($record,$last_reset,$part) = @_;
 3302:     my $timestamp = '';
 3303:     my $num_tries = 0;
 3304:     if ($$record{'version'}) {
 3305:         for (my $version=$$record{'version'};$version>=1;$version--) {
 3306:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 3307:                 $timestamp = $$record{$version.':timestamp'};
 3308:                 if ($timestamp > $last_reset) {
 3309:                     $num_tries ++;
 3310:                 } else {
 3311:                     last;
 3312:                 }
 3313:             }
 3314:         }
 3315:     }
 3316:     return $num_tries;
 3317: }
 3318: 
 3319: # ----------- Determine decrements required in aggregate totals 
 3320: sub decrement_aggs {
 3321:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 3322:     my %decrement = (
 3323:                         attempts => 0,
 3324:                         users => 0,
 3325:                         correct => 0
 3326:                     );
 3327:     $decrement{'attempts'} = $aggtries;
 3328:     if ($solvedstatus =~ /^correct/) {
 3329:         $decrement{'correct'} = 1;
 3330:     }
 3331:     if ($aggtries == $totaltries) {
 3332:         $decrement{'users'} = 1;
 3333:     }
 3334:     foreach my $type (keys(%decrement)) {
 3335:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 3336:     }
 3337:     return;
 3338: }
 3339: 
 3340: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 3341: sub get_last_resets {
 3342:     my ($symb,$courseid,$partids) =@_;
 3343:     my %last_resets;
 3344:     my $cdom = $env{'course.'.$courseid.'.domain'};
 3345:     my $cname = $env{'course.'.$courseid.'.num'};
 3346:     my @keys;
 3347:     foreach my $part (@{$partids}) {
 3348: 	push(@keys,"$symb\0$part\0resettime");
 3349:     }
 3350:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 3351: 				     $cdom,$cname);
 3352:     foreach my $part (@{$partids}) {
 3353: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 3354:     }
 3355:     return %last_resets;
 3356: }
 3357: 
 3358: # ----------- Handles creating versions for portfolio files as answers
 3359: sub version_portfiles {
 3360:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 3361:     my $version_parts = join('|',@$v_flag);
 3362:     my @returned_keys;
 3363:     my $parts = join('|', @$parts_graded);
 3364:     foreach my $key (keys(%$record)) {
 3365:         my $new_portfiles;
 3366:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 3367:             my @versioned_portfiles;
 3368:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 3369:             if (@portfiles) {
 3370:                 &Apache::lonnet::portfiles_versioning($symb,$domain,$stu_name,\@portfiles,
 3371:                                                       \@versioned_portfiles);
 3372:             }
 3373:             $$record{$key} = join(',',@versioned_portfiles);
 3374:             push(@returned_keys,$key);
 3375:         }
 3376:     } 
 3377:     return (@returned_keys);   
 3378: }
 3379: 
 3380: #--------------------------------------------------------------------------------------
 3381: #
 3382: #-------------------------- Next few routines handles grading by section or whole class
 3383: #
 3384: #--- Javascript to handle grading by section or whole class
 3385: sub viewgrades_js {
 3386:     my ($request) = shift;
 3387: 
 3388:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3389:     &js_escape(\$alertmsg);
 3390:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
 3391:    function writePoint(partid,weight,point) {
 3392: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3393: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3394: 	if (point == "textval") {
 3395: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3396: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3397: 		alert("$alertmsg"+parseFloat(point));
 3398: 		var resetbox = false;
 3399: 		for (var i=0; i<radioButton.length; i++) {
 3400: 		    if (radioButton[i].checked) {
 3401: 			textbox.value = i;
 3402: 			resetbox = true;
 3403: 		    }
 3404: 		}
 3405: 		if (!resetbox) {
 3406: 		    textbox.value = "";
 3407: 		}
 3408: 		return;
 3409: 	    }
 3410: 	    if (parseFloat(point) > parseFloat(weight)) {
 3411: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3412: 				   ") greater than the weight for the part. Accept?");
 3413: 		if (resp == false) {
 3414: 		    textbox.value = "";
 3415: 		    return;
 3416: 		}
 3417: 	    }
 3418: 	    for (var i=0; i<radioButton.length; i++) {
 3419: 		radioButton[i].checked=false;
 3420: 		if (parseFloat(point) == i) {
 3421: 		    radioButton[i].checked=true;
 3422: 		}
 3423: 	    }
 3424: 
 3425: 	} else {
 3426: 	    textbox.value = parseFloat(point);
 3427: 	}
 3428: 	for (i=0;i<document.classgrade.total.value;i++) {
 3429: 	    var user = document.classgrade["ctr"+i].value;
 3430: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3431: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3432: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3433: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3434: 	    if (saveval != "correct") {
 3435: 		scorename.value = point;
 3436: 		if (selname[0].selected != true) {
 3437: 		    selname[0].selected = true;
 3438: 		}
 3439: 	    }
 3440: 	}
 3441: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3442:     }
 3443: 
 3444:     function writeRadText(partid,weight) {
 3445: 	var selval   = document.classgrade["SELVAL_"+partid];
 3446: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3447:         var override = document.classgrade["FORCE_"+partid].checked;
 3448: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3449: 	if (selval[1].selected || selval[2].selected) {
 3450: 	    for (var i=0; i<radioButton.length; i++) {
 3451: 		radioButton[i].checked=false;
 3452: 
 3453: 	    }
 3454: 	    textbox.value = "";
 3455: 
 3456: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3457: 		var user = document.classgrade["ctr"+i].value;
 3458: 		user = user.replace(new RegExp(':', 'g'),"_");
 3459: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3460: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3461: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3462: 		if ((saveval != "correct") || override) {
 3463: 		    scorename.value = "";
 3464: 		    if (selval[1].selected) {
 3465: 			selname[1].selected = true;
 3466: 		    } else {
 3467: 			selname[2].selected = true;
 3468: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3469: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3470: 		    }
 3471: 		}
 3472: 	    }
 3473: 	} else {
 3474: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3475: 		var user = document.classgrade["ctr"+i].value;
 3476: 		user = user.replace(new RegExp(':', 'g'),"_");
 3477: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3478: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3479: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3480: 		if ((saveval != "correct") || override) {
 3481: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3482: 		    selname[0].selected = true;
 3483: 		}
 3484: 	    }
 3485: 	}	    
 3486:     }
 3487: 
 3488:     function changeSelect(partid,user) {
 3489: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3490: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3491: 	var point  = textbox.value;
 3492: 	var weight = document.classgrade["weight_"+partid].value;
 3493: 
 3494: 	if (isNaN(point) || parseFloat(point) < 0) {
 3495: 	    alert("$alertmsg"+parseFloat(point));
 3496: 	    textbox.value = "";
 3497: 	    return;
 3498: 	}
 3499: 	if (parseFloat(point) > parseFloat(weight)) {
 3500: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3501: 			       ") greater than the weight of the part. Accept?");
 3502: 	    if (resp == false) {
 3503: 		textbox.value = "";
 3504: 		return;
 3505: 	    }
 3506: 	}
 3507: 	selval[0].selected = true;
 3508:     }
 3509: 
 3510:     function changeOneScore(partid,user) {
 3511: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3512: 	if (selval[1].selected || selval[2].selected) {
 3513: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3514: 	    if (selval[2].selected) {
 3515: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3516: 	    }
 3517:         }
 3518:     }
 3519: 
 3520:     function resetEntry(numpart) {
 3521: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3522: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3523: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3524: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3525: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3526: 	    for (var i=0; i<radioButton.length; i++) {
 3527: 		radioButton[i].checked=false;
 3528: 
 3529: 	    }
 3530: 	    textbox.value = "";
 3531: 	    selval[0].selected = true;
 3532: 
 3533: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3534: 		var user = document.classgrade["ctr"+i].value;
 3535: 		user = user.replace(new RegExp(':', 'g'),"_");
 3536: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3537: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3538: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3539: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3540: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3541: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3542: 		if (saveselval == "excused") {
 3543: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3544: 		} else {
 3545: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3546: 		}
 3547: 	    }
 3548: 	}
 3549:     }
 3550: 
 3551: VIEWJAVASCRIPT
 3552: }
 3553: 
 3554: #--- show scores for a section or whole class w/ option to change/update a score
 3555: sub viewgrades {
 3556:     my ($request,$symb) = @_;
 3557:     &viewgrades_js($request);
 3558: 
 3559:     #need to make sure we have the correct data for later EXT calls, 
 3560:     #thus invalidate the cache
 3561:     &Apache::lonnet::devalidatecourseresdata(
 3562:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3563:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3564:     &Apache::lonnet::clear_EXT_cache_status();
 3565: 
 3566:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3567: 
 3568:     #view individual student submission form - called using Javascript viewOneStudent
 3569:     $result.=&jscriptNform($symb);
 3570: 
 3571:     #beginning of class grading form
 3572:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3573:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3574: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3575: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3576: 	&build_section_inputs().
 3577: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3578: 
 3579:     my ($common_header,$specific_header);
 3580:     if ($env{'form.section'} eq 'all') {
 3581: 	$common_header = &mt('Assign Common Grade to Class');
 3582:         $specific_header = &mt('Assign Grade to Specific Students in Class');
 3583:     } elsif ($env{'form.section'} eq 'none') {
 3584:         $common_header = &mt('Assign Common Grade to Students in no Section');
 3585: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
 3586:     } else {
 3587:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3588:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
 3589: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
 3590:     }
 3591:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
 3592:     #radio buttons/text box for assigning points for a section or class.
 3593:     #handles different parts of a problem
 3594:     my $res_error;
 3595:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3596:     if ($res_error) {
 3597:         return &navmap_errormsg();
 3598:     }
 3599:     my %weight = ();
 3600:     my $ctsparts = 0;
 3601:     my %seen = ();
 3602:     my @part_response_id = &flatten_responseType($responseType);
 3603:     foreach my $part_response_id (@part_response_id) {
 3604:     	my ($partid,$respid) = @{ $part_response_id };
 3605: 	my $part_resp = join('_',@{ $part_response_id });
 3606: 	next if $seen{$partid};
 3607: 	$seen{$partid}++;
 3608: 	my $handgrade=$$handgrade{$part_resp};
 3609: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 3610: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 3611: 
 3612: 	my $display_part=&get_display_part($partid,$symb);
 3613: 	my $radio.='<table border="0"><tr>';  
 3614: 	my $ctr = 0;
 3615: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 3616: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 3617: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 3618: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 3619: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 3620: 	    $ctr++;
 3621: 	}
 3622: 	$radio.='</tr></table>';
 3623: 	my $line = '<input type="text" name="TEXTVAL_'.
 3624: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
 3625: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 3626: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 3627:         $line.= '<td><b>'.&mt('Grade Status').':</b>'.
 3628:             '<select name="SELVAL_'.$partid.'" '.
 3629:             'onchange="javascript:writeRadText(\''.$partid.'\','.
 3630:                 $weight{$partid}.')"> '.
 3631: 	    '<option selected="selected"> </option>'.
 3632: 	    '<option value="excused">'.&mt('excused').'</option>'.
 3633: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 3634: 	    '</select></td>'.
 3635:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 3636: 	$line.='<input type="hidden" name="partid_'.
 3637: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 3638: 	$line.='<input type="hidden" name="weight_'.
 3639: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 3640: 
 3641: 	$result.=
 3642: 	    &Apache::loncommon::start_data_table_row()."\n".
 3643: 	    '<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>'.
 3644: 	    &Apache::loncommon::end_data_table_row()."\n";
 3645: 	$ctsparts++;
 3646:     }
 3647:     $result.=&Apache::loncommon::end_data_table()."\n".
 3648: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 3649:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 3650: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
 3651: 
 3652:     #table listing all the students in a section/class
 3653:     #header of table
 3654:     $result.= '<h3>'.$specific_header.'</h3>'.
 3655:               &Apache::loncommon::start_data_table().
 3656: 	      &Apache::loncommon::start_data_table_header_row().
 3657: 	      '<th>'.&mt('No.').'</th>'.
 3658: 	      '<th>'.&nameUserString('header')."</th>\n";
 3659:     my $partserror;
 3660:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3661:     if ($partserror) {
 3662:         return &navmap_errormsg();
 3663:     }
 3664:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 3665:     my @partids = ();
 3666:     foreach my $part (@parts) {
 3667: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3668:         my $narrowtext = &mt('Tries');
 3669: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 3670: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 3671: 	my ($partid) = &split_part_type($part);
 3672:         push(@partids,$partid);
 3673: #
 3674: # FIXME: Looks like $display looks at English text
 3675: #
 3676: 	my $display_part=&get_display_part($partid,$symb);
 3677: 	if ($display =~ /^Partial Credit Factor/) {
 3678: 	    $result.='<th>'.
 3679: 		&mt('Score Part: [_1][_2](weight = [_3])',
 3680: 		    $display_part,'<br />',$weight{$partid}).'</th>'."\n";
 3681: 	    next;
 3682: 	    
 3683: 	} else {
 3684: 	    if ($display =~ /Problem Status/) {
 3685: 		my $grade_status_mt = &mt('Grade Status');
 3686: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 3687: 	    }
 3688: 	    my $part_mt = &mt('Part:');
 3689: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 3690: 	}
 3691: 
 3692: 	$result.='<th>'.$display.'</th>'."\n";
 3693:     }
 3694:     $result.=&Apache::loncommon::end_data_table_header_row();
 3695: 
 3696:     my %last_resets = 
 3697: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 3698: 
 3699:     #get info for each student
 3700:     #list all the students - with points and grade status
 3701:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3702:     my $ctr = 0;
 3703:     foreach (sort 
 3704: 	     {
 3705: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3706: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3707: 		 }
 3708: 		 return $a cmp $b;
 3709: 	     } (keys(%$fullname))) {
 3710: 	$ctr++;
 3711: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 3712: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
 3713:     }
 3714:     $result.=&Apache::loncommon::end_data_table();
 3715:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 3716:     $result.='<input type="button" value="'.&mt('Save').'" '.
 3717: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
 3718:     if (scalar(%$fullname) eq 0) {
 3719: 	my $colspan=3+scalar(@parts);
 3720: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3721:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 3722: 	$result='<span class="LC_warning">'.
 3723: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 3724: 	        $section_display, $stu_status).
 3725: 	    '</span>';
 3726:     }
 3727:     return $result;
 3728: }
 3729: 
 3730: #--- call by previous routine to display each student
 3731: sub viewstudentgrade {
 3732:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 3733:     my ($uname,$udom) = split(/:/,$student);
 3734:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 3735:     my %aggregates = (); 
 3736:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 3737: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
 3738: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
 3739: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 3740: 	'\');" target="_self">'.$fullname.'</a> '.
 3741: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 3742:     $student=~s/:/_/; # colon doen't work in javascript for names
 3743:     foreach my $apart (@$parts) {
 3744: 	my ($part,$type) = &split_part_type($apart);
 3745: 	my $score=$record{"resource.$part.$type"};
 3746:         $result.='<td align="center">';
 3747:         my ($aggtries,$totaltries);
 3748:         unless (exists($aggregates{$part})) {
 3749: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 3750: 
 3751: 	    $aggtries = $totaltries;
 3752:             if ($$last_resets{$part}) {  
 3753:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 3754: 					   $part);
 3755:             }
 3756:             $result.='<input type="hidden" name="'.
 3757:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 3758:             $result.='<input type="hidden" name="'.
 3759:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 3760:             $aggregates{$part} = 1;
 3761:         }
 3762: 	if ($type eq 'awarded') {
 3763: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 3764: 	    $result.='<input type="hidden" name="'.
 3765: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 3766: 	    $result.='<input type="text" name="'.
 3767: 		'GD_'.$student.'_'.$part.'_awarded" '.
 3768:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
 3769: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 3770: 	} elsif ($type eq 'solved') {
 3771: 	    my ($status,$foo)=split(/_/,$score,2);
 3772: 	    $status = 'nothing' if ($status eq '');
 3773: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 3774: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 3775: 	    $result.='&nbsp;<select name="'.
 3776: 		'GD_'.$student.'_'.$part.'_solved" '.
 3777:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 3778: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 3779: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 3780: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 3781: 	    $result.="</select>&nbsp;</td>\n";
 3782: 	} else {
 3783: 	    $result.='<input type="hidden" name="'.
 3784: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 3785: 		    "\n";
 3786: 	    $result.='<input type="text" name="'.
 3787: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 3788: 		'value="'.$score.'" size="4" /></td>'."\n";
 3789: 	}
 3790:     }
 3791:     $result.=&Apache::loncommon::end_data_table_row();
 3792:     return $result;
 3793: }
 3794: 
 3795: #--- change scores for all the students in a section/class
 3796: #    record does not get update if unchanged
 3797: sub editgrades {
 3798:     my ($request,$symb) = @_;
 3799: 
 3800:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3801:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 3802:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
 3803: 
 3804:     my $result= &Apache::loncommon::start_data_table().
 3805: 	&Apache::loncommon::start_data_table_header_row().
 3806: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 3807: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 3808:     my %scoreptr = (
 3809: 		    'correct'  =>'correct_by_override',
 3810: 		    'incorrect'=>'incorrect_by_override',
 3811: 		    'excused'  =>'excused',
 3812: 		    'ungraded' =>'ungraded_attempted',
 3813:                     'credited' =>'credit_attempted',
 3814: 		    'nothing'  => '',
 3815: 		    );
 3816:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 3817: 
 3818:     my (@partid);
 3819:     my %weight = ();
 3820:     my %columns = ();
 3821:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 3822: 
 3823:     my $partserror;
 3824:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3825:     if ($partserror) {
 3826:         return &navmap_errormsg();
 3827:     }
 3828:     my $header;
 3829:     while ($ctr < $env{'form.totalparts'}) {
 3830: 	my $partid = $env{'form.partid_'.$ctr};
 3831: 	push(@partid,$partid);
 3832: 	$weight{$partid} = $env{'form.weight_'.$partid};
 3833: 	$ctr++;
 3834:     }
 3835:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3836:     foreach my $partid (@partid) {
 3837: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 3838: 	    '<th align="center">'.&mt('New Score').'</th>';
 3839: 	$columns{$partid}=2;
 3840: 	foreach my $stores (@parts) {
 3841: 	    my ($part,$type) = &split_part_type($stores);
 3842: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 3843: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 3844: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 3845: 	    $display =~ s/\[Part: \Q$part\E\]//;
 3846:             my $narrowtext = &mt('Tries');
 3847: 	    $display =~ s/Number of Attempts/$narrowtext/;
 3848: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 3849: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 3850: 	    $columns{$partid}+=2;
 3851: 	}
 3852:     }
 3853:     foreach my $partid (@partid) {
 3854: 	my $display_part=&get_display_part($partid,$symb);
 3855: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 3856: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 3857: 	    '</th>';
 3858: 
 3859:     }
 3860:     $result .= &Apache::loncommon::end_data_table_header_row().
 3861: 	&Apache::loncommon::start_data_table_header_row().
 3862: 	$header.
 3863: 	&Apache::loncommon::end_data_table_header_row();
 3864:     my @noupdate;
 3865:     my ($updateCtr,$noupdateCtr) = (1,1);
 3866:     for ($i=0; $i<$env{'form.total'}; $i++) {
 3867: 	my $line;
 3868: 	my $user = $env{'form.ctr'.$i};
 3869: 	my ($uname,$udom)=split(/:/,$user);
 3870: 	my %newrecord;
 3871: 	my $updateflag = 0;
 3872: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 3873: 	my $usec=$classlist->{"$uname:$udom"}[5];
 3874: 	if (!&canmodify($usec)) {
 3875: 	    my $numcols=scalar(@partid)*4+2;
 3876: 	    push(@noupdate,
 3877: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
 3878: 		 &mt('Not allowed to modify student')."</span></td></tr>");
 3879: 	    next;
 3880: 	}
 3881:         my %aggregate = ();
 3882:         my $aggregateflag = 0;
 3883: 	$user=~s/:/_/; # colon doen't work in javascript for names
 3884: 	foreach (@partid) {
 3885: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 3886: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 3887: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 3888: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3889: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 3890: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 3891: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 3892: 	    my $score;
 3893: 	    if ($partial eq '') {
 3894: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3895: 	    } elsif ($partial > 0) {
 3896: 		$score = 'correct_by_override';
 3897: 	    } elsif ($partial == 0) {
 3898: 		$score = 'incorrect_by_override';
 3899: 	    }
 3900: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 3901: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 3902: 
 3903: 	    $newrecord{'resource.'.$_.'.regrader'}=
 3904: 		"$env{'user.name'}:$env{'user.domain'}";
 3905: 	    if ($dropMenu eq 'reset status' &&
 3906: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 3907: 		$newrecord{'resource.'.$_.'.tries'} = '';
 3908: 		$newrecord{'resource.'.$_.'.solved'} = '';
 3909: 		$newrecord{'resource.'.$_.'.award'} = '';
 3910: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 3911: 		$updateflag = 1;
 3912:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 3913:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 3914:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 3915:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 3916:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3917:                     $aggregateflag = 1;
 3918:                 }
 3919: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 3920: 		$updateflag = 1;
 3921: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 3922: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 3923: 		$rec_update++;
 3924: 	    }
 3925: 
 3926: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3927: 		'<td align="center">'.$awarded.
 3928: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 3929: 
 3930: 
 3931: 	    my $partid=$_;
 3932: 	    foreach my $stores (@parts) {
 3933: 		my ($part,$type) = &split_part_type($stores);
 3934: 		if ($part !~ m/^\Q$partid\E/) { next;}
 3935: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 3936: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 3937: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 3938: 		if ($awarded ne '' && $awarded ne $old_aw) {
 3939: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 3940: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3941: 		    $updateflag=1;
 3942: 		}
 3943: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3944: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 3945: 	    }
 3946: 	}
 3947: 	$line.="\n";
 3948: 
 3949: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3950: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3951: 
 3952: 	if ($updateflag) {
 3953: 	    $count++;
 3954: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 3955: 				    $udom,$uname);
 3956: 
 3957: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 3958: 					      $cnum,$udom,$uname)) {
 3959: 		# need to figure out if should be in queue.
 3960: 		my %record =  
 3961: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 3962: 					     $udom,$uname);
 3963: 		my $all_graded = 1;
 3964: 		my $none_graded = 1;
 3965: 		foreach my $part (@parts) {
 3966: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 3967: 			$all_graded = 0;
 3968: 		    } else {
 3969: 			$none_graded = 0;
 3970: 		    }
 3971: 		}
 3972: 
 3973: 		if ($all_graded || $none_graded) {
 3974: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 3975: 							   $symb,$cdom,$cnum,
 3976: 							   $udom,$uname);
 3977: 		}
 3978: 	    }
 3979: 
 3980: 	    $result.=&Apache::loncommon::start_data_table_row().
 3981: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 3982: 		&Apache::loncommon::end_data_table_row();
 3983: 	    $updateCtr++;
 3984: 	} else {
 3985: 	    push(@noupdate,
 3986: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 3987: 	    $noupdateCtr++;
 3988: 	}
 3989:         if ($aggregateflag) {
 3990:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3991: 				  $cdom,$cnum);
 3992:         }
 3993:     }
 3994:     if (@noupdate) {
 3995: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
 3996: 	my $numcols=scalar(@partid)*4+2;
 3997: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 3998: 	    '<td align="center" colspan="'.$numcols.'">'.
 3999: 	    &mt('No Changes Occurred For the Students Below').
 4000: 	    '</td>'.
 4001: 	    &Apache::loncommon::end_data_table_row();
 4002: 	foreach my $line (@noupdate) {
 4003: 	    $result.=
 4004: 		&Apache::loncommon::start_data_table_row().
 4005: 		$line.
 4006: 		&Apache::loncommon::end_data_table_row();
 4007: 	}
 4008:     }
 4009:     $result .= &Apache::loncommon::end_data_table();
 4010:     my $msg = '<p><b>'.
 4011: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 4012: 	    $rec_update,$count).'</b><br />'.
 4013: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 4014: 	'</b></p>';
 4015:     return $title.$msg.$result;
 4016: }
 4017: 
 4018: sub split_part_type {
 4019:     my ($partstr) = @_;
 4020:     my ($temp,@allparts)=split(/_/,$partstr);
 4021:     my $type=pop(@allparts);
 4022:     my $part=join('_',@allparts);
 4023:     return ($part,$type);
 4024: }
 4025: 
 4026: #------------- end of section for handling grading by section/class ---------
 4027: #
 4028: #----------------------------------------------------------------------------
 4029: 
 4030: 
 4031: #----------------------------------------------------------------------------
 4032: #
 4033: #-------------------------- Next few routines handles grading by csv upload
 4034: #
 4035: #--- Javascript to handle csv upload
 4036: sub csvupload_javascript_reverse_associate {
 4037:     my $error1=&mt('You need to specify the username or the student/employee ID');
 4038:     my $error2=&mt('You need to specify at least one grading field');
 4039:   &js_escape(\$error1);
 4040:   &js_escape(\$error2);
 4041:   return(<<ENDPICK);
 4042:   function verify(vf) {
 4043:     var foundsomething=0;
 4044:     var founduname=0;
 4045:     var foundID=0;
 4046:     for (i=0;i<=vf.nfields.value;i++) {
 4047:       tw=eval('vf.f'+i+'.selectedIndex');
 4048:       if (i==0 && tw!=0) { foundID=1; }
 4049:       if (i==1 && tw!=0) { founduname=1; }
 4050:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 4051:     }
 4052:     if (founduname==0 && foundID==0) {
 4053: 	alert('$error1');
 4054: 	return;
 4055:     }
 4056:     if (foundsomething==0) {
 4057: 	alert('$error2');
 4058: 	return;
 4059:     }
 4060:     vf.submit();
 4061:   }
 4062:   function flip(vf,tf) {
 4063:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4064:     var i;
 4065:     for (i=0;i<=vf.nfields.value;i++) {
 4066:       //can not pick the same destination field for both name and domain
 4067:       if (((i ==0)||(i ==1)) && 
 4068:           ((tf==0)||(tf==1)) && 
 4069:           (i!=tf) &&
 4070:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4071:         eval('vf.f'+i+'.selectedIndex=0;')
 4072:       }
 4073:     }
 4074:   }
 4075: ENDPICK
 4076: }
 4077: 
 4078: sub csvupload_javascript_forward_associate {
 4079:     my $error1=&mt('You need to specify the username or the student/employee ID');
 4080:     my $error2=&mt('You need to specify at least one grading field');
 4081:   &js_escape(\$error1);
 4082:   &js_escape(\$error2);
 4083:   return(<<ENDPICK);
 4084:   function verify(vf) {
 4085:     var foundsomething=0;
 4086:     var founduname=0;
 4087:     var foundID=0;
 4088:     for (i=0;i<=vf.nfields.value;i++) {
 4089:       tw=eval('vf.f'+i+'.selectedIndex');
 4090:       if (tw==1) { foundID=1; }
 4091:       if (tw==2) { founduname=1; }
 4092:       if (tw>3) { foundsomething=1; }
 4093:     }
 4094:     if (founduname==0 && foundID==0) {
 4095: 	alert('$error1');
 4096: 	return;
 4097:     }
 4098:     if (foundsomething==0) {
 4099: 	alert('$error2');
 4100: 	return;
 4101:     }
 4102:     vf.submit();
 4103:   }
 4104:   function flip(vf,tf) {
 4105:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4106:     var i;
 4107:     //can not pick the same destination field twice
 4108:     for (i=0;i<=vf.nfields.value;i++) {
 4109:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4110:         eval('vf.f'+i+'.selectedIndex=0;')
 4111:       }
 4112:     }
 4113:   }
 4114: ENDPICK
 4115: }
 4116: 
 4117: sub csvuploadmap_header {
 4118:     my ($request,$symb,$datatoken,$distotal)= @_;
 4119:     my $javascript;
 4120:     if ($env{'form.upfile_associate'} eq 'reverse') {
 4121: 	$javascript=&csvupload_javascript_reverse_associate();
 4122:     } else {
 4123: 	$javascript=&csvupload_javascript_forward_associate();
 4124:     }
 4125: 
 4126:     $symb = &Apache::lonenc::check_encrypt($symb);
 4127:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
 4128:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
 4129:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
 4130:     my $reverse=&mt("Reverse Association");
 4131:     $request->print(<<ENDPICK);
 4132: <br />
 4133: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 4134: <input type="hidden" name="associate"  value="" />
 4135: <input type="hidden" name="phase"      value="three" />
 4136: <input type="hidden" name="datatoken"  value="$datatoken" />
 4137: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 4138: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 4139: <input type="hidden" name="upfile_associate" 
 4140:                                        value="$env{'form.upfile_associate'}" />
 4141: <input type="hidden" name="symb"       value="$symb" />
 4142: <input type="hidden" name="command"    value="csvuploadoptions" />
 4143: <hr />
 4144: ENDPICK
 4145:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
 4146:     return '';
 4147: 
 4148: }
 4149: 
 4150: sub csvupload_fields {
 4151:     my ($symb,$errorref) = @_;
 4152:     my (@parts) = &getpartlist($symb,$errorref);
 4153:     if (ref($errorref)) {
 4154:         if ($$errorref) {
 4155:             return;
 4156:         }
 4157:     }
 4158: 
 4159:     my @fields=(['ID','Student/Employee ID'],
 4160: 		['username','Student Username'],
 4161: 		['domain','Student Domain']);
 4162:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 4163:     foreach my $part (sort(@parts)) {
 4164: 	my @datum;
 4165: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 4166: 	my $name=$part;
 4167: 	if  (!$display) { $display = $name; }
 4168: 	@datum=($name,$display);
 4169: 	if ($name=~/^stores_(.*)_awarded/) {
 4170: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 4171: 	}
 4172: 	push(@fields,\@datum);
 4173:     }
 4174:     return (@fields);
 4175: }
 4176: 
 4177: sub csvuploadmap_footer {
 4178:     my ($request,$i,$keyfields) =@_;
 4179:     my $buttontext = &mt('Assign Grades');
 4180:     $request->print(<<ENDPICK);
 4181: </table>
 4182: <input type="hidden" name="nfields" value="$i" />
 4183: <input type="hidden" name="keyfields" value="$keyfields" />
 4184: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
 4185: </form>
 4186: ENDPICK
 4187: }
 4188: 
 4189: sub checkforfile_js {
 4190:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 4191:     &js_escape(\$alertmsg);
 4192:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
 4193:     function checkUpload(formname) {
 4194: 	if (formname.upfile.value == "") {
 4195: 	    alert("$alertmsg");
 4196: 	    return false;
 4197: 	}
 4198: 	formname.submit();
 4199:     }
 4200: CSVFORMJS
 4201:     return $result;
 4202: }
 4203: 
 4204: sub upcsvScores_form {
 4205:     my ($request,$symb) = @_;
 4206:     if (!$symb) {return '';}
 4207:     my $result=&checkforfile_js();
 4208:     $result.=&Apache::loncommon::start_data_table().
 4209:              &Apache::loncommon::start_data_table_header_row().
 4210:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
 4211:              &Apache::loncommon::end_data_table_header_row().
 4212:              &Apache::loncommon::start_data_table_row().'<td>';
 4213:     my $upload=&mt("Upload Scores");
 4214:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 4215:     my $ignore=&mt('Ignore First Line');
 4216:     $symb = &Apache::lonenc::check_encrypt($symb);
 4217:     $result.=<<ENDUPFORM;
 4218: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4219: <input type="hidden" name="symb" value="$symb" />
 4220: <input type="hidden" name="command" value="csvuploadmap" />
 4221: $upfile_select
 4222: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 4223: </form>
 4224: ENDUPFORM
 4225:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 4226:                            &mt("How do I create a CSV file from a spreadsheet")).
 4227:              '</td>'.
 4228:             &Apache::loncommon::end_data_table_row().
 4229:             &Apache::loncommon::end_data_table();
 4230:     return $result;
 4231: }
 4232: 
 4233: 
 4234: sub csvuploadmap {
 4235:     my ($request,$symb)= @_;
 4236:     if (!$symb) {return '';}
 4237: 
 4238:     my $datatoken;
 4239:     if (!$env{'form.datatoken'}) {
 4240: 	$datatoken=&Apache::loncommon::upfile_store($request);
 4241:     } else {
 4242: 	$datatoken=$env{'form.datatoken'};
 4243: 	&Apache::loncommon::load_tmp_file($request);
 4244:     }
 4245:     my @records=&Apache::loncommon::upfile_record_sep();
 4246:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 4247:     my ($i,$keyfields);
 4248:     if (@records) {
 4249:         my $fieldserror;
 4250: 	my @fields=&csvupload_fields($symb,\$fieldserror);
 4251:         if ($fieldserror) {
 4252:             $request->print(&navmap_errormsg());
 4253:             return;
 4254:         }
 4255: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 4256: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 4257: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 4258: 							  \@fields);
 4259: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 4260: 	    chop($keyfields);
 4261: 	} else {
 4262: 	    unshift(@fields,['none','']);
 4263: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 4264: 							    \@fields);
 4265:             foreach my $rec (@records) {
 4266:                 my %temp = &Apache::loncommon::record_sep($rec);
 4267:                 if (%temp) {
 4268:                     $keyfields=join(',',sort(keys(%temp)));
 4269:                     last;
 4270:                 }
 4271:             }
 4272: 	}
 4273:     }
 4274:     &csvuploadmap_footer($request,$i,$keyfields);
 4275: 
 4276:     return '';
 4277: }
 4278: 
 4279: sub csvuploadoptions {
 4280:     my ($request,$symb)= @_;
 4281:     my $overwrite=&mt('Overwrite any existing score');
 4282:     $request->print(<<ENDPICK);
 4283: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4284: <input type="hidden" name="command"    value="csvuploadassign" />
 4285: <p>
 4286: <label>
 4287:    <input type="checkbox" name="overwite_scores" checked="checked" />
 4288:    $overwrite
 4289: </label>
 4290: </p>
 4291: ENDPICK
 4292:     my %fields=&get_fields();
 4293:     if (!defined($fields{'domain'})) {
 4294: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 4295: 	$request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
 4296:     }
 4297:     foreach my $key (sort(keys(%env))) {
 4298: 	if ($key !~ /^form\.(.*)$/) { next; }
 4299: 	my $cleankey=$1;
 4300: 	if ($cleankey eq 'command') { next; }
 4301: 	$request->print('<input type="hidden" name="'.$cleankey.
 4302: 			'"  value="'.$env{$key}.'" />'."\n");
 4303:     }
 4304:     # FIXME do a check for any duplicated user ids...
 4305:     # FIXME do a check for any invalid user ids?...
 4306:     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
 4307: <hr /></form>'."\n");
 4308:     return '';
 4309: }
 4310: 
 4311: sub get_fields {
 4312:     my %fields;
 4313:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 4314:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 4315: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 4316: 	    if ($env{'form.f'.$i} ne 'none') {
 4317: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 4318: 	    }
 4319: 	} else {
 4320: 	    if ($env{'form.f'.$i} ne 'none') {
 4321: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 4322: 	    }
 4323: 	}
 4324:     }
 4325:     return %fields;
 4326: }
 4327: 
 4328: sub csvuploadassign {
 4329:     my ($request,$symb)= @_;
 4330:     if (!$symb) {return '';}
 4331:     my $error_msg = '';
 4332:     &Apache::loncommon::load_tmp_file($request);
 4333:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 4334:     my %fields=&get_fields();
 4335:     my $courseid=$env{'request.course.id'};
 4336:     my ($classlist) = &getclasslist('all',0);
 4337:     my @notallowed;
 4338:     my @skipped;
 4339:     my @warnings;
 4340:     my $countdone=0;
 4341:     foreach my $grade (@gradedata) {
 4342: 	my %entries=&Apache::loncommon::record_sep($grade);
 4343: 	my $domain;
 4344: 	if ($entries{$fields{'domain'}}) {
 4345: 	    $domain=$entries{$fields{'domain'}};
 4346: 	} else {
 4347: 	    $domain=$env{'form.default_domain'};
 4348: 	}
 4349: 	$domain=~s/\s//g;
 4350: 	my $username=$entries{$fields{'username'}};
 4351: 	$username=~s/\s//g;
 4352: 	if (!$username) {
 4353: 	    my $id=$entries{$fields{'ID'}};
 4354: 	    $id=~s/\s//g;
 4355: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 4356: 	    $username=$ids{$id};
 4357: 	}
 4358: 	if (!exists($$classlist{"$username:$domain"})) {
 4359: 	    my $id=$entries{$fields{'ID'}};
 4360: 	    $id=~s/\s//g;
 4361: 	    if ($id) {
 4362: 		push(@skipped,"$id:$domain");
 4363: 	    } else {
 4364: 		push(@skipped,"$username:$domain");
 4365: 	    }
 4366: 	    next;
 4367: 	}
 4368: 	my $usec=$classlist->{"$username:$domain"}[5];
 4369: 	if (!&canmodify($usec)) {
 4370: 	    push(@notallowed,"$username:$domain");
 4371: 	    next;
 4372: 	}
 4373: 	my %points;
 4374: 	my %grades;
 4375: 	foreach my $dest (keys(%fields)) {
 4376: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 4377: 		$dest eq 'domain') { next; }
 4378: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 4379: 	    if ($dest=~/stores_(.*)_points/) {
 4380: 		my $part=$1;
 4381: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 4382: 					      $symb,$domain,$username);
 4383:                 if ($wgt) {
 4384:                     $entries{$fields{$dest}}=~s/\s//g;
 4385:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 4386:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 4387:                                           : 'correct_by_override';
 4388:                     if ($pcr>1) {
 4389:                        push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
 4390:                     }
 4391:                     $grades{"resource.$part.awarded"}=$pcr;
 4392:                     $grades{"resource.$part.solved"}=$award;
 4393:                     $points{$part}=1;
 4394:                 } else {
 4395:                     $error_msg = "<br />" .
 4396:                         &mt("Some point values were assigned"
 4397:                             ." for problems with a weight "
 4398:                             ."of zero. These values were "
 4399:                             ."ignored.");
 4400:                 }
 4401: 	    } else {
 4402: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 4403: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 4404: 		my $store_key=$dest;
 4405: 		$store_key=~s/^stores/resource/;
 4406: 		$store_key=~s/_/\./g;
 4407: 		$grades{$store_key}=$entries{$fields{$dest}};
 4408: 	    }
 4409: 	}
 4410: 	if (! %grades) { 
 4411:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 4412:         } else {
 4413: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 4414: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 4415: 					   $env{'request.course.id'},
 4416: 					   $domain,$username);
 4417: 	   if ($result eq 'ok') {
 4418: # Successfully stored
 4419: 	      $request->print('.');
 4420: # Remove from grading queue
 4421:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
 4422:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
 4423:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
 4424:                                              $domain,$username);
 4425:               $countdone++;
 4426:            } else {
 4427: 	      $request->print("<p><span class=\"LC_error\">".
 4428:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 4429:                                   "$username:$domain",$result)."</span></p>");
 4430: 	   }
 4431: 	   $request->rflush();
 4432:         }
 4433:     }
 4434:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
 4435:     if (@warnings) {
 4436:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
 4437:         $request->print(join(', ',@warnings));
 4438:     }
 4439:     if (@skipped) {
 4440: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
 4441:         $request->print(join(', ',@skipped));
 4442:     }
 4443:     if (@notallowed) {
 4444: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
 4445: 	$request->print(join(', ',@notallowed));
 4446:     }
 4447:     $request->print("<br />\n");
 4448:     return $error_msg;
 4449: }
 4450: #------------- end of section for handling csv file upload ---------
 4451: #
 4452: #-------------------------------------------------------------------
 4453: #
 4454: #-------------- Next few routines handle grading by page/sequence
 4455: #
 4456: #--- Select a page/sequence and a student to grade
 4457: sub pickStudentPage {
 4458:     my ($request,$symb) = @_;
 4459: 
 4460:     my $alertmsg = &mt('Please select the student you wish to grade.');
 4461:     &js_escape(\$alertmsg);
 4462:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
 4463: 
 4464: function checkPickOne(formname) {
 4465:     if (radioSelection(formname.student) == null) {
 4466: 	alert("$alertmsg");
 4467: 	return;
 4468:     }
 4469:     ptr = pullDownSelection(formname.selectpage);
 4470:     formname.page.value = formname["page"+ptr].value;
 4471:     formname.title.value = formname["title"+ptr].value;
 4472:     formname.submit();
 4473: }
 4474: 
 4475: LISTJAVASCRIPT
 4476:     &commonJSfunctions($request);
 4477: 
 4478:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4479:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4480:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4481: 
 4482:     my $result='<h3><span class="LC_info">&nbsp;'.
 4483: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 4484: 
 4485:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 4486:     my $map_error;
 4487:     my ($titles,$symbx) = &getSymbMap($map_error);
 4488:     if ($map_error) {
 4489:         $request->print(&navmap_errormsg());
 4490:         return; 
 4491:     }
 4492:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 4493: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 4494: #    my $type=($curpage =~ /\.(page|sequence)/);
 4495: 
 4496:     # Collection of hidden fields
 4497:     my $ctr=0;
 4498:     foreach (@$titles) {
 4499:         my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4500:         $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 4501:         $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 4502:         $ctr++;
 4503:     }
 4504:     $result.='<input type="hidden" name="page" />'."\n".
 4505:         '<input type="hidden" name="title" />'."\n";
 4506: 
 4507:     $result.=&build_section_inputs();
 4508:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4509:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 4510: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 4511: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 4512: 
 4513:     # Show grading options
 4514:     $result.=&Apache::lonhtmlcommon::start_pick_box();
 4515:     my $select = '<select name="selectpage">'."\n";
 4516:     $ctr=0;
 4517:     foreach (@$titles) {
 4518: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4519: 	$select.='<option value="'.$ctr.'"'.
 4520: 	    ($$symbx{$_} =~ /$curpage$/ ? ' selected="selected"' : '').
 4521: 	    '>'.$showtitle.'</option>'."\n";
 4522: 	$ctr++;
 4523:     }
 4524:     $select.= '</select>';
 4525: 
 4526:     $result.=
 4527:         &Apache::lonhtmlcommon::row_title(&mt('Problems from'))
 4528:        .$select
 4529:        .&Apache::lonhtmlcommon::row_closure();
 4530: 
 4531:     $result.=
 4532:         &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
 4533:        .'<label><input type="radio" name="vProb" value="no"'
 4534:            .' checked="checked" /> '.&mt('no').' </label>'."\n"
 4535:        .'<label><input type="radio" name="vProb" value="yes" />'
 4536:            .&mt('yes').'</label>'."\n"
 4537:        .&Apache::lonhtmlcommon::row_closure();
 4538: 
 4539:     $result.=
 4540:         &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
 4541:        .'<label><input type="radio" name="lastSub" value="none" /> '
 4542:            .&mt('none').' </label>'."\n"
 4543:        .'<label><input type="radio" name="lastSub" value="datesub"'
 4544:            .' checked="checked" /> '.&mt('all submissions').'</label>'."\n"
 4545:        .'<label><input type="radio" name="lastSub" value="all" /> '
 4546:            .&mt('all submissions with details').' </label>'
 4547:        .&Apache::lonhtmlcommon::row_closure();
 4548:     
 4549:     $result.=
 4550:         &Apache::lonhtmlcommon::row_title(&mt('Use CODE'))
 4551:        .'<input type="text" name="CODE" value="" />'
 4552:        .&Apache::lonhtmlcommon::row_closure(1)
 4553:        .&Apache::lonhtmlcommon::end_pick_box();
 4554: 
 4555:     # Show list of students to select for grading
 4556:     $result.='<br /><input type="button" '.
 4557:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 4558: 
 4559:     $request->print($result);
 4560: 
 4561:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 4562: 	&Apache::loncommon::start_data_table().
 4563: 	&Apache::loncommon::start_data_table_header_row().
 4564: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4565: 	'<th>'.&nameUserString('header').'</th>'.
 4566: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4567: 	'<th>'.&nameUserString('header').'</th>'.
 4568: 	&Apache::loncommon::end_data_table_header_row();
 4569:  
 4570:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 4571:     my $ptr = 1;
 4572:     foreach my $student (sort 
 4573: 			 {
 4574: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4575: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4576: 			     }
 4577: 			     return $a cmp $b;
 4578: 			 } (keys(%$fullname))) {
 4579: 	my ($uname,$udom) = split(/:/,$student);
 4580: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 4581:                                   : '</td>');
 4582: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 4583: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 4584: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 4585: 	$studentTable.=
 4586: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 4587:                          : '');
 4588: 	$ptr++;
 4589:     }
 4590:     if ($ptr%2 == 0) {
 4591: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 4592: 	    &Apache::loncommon::end_data_table_row();
 4593:     }
 4594:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 4595:     $studentTable.='<input type="button" '.
 4596:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 4597: 
 4598:     $request->print($studentTable);
 4599: 
 4600:     return '';
 4601: }
 4602: 
 4603: sub getSymbMap {
 4604:     my ($map_error) = @_;
 4605:     my $navmap = Apache::lonnavmaps::navmap->new();
 4606:     unless (ref($navmap)) {
 4607:         if (ref($map_error)) {
 4608:             $$map_error = 'navmap';
 4609:         }
 4610:         return;
 4611:     }
 4612:     my %symbx = ();
 4613:     my @titles = ();
 4614:     my $minder = 0;
 4615: 
 4616:     # Gather every sequence that has problems.
 4617:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 4618: 					       1,0,1);
 4619:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 4620: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 4621: 	    my $title = $minder.'.'.
 4622: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 4623: 	    push(@titles, $title); # minder in case two titles are identical
 4624: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 4625: 	    $minder++;
 4626: 	}
 4627:     }
 4628:     return \@titles,\%symbx;
 4629: }
 4630: 
 4631: #
 4632: #--- Displays a page/sequence w/wo problems, w/wo submissions
 4633: sub displayPage {
 4634:     my ($request,$symb) = @_;
 4635:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4636:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4637:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4638:     my $pageTitle = $env{'form.page'};
 4639:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4640:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4641:     my $usec=$classlist->{$env{'form.student'}}[5];
 4642: 
 4643:     #need to make sure we have the correct data for later EXT calls, 
 4644:     #thus invalidate the cache
 4645:     &Apache::lonnet::devalidatecourseresdata(
 4646:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 4647:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 4648:     &Apache::lonnet::clear_EXT_cache_status();
 4649: 
 4650:     if (!&canview($usec)) {
 4651:         $request->print(
 4652:             '<span class="LC_warning">'.
 4653:             &mt('Unable to view requested student. ([_1])',
 4654:                     $env{'form.student'}).
 4655:             '</span>');
 4656:         return;
 4657:     }
 4658:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4659:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 4660: 	'</h3>'."\n";
 4661:     $env{'form.CODE'} = uc($env{'form.CODE'});
 4662:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 4663: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 4664:     } else {
 4665: 	delete($env{'form.CODE'});
 4666:     }
 4667:     &sub_page_js($request);
 4668:     $request->print($result);
 4669: 
 4670:     my $navmap = Apache::lonnavmaps::navmap->new();
 4671:     unless (ref($navmap)) {
 4672:         $request->print(&navmap_errormsg());
 4673:         return;
 4674:     }
 4675:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 4676:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4677:     if (!$map) {
 4678: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 4679: 	return; 
 4680:     }
 4681:     my $iterator = $navmap->getIterator($map->map_start(),
 4682: 					$map->map_finish());
 4683: 
 4684:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 4685: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 4686: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 4687: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 4688: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 4689: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 4690: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4691: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
 4692: 
 4693:     if (defined($env{'form.CODE'})) {
 4694: 	$studentTable.=
 4695: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 4696:     }
 4697:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 4698: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 4699: 
 4700:     $studentTable.='&nbsp;<span class="LC_info">'.
 4701:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
 4702:         '</span>'."\n".
 4703: 	&Apache::loncommon::start_data_table().
 4704: 	&Apache::loncommon::start_data_table_header_row().
 4705: 	'<th>'.&mt('Prob.').'</th>'.
 4706: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 4707: 	&Apache::loncommon::end_data_table_header_row();
 4708: 
 4709:     &Apache::lonxml::clear_problem_counter();
 4710:     my ($depth,$question,$prob) = (1,1,1);
 4711:     $iterator->next(); # skip the first BEGIN_MAP
 4712:     my $curRes = $iterator->next(); # for "current resource"
 4713:     while ($depth > 0) {
 4714:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4715:         if($curRes == $iterator->END_MAP) { $depth--; }
 4716: 
 4717:         if (ref($curRes) && $curRes->is_problem()) {
 4718: 	    my $parts = $curRes->parts();
 4719:             my $title = $curRes->compTitle();
 4720: 	    my $symbx = $curRes->symb();
 4721: 	    $studentTable.=
 4722: 		&Apache::loncommon::start_data_table_row().
 4723: 		'<td align="center" valign="top" >'.$prob.
 4724: 		(scalar(@{$parts}) == 1 ? '' 
 4725: 		                        : '<br />('.&mt('[_1]parts',
 4726: 							scalar(@{$parts}).'&nbsp;').')'
 4727: 		 ).
 4728: 		 '</td>';
 4729: 	    $studentTable.='<td valign="top">';
 4730: 	    my %form = ('CODE' => $env{'form.CODE'},);
 4731: 	    if ($env{'form.vProb'} eq 'yes' ) {
 4732: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 4733: 					     undef,'both',\%form);
 4734: 	    } else {
 4735: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 4736: 		$companswer =~ s|<form(.*?)>||g;
 4737: 		$companswer =~ s|</form>||g;
 4738: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 4739: #		    $companswer =~ s/$1/ /ms;
 4740: #		    $request->print('match='.$1."<br />\n");
 4741: #		}
 4742: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 4743: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 4744: 	    }
 4745: 
 4746: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 4747: 
 4748: 	    if ($env{'form.lastSub'} eq 'datesub') {
 4749: 		if ($record{'version'} eq '') {
 4750: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
 4751: 		} else {
 4752: 		    my %responseType = ();
 4753: 		    foreach my $partid (@{$parts}) {
 4754: 			my @responseIds =$curRes->responseIds($partid);
 4755: 			my @responseType =$curRes->responseType($partid);
 4756: 			my %responseIds;
 4757: 			for (my $i=0;$i<=$#responseIds;$i++) {
 4758: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 4759: 			}
 4760: 			$responseType{$partid} = \%responseIds;
 4761: 		    }
 4762: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 4763: 
 4764: 		}
 4765: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 4766: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 4767:                 my $identifier = (&canmodify($usec)? $prob : ''); 
 4768: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 4769: 									$env{'request.course.id'},
 4770: 									'','.submission',undef,
 4771:                                                                         $usec,$identifier);
 4772:  
 4773: 	    }
 4774: 	    if (&canmodify($usec)) {
 4775:             $studentTable.=&gradeBox_start();
 4776: 		foreach my $partid (@{$parts}) {
 4777: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 4778: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 4779: 		    $question++;
 4780: 		}
 4781:             $studentTable.=&gradeBox_end();
 4782: 		$prob++;
 4783: 	    }
 4784: 	    $studentTable.='</td></tr>';
 4785: 
 4786: 	}
 4787:         $curRes = $iterator->next();
 4788:     }
 4789: 
 4790:     $studentTable.=
 4791:         '</table>'."\n".
 4792:         '<input type="button" value="'.&mt('Save').'" '.
 4793:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 4794:         '</form>'."\n";
 4795:     $request->print($studentTable);
 4796: 
 4797:     return '';
 4798: }
 4799: 
 4800: sub displaySubByDates {
 4801:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 4802:     my $isCODE=0;
 4803:     my $isTask = ($symb =~/\.task$/);
 4804:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 4805:     my $studentTable=&Apache::loncommon::start_data_table().
 4806: 	&Apache::loncommon::start_data_table_header_row().
 4807: 	'<th>'.&mt('Date/Time').'</th>'.
 4808: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 4809:         ($isTask?'<th>'.&mt('Version').'</th>':'').
 4810: 	'<th>'.&mt('Submission').'</th>'.
 4811: 	'<th>'.&mt('Status').'</th>'.
 4812: 	&Apache::loncommon::end_data_table_header_row();
 4813:     my ($version);
 4814:     my %mark;
 4815:     my %orders;
 4816:     $mark{'correct_by_student'} = $checkIcon;
 4817:     if (!exists($$record{'1:timestamp'})) {
 4818: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 4819:     }
 4820: 
 4821:     my $interaction;
 4822:     my $no_increment = 1;
 4823:     my (%lastrndseed,%lasttype);
 4824:     for ($version=1;$version<=$$record{'version'};$version++) {
 4825: 	my $timestamp = 
 4826: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 4827: 	if (exists($$record{$version.':resource.0.version'})) {
 4828: 	    $interaction = $$record{$version.':resource.0.version'};
 4829: 	}
 4830:         if ($isTask && $env{'form.previousversion'}) {
 4831:             next unless ($interaction == $env{'form.previousversion'});
 4832:         }
 4833: 	my $where = ($isTask ? "$version:resource.$interaction"
 4834: 		             : "$version:resource");
 4835: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 4836: 	    '<td>'.$timestamp.'</td>';
 4837: 	if ($isCODE) {
 4838: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 4839: 	}
 4840:         if ($isTask) {
 4841:             $studentTable.='<td>'.$interaction.'</td>';
 4842:         }
 4843: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 4844: 	my @displaySub = ();
 4845: 	foreach my $partid (@{$parts}) {
 4846:             my ($hidden,$type);
 4847:             $type = $$record{$version.':resource.'.$partid.'.type'};
 4848:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
 4849:                 $hidden = 1;
 4850:             }
 4851: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
 4852: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 4853: 	    
 4854: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 4855: 	    my $display_part=&get_display_part($partid,$symb);
 4856: 	    foreach my $matchKey (@matchKey) {
 4857: 		if (exists($$record{$version.':'.$matchKey}) &&
 4858: 		    $$record{$version.':'.$matchKey} ne '') {
 4859:                     
 4860: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 4861: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 4862:                     $displaySub[0].='<span class="LC_nobreak">';
 4863:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
 4864:                                    .' <span class="LC_internal_info">'
 4865:                                    .'('.&mt('Response ID: [_1]',$responseId).')'
 4866:                                    .'</span>'
 4867:                                    .' <b>';
 4868:                     if ($hidden) {
 4869:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
 4870:                     } else {
 4871:                         my ($trial,$rndseed,$newvariation);
 4872:                         if ($type eq 'randomizetry') {
 4873:                             $trial = $$record{"$where.$partid.tries"};
 4874:                             $rndseed = $$record{"$where.$partid.rndseed"};
 4875:                         }
 4876: 		        if ($$record{"$where.$partid.tries"} eq '') {
 4877: 			    $displaySub[0].=&mt('Trial not counted');
 4878: 		        } else {
 4879: 			    $displaySub[0].=&mt('Trial: [_1]',
 4880: 					    $$record{"$where.$partid.tries"});
 4881:                             if (($rndseed ne '') && ($lastrndseed{$partid} ne '')) {
 4882:                                 if (($rndseed ne $lastrndseed{$partid}) &&
 4883:                                     (($type eq 'randomizetry') || ($lasttype{$partid} eq 'randomizetry'))) {
 4884:                                     $newvariation = '&nbsp;('.&mt('New variation this try').')';
 4885:                                 }
 4886:                             }
 4887:                             $lastrndseed{$partid} = $rndseed;
 4888:                             $lasttype{$partid} = $type;
 4889: 		        }
 4890: 		        my $responseType=($isTask ? 'Task'
 4891:                                               : $responseType->{$partid}->{$responseId});
 4892: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
 4893: 		        if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
 4894: 			    $orders{$partid}->{$responseId}=
 4895: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
 4896:                                            $no_increment,$type,$trial,$rndseed);
 4897: 		        }
 4898: 		        $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
 4899: 		        $displaySub[0].='&nbsp; '.
 4900: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
 4901:                     }
 4902: 		}
 4903: 	    }
 4904: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 4905: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 4906: 				    $$record{"$where.$partid.checkedin"},
 4907: 				    $$record{"$where.$partid.checkedin.slot"}).
 4908: 					'<br />';
 4909: 	    }
 4910: 	    if (exists $$record{"$where.$partid.award"}) {
 4911: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 4912: 		    lc($$record{"$where.$partid.award"}).' '.
 4913: 		    $mark{$$record{"$where.$partid.solved"}}.
 4914: 		    '<br />';
 4915: 	    }
 4916: 	    if (exists $$record{"$where.$partid.regrader"}) {
 4917: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 4918: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4919: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 4920: 		$displaySub[2].=
 4921: 		    $$record{"$version:resource.$partid.regrader"}.
 4922: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4923: 	    }
 4924: 	}
 4925: 	# needed because old essay regrader has not parts info
 4926: 	if (exists $$record{"$version:resource.regrader"}) {
 4927: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 4928: 	}
 4929: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 4930: 	if ($displaySub[2]) {
 4931: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 4932: 	}
 4933: 	$studentTable.='&nbsp;</td>'.
 4934: 	    &Apache::loncommon::end_data_table_row();
 4935:     }
 4936:     $studentTable.=&Apache::loncommon::end_data_table();
 4937:     return $studentTable;
 4938: }
 4939: 
 4940: sub updateGradeByPage {
 4941:     my ($request,$symb) = @_;
 4942: 
 4943:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4944:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4945:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4946:     my $pageTitle = $env{'form.page'};
 4947:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4948:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4949:     my $usec=$classlist->{$env{'form.student'}}[5];
 4950:     if (!&canmodify($usec)) {
 4951: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 4952: 	return;
 4953:     }
 4954:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4955:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 4956: 	'</h3>'."\n";
 4957: 
 4958:     $request->print($result);
 4959: 
 4960: 
 4961:     my $navmap = Apache::lonnavmaps::navmap->new();
 4962:     unless (ref($navmap)) {
 4963:         $request->print(&navmap_errormsg());
 4964:         return;
 4965:     }
 4966:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 4967:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4968:     if (!$map) {
 4969: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 4970: 	return; 
 4971:     }
 4972:     my $iterator = $navmap->getIterator($map->map_start(),
 4973: 					$map->map_finish());
 4974: 
 4975:     my $studentTable=
 4976: 	&Apache::loncommon::start_data_table().
 4977: 	&Apache::loncommon::start_data_table_header_row().
 4978: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 4979: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 4980: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 4981: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 4982: 	&Apache::loncommon::end_data_table_header_row();
 4983: 
 4984:     $iterator->next(); # skip the first BEGIN_MAP
 4985:     my $curRes = $iterator->next(); # for "current resource"
 4986:     my ($depth,$question,$prob,$changeflag,$hideflag)= (1,1,1,0,0);
 4987:     while ($depth > 0) {
 4988:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4989:         if($curRes == $iterator->END_MAP) { $depth--; }
 4990: 
 4991:         if (ref($curRes) && $curRes->is_problem()) {
 4992: 	    my $parts = $curRes->parts();
 4993:             my $title = $curRes->compTitle();
 4994: 	    my $symbx = $curRes->symb();
 4995: 	    $studentTable.=
 4996: 		&Apache::loncommon::start_data_table_row().
 4997: 		'<td align="center" valign="top" >'.$prob.
 4998: 		(scalar(@{$parts}) == 1 ? '' 
 4999:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
 5000: 		.')').'</td>';
 5001: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 5002: 
 5003: 	    my %newrecord=();
 5004: 	    my @displayPts=();
 5005:             my %aggregate = ();
 5006:             my $aggregateflag = 0;
 5007:             if ($env{'form.HIDE'.$prob}) {
 5008:                 my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 5009:                 my ($version,$parts) = split(/:/,$env{'form.HIDE'.$prob},2);
 5010:                 my $numchgs = &makehidden($version,$parts,\%record,$symbx,$udom,$uname,1);
 5011:                 $hideflag += $numchgs;
 5012:             }
 5013: 	    foreach my $partid (@{$parts}) {
 5014: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 5015: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 5016: 
 5017: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 5018: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 5019: 		my $partial = $newpts/$wgt;
 5020: 		my $score;
 5021: 		if ($partial > 0) {
 5022: 		    $score = 'correct_by_override';
 5023: 		} elsif ($newpts ne '') { #empty is taken as 0
 5024: 		    $score = 'incorrect_by_override';
 5025: 		}
 5026: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 5027: 		if ($dropMenu eq 'excused') {
 5028: 		    $partial = '';
 5029: 		    $score = 'excused';
 5030: 		} elsif ($dropMenu eq 'reset status'
 5031: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 5032: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 5033: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 5034: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 5035: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 5036: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 5037: 		    $changeflag++;
 5038: 		    $newpts = '';
 5039:                     
 5040:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 5041:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 5042:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 5043:                     if ($aggtries > 0) {
 5044:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 5045:                         $aggregateflag = 1;
 5046:                     }
 5047: 		}
 5048: 		my $display_part=&get_display_part($partid,$curRes->symb());
 5049: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 5050: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5051: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 5052: 		    '&nbsp;<br />';
 5053: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5054: 		     (($score eq 'excused') ? 'excused' : $newpts).
 5055: 		    '&nbsp;<br />';
 5056: 		$question++;
 5057: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 5058: 
 5059: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 5060: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 5061: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 5062: 		    if (scalar(keys(%newrecord)) > 0);
 5063: 
 5064: 		$changeflag++;
 5065: 	    }
 5066: 	    if (scalar(keys(%newrecord)) > 0) {
 5067: 		my %record = 
 5068: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 5069: 					     $udom,$uname);
 5070: 
 5071: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 5072: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 5073: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 5074: 		    $newrecord{'resource.CODE'} = '';
 5075: 		}
 5076: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 5077: 					$udom,$uname);
 5078: 		%record = &Apache::lonnet::restore($symbx,
 5079: 						   $env{'request.course.id'},
 5080: 						   $udom,$uname);
 5081: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 5082: 					     $cdom,$cnum,$udom,$uname);
 5083: 	    }
 5084: 	    
 5085:             if ($aggregateflag) {
 5086:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 5087:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 5088:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 5089:             }
 5090: 
 5091: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 5092: 		'<td valign="top">'.$displayPts[1].'</td>'.
 5093: 		&Apache::loncommon::end_data_table_row();
 5094: 
 5095: 	    $prob++;
 5096: 	}
 5097:         $curRes = $iterator->next();
 5098:     }
 5099: 
 5100:     $studentTable.=&Apache::loncommon::end_data_table();
 5101:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 5102: 		  &mt('The scores were changed for [quant,_1,problem].',
 5103: 		  $changeflag).'<br />');
 5104:     my $hidemsg=($hideflag == 0 ? '' :
 5105:                  &mt('Submissions were marked "hidden" for [quant,_1,transaction].',
 5106:                      $hideflag).'<br />');
 5107:     $request->print($hidemsg.$grademsg.$studentTable);
 5108: 
 5109:     return '';
 5110: }
 5111: 
 5112: #-------- end of section for handling grading by page/sequence ---------
 5113: #
 5114: #-------------------------------------------------------------------
 5115: 
 5116: #-------------------- Bubblesheet (Scantron) Grading -------------------
 5117: #
 5118: #------ start of section for handling grading by page/sequence ---------
 5119: 
 5120: =pod
 5121: 
 5122: =head1 Bubble sheet grading routines
 5123: 
 5124:   For this documentation:
 5125: 
 5126:    'scanline' refers to the full line of characters
 5127:    from the file that we are parsing that represents one entire sheet
 5128: 
 5129:    'bubble line' refers to the data
 5130:    representing the line of bubbles that are on the physical bubblesheet
 5131: 
 5132: 
 5133: The overall process is that a scanned in bubblesheet data is uploaded
 5134: into a course. When a user wants to grade, they select a
 5135: sequence/folder of resources, a file of bubblesheet info, and pick
 5136: one of the predefined configurations for what each scanline looks
 5137: like.
 5138: 
 5139: Next each scanline is checked for any errors of either 'missing
 5140: bubbles' (it's an error because it may have been mis-scanned
 5141: because too light bubbling), 'double bubble' (each bubble line should
 5142: have no more than one letter picked), invalid or duplicated CODE,
 5143: invalid student/employee ID
 5144: 
 5145: If the CODE option is used that determines the randomization of the
 5146: homework problems, either way the student/employee ID is looked up into a
 5147: username:domain.
 5148: 
 5149: During the validation phase the instructor can choose to skip scanlines. 
 5150: 
 5151: After the validation phase, there are now 3 bubblesheet files
 5152: 
 5153:   scantron_original_filename (unmodified original file)
 5154:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 5155:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 5156: 
 5157: Also there is a separate hash nohist_scantrondata that contains extra
 5158: correction information that isn't representable in the bubblesheet
 5159: file (see &scantron_getfile() for more information)
 5160: 
 5161: After all scanlines are either valid, marked as valid or skipped, then
 5162: foreach line foreach problem in the picked sequence, an ssi request is
 5163: made that simulates a user submitting their selected letter(s) against
 5164: the homework problem.
 5165: 
 5166: =over 4
 5167: 
 5168: 
 5169: 
 5170: =item defaultFormData
 5171: 
 5172:   Returns html hidden inputs used to hold context/default values.
 5173: 
 5174:  Arguments:
 5175:   $symb - $symb of the current resource 
 5176: 
 5177: =cut
 5178: 
 5179: sub defaultFormData {
 5180:     my ($symb)=@_;
 5181:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />';
 5182: }
 5183: 
 5184: 
 5185: =pod 
 5186: 
 5187: =item getSequenceDropDown
 5188: 
 5189:    Return html dropdown of possible sequences to grade
 5190:  
 5191:  Arguments:
 5192:    $symb - $symb of the current resource
 5193:    $map_error - ref to scalar which will container error if
 5194:                 $navmap object is unavailable in &getSymbMap().
 5195: 
 5196: =cut
 5197: 
 5198: sub getSequenceDropDown {
 5199:     my ($symb,$map_error)=@_;
 5200:     my $result='<select name="selectpage">'."\n";
 5201:     my ($titles,$symbx) = &getSymbMap($map_error);
 5202:     if (ref($map_error)) {
 5203:         return if ($$map_error);
 5204:     }
 5205:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 5206:     my $ctr=0;
 5207:     foreach (@$titles) {
 5208: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 5209: 	$result.='<option value="'.$$symbx{$_}.'" '.
 5210: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 5211: 	    '>'.$showtitle.'</option>'."\n";
 5212: 	$ctr++;
 5213:     }
 5214:     $result.= '</select>';
 5215:     return $result;
 5216: }
 5217: 
 5218: my %bubble_lines_per_response;     # no. bubble lines for each response.
 5219:                                    # key is zero-based index - 0, 1, 2 ...
 5220: 
 5221: my %first_bubble_line;             # First bubble line no. for each bubble.
 5222: 
 5223: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 5224:                                    # matchresponse or rankresponse, where 
 5225:                                    # an individual response can have multiple 
 5226:                                    # lines
 5227: 
 5228: my %responsetype_per_response;     # responsetype for each response
 5229: 
 5230: my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
 5231:                                    # numbered response. Needed when randomorder
 5232:                                    # or randompick are in use. Key is ID, value 
 5233:                                    # is response number.
 5234: 
 5235: # Save and restore the bubble lines array to the form env.
 5236: 
 5237: 
 5238: sub save_bubble_lines {
 5239:     foreach my $line (keys(%bubble_lines_per_response)) {
 5240: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 5241: 	$env{"form.scantron.first_bubble_line.$line"} =
 5242: 	    $first_bubble_line{$line};
 5243:         $env{"form.scantron.sub_bubblelines.$line"} = 
 5244:             $subdivided_bubble_lines{$line};
 5245:         $env{"form.scantron.responsetype.$line"} =
 5246:             $responsetype_per_response{$line};
 5247:     }
 5248:     foreach my $resid (keys(%masterseq_id_responsenum)) {
 5249:         my $line = $masterseq_id_responsenum{$resid};
 5250:         $env{"form.scantron.residpart.$line"} = $resid;
 5251:     }
 5252: }
 5253: 
 5254: 
 5255: sub restore_bubble_lines {
 5256:     my $line = 0;
 5257:     %bubble_lines_per_response = ();
 5258:     %masterseq_id_responsenum = ();
 5259:     while ($env{"form.scantron.bubblelines.$line"}) {
 5260: 	my $value = $env{"form.scantron.bubblelines.$line"};
 5261: 	$bubble_lines_per_response{$line} = $value;
 5262: 	$first_bubble_line{$line}  =
 5263: 	    $env{"form.scantron.first_bubble_line.$line"};
 5264:         $subdivided_bubble_lines{$line} =
 5265:             $env{"form.scantron.sub_bubblelines.$line"};
 5266:         $responsetype_per_response{$line} =
 5267:             $env{"form.scantron.responsetype.$line"};
 5268:         my $id = $env{"form.scantron.residpart.$line"};
 5269:         $masterseq_id_responsenum{$id} = $line;
 5270: 	$line++;
 5271:     }
 5272: }
 5273: 
 5274: =pod 
 5275: 
 5276: =item scantron_filenames
 5277: 
 5278:    Returns a list of the scantron files in the current course 
 5279: 
 5280: =cut
 5281: 
 5282: sub scantron_filenames {
 5283:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5284:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5285:     my $getpropath = 1;
 5286:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
 5287:                                                         $cname,$getpropath);
 5288:     my @possiblenames;
 5289:     if (ref($dirlist) eq 'ARRAY') {
 5290:         foreach my $filename (sort(@{$dirlist})) {
 5291: 	    ($filename)=split(/&/,$filename);
 5292: 	    if ($filename!~/^scantron_orig_/) { next ; }
 5293: 	    $filename=~s/^scantron_orig_//;
 5294: 	    push(@possiblenames,$filename);
 5295:         }
 5296:     }
 5297:     return @possiblenames;
 5298: }
 5299: 
 5300: =pod 
 5301: 
 5302: =item scantron_uploads
 5303: 
 5304:    Returns  html drop-down list of scantron files in current course.
 5305: 
 5306:  Arguments:
 5307:    $file2grade - filename to set as selected in the dropdown
 5308: 
 5309: =cut
 5310: 
 5311: sub scantron_uploads {
 5312:     my ($file2grade) = @_;
 5313:     my $result=	'<select name="scantron_selectfile">';
 5314:     $result.="<option></option>";
 5315:     foreach my $filename (sort(&scantron_filenames())) {
 5316: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 5317:     }
 5318:     $result.="</select>";
 5319:     return $result;
 5320: }
 5321: 
 5322: =pod 
 5323: 
 5324: =item scantron_scantab
 5325: 
 5326:   Returns html drop down of the scantron formats in the scantronformat.tab
 5327:   file.
 5328: 
 5329: =cut
 5330: 
 5331: sub scantron_scantab {
 5332:     my $result='<select name="scantron_format">'."\n";
 5333:     $result.='<option></option>'."\n";
 5334:     my @lines = &get_scantronformat_file();
 5335:     if (@lines > 0) {
 5336:         foreach my $line (@lines) {
 5337:             next if (($line =~ /^\#/) || ($line eq ''));
 5338: 	    my ($name,$descrip)=split(/:/,$line);
 5339: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 5340:         }
 5341:     }
 5342:     $result.='</select>'."\n";
 5343:     return $result;
 5344: }
 5345: 
 5346: =pod
 5347: 
 5348: =item get_scantronformat_file
 5349: 
 5350:   Returns an array containing lines from the scantron format file for
 5351:   the domain of the course.
 5352: 
 5353:   If a url for a custom.tab file is listed in domain's configuration.db, 
 5354:   lines are from this file.
 5355: 
 5356:   Otherwise, if a default.tab has been published in RES space by the 
 5357:   domainconfig user, lines are from this file.
 5358: 
 5359:   Otherwise, fall back to getting lines from the legacy file on the
 5360:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
 5361: 
 5362: =cut
 5363: 
 5364: sub get_scantronformat_file {
 5365:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5366:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
 5367:     my $gottab = 0;
 5368:     my @lines;
 5369:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 5370:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 5371:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 5372:             if ($formatfile ne '-1') {
 5373:                 @lines = split("\n",$formatfile,-1);
 5374:                 $gottab = 1;
 5375:             }
 5376:         }
 5377:     }
 5378:     if (!$gottab) {
 5379:         my $confname = $cdom.'-domainconfig';
 5380:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 5381:         my $formatfile =  &Apache::lonnet::getfile($default);
 5382:         if ($formatfile ne '-1') {
 5383:             @lines = split("\n",$formatfile,-1);
 5384:             $gottab = 1;
 5385:         }
 5386:     }
 5387:     if (!$gottab) {
 5388:         my @domains = &Apache::lonnet::current_machine_domains();
 5389:         if (grep(/^\Q$cdom\E$/,@domains)) {
 5390:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 5391:             @lines = <$fh>;
 5392:             close($fh);
 5393:         } else {
 5394:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
 5395:             @lines = <$fh>;
 5396:             close($fh);
 5397:         }
 5398:     }
 5399:     return @lines;
 5400: }
 5401: 
 5402: =pod 
 5403: 
 5404: =item scantron_CODElist
 5405: 
 5406:   Returns html drop down of the saved CODE lists from current course,
 5407:   generated from earlier printings.
 5408: 
 5409: =cut
 5410: 
 5411: sub scantron_CODElist {
 5412:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5413:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5414:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 5415:     my $namechoice='<option></option>';
 5416:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 5417: 	if ($name =~ /^error: 2 /) { next; }
 5418: 	if ($name =~ /^type\0/) { next; }
 5419: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 5420:     }
 5421:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 5422:     return $namechoice;
 5423: }
 5424: 
 5425: =pod 
 5426: 
 5427: =item scantron_CODEunique
 5428: 
 5429:   Returns the html for "Each CODE to be used once" radio.
 5430: 
 5431: =cut
 5432: 
 5433: sub scantron_CODEunique {
 5434:     my $result='<span class="LC_nobreak">
 5435:                  <label><input type="radio" name="scantron_CODEunique"
 5436:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 5437:                 </span>
 5438:                 <span class="LC_nobreak">
 5439:                  <label><input type="radio" name="scantron_CODEunique"
 5440:                         value="no" />'.&mt('No').' </label>
 5441:                 </span>';
 5442:     return $result;
 5443: }
 5444: 
 5445: =pod 
 5446: 
 5447: =item scantron_selectphase
 5448: 
 5449:   Generates the initial screen to start the bubblesheet process.
 5450:   Allows for - starting a grading run.
 5451:              - downloading existing scan data (original, corrected
 5452:                                                 or skipped info)
 5453: 
 5454:              - uploading new scan data
 5455: 
 5456:  Arguments:
 5457:   $r          - The Apache request object
 5458:   $file2grade - name of the file that contain the scanned data to score
 5459: 
 5460: =cut
 5461: 
 5462: sub scantron_selectphase {
 5463:     my ($r,$file2grade,$symb) = @_;
 5464:     if (!$symb) {return '';}
 5465:     my $map_error;
 5466:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
 5467:     if ($map_error) {
 5468:         $r->print('<br />'.&navmap_errormsg().'<br />');
 5469:         return;
 5470:     }
 5471:     my $default_form_data=&defaultFormData($symb);
 5472:     my $file_selector=&scantron_uploads($file2grade);
 5473:     my $format_selector=&scantron_scantab();
 5474:     my $CODE_selector=&scantron_CODElist();
 5475:     my $CODE_unique=&scantron_CODEunique();
 5476:     my $result;
 5477: 
 5478:     $ssi_error = 0;
 5479: 
 5480:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 5481:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 5482: 
 5483: 	# Chunk of form to prompt for a scantron file upload.
 5484: 
 5485:         $r->print('
 5486:     <br />
 5487:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5488:        '.&Apache::loncommon::start_data_table_header_row().'
 5489:             <th>
 5490:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
 5491:             </th>
 5492:        '.&Apache::loncommon::end_data_table_header_row().'
 5493:        '.&Apache::loncommon::start_data_table_row().'
 5494:             <td>
 5495: ');
 5496:     my $default_form_data=&defaultFormData($symb);
 5497:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5498:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 5499:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 5500:     &js_escape(\$alertmsg);
 5501:     $r->print(&Apache::lonhtmlcommon::scripttag('
 5502:     function checkUpload(formname) {
 5503: 	if (formname.upfile.value == "") {
 5504: 	    alert("'.$alertmsg.'");
 5505: 	    return false;
 5506: 	}
 5507: 	formname.submit();
 5508:     }'));
 5509:     $r->print('
 5510:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 5511:                 '.$default_form_data.'
 5512:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 5513:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 5514:                 <input name="command" value="scantronupload_save" type="hidden" />
 5515:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
 5516:                 <br />
 5517:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 5518:               </form>
 5519: ');
 5520: 
 5521:         $r->print('
 5522:             </td>
 5523:        '.&Apache::loncommon::end_data_table_row().'
 5524:        '.&Apache::loncommon::end_data_table().'
 5525: ');
 5526:     }
 5527: 
 5528:     # Chunk of form to prompt for a file to grade and how:
 5529: 
 5530:     $result.= '
 5531:     <br />
 5532:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 5533:     <input type="hidden" name="command" value="scantron_warning" />
 5534:     '.$default_form_data.'
 5535:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5536:        '.&Apache::loncommon::start_data_table_header_row().'
 5537:             <th colspan="2">
 5538:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 5539:             </th>
 5540:        '.&Apache::loncommon::end_data_table_header_row().'
 5541:        '.&Apache::loncommon::start_data_table_row().'
 5542:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 5543:        '.&Apache::loncommon::end_data_table_row().'
 5544:        '.&Apache::loncommon::start_data_table_row().'
 5545:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
 5546:        '.&Apache::loncommon::end_data_table_row().'
 5547:        '.&Apache::loncommon::start_data_table_row().'
 5548:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
 5549:        '.&Apache::loncommon::end_data_table_row().'
 5550:        '.&Apache::loncommon::start_data_table_row().'
 5551:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 5552:        '.&Apache::loncommon::end_data_table_row().'
 5553:        '.&Apache::loncommon::start_data_table_row().'
 5554:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 5555:        '.&Apache::loncommon::end_data_table_row().'
 5556:        '.&Apache::loncommon::start_data_table_row().'
 5557: 	    <td> '.&mt('Options:').' </td>
 5558:             <td>
 5559: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 5560:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 5561:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 5562: 	    </td>
 5563:        '.&Apache::loncommon::end_data_table_row().'
 5564:        '.&Apache::loncommon::start_data_table_row().'
 5565:             <td colspan="2">
 5566:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
 5567:             </td>
 5568:        '.&Apache::loncommon::end_data_table_row().'
 5569:     '.&Apache::loncommon::end_data_table().'
 5570:     </form>
 5571: ';
 5572:    
 5573:     $r->print($result);
 5574: 
 5575: 
 5576: 
 5577:     # Chunk of the form that prompts to view a scoring office file,
 5578:     # corrected file, skipped records in a file.
 5579: 
 5580:     $r->print('
 5581:    <br />
 5582:    <form action="/adm/grades" name="scantron_download">
 5583:      '.$default_form_data.'
 5584:      <input type="hidden" name="command" value="scantron_download" />
 5585:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5586:        '.&Apache::loncommon::start_data_table_header_row().'
 5587:               <th>
 5588:                 &nbsp;'.&mt('Download a scoring office file').'
 5589:               </th>
 5590:        '.&Apache::loncommon::end_data_table_header_row().'
 5591:        '.&Apache::loncommon::start_data_table_row().'
 5592:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 5593:                 <br />
 5594:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 5595:        '.&Apache::loncommon::end_data_table_row().'
 5596:      '.&Apache::loncommon::end_data_table().'
 5597:    </form>
 5598:    <br />
 5599: ');
 5600: 
 5601:     &Apache::lonpickcode::code_list($r,2);
 5602: 
 5603:     $r->print('<br /><form method="post" name="checkscantron" action="">'.
 5604:              $default_form_data."\n".
 5605:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 5606:              &Apache::loncommon::start_data_table_header_row()."\n".
 5607:              '<th colspan="2">
 5608:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
 5609:              '</th>'."\n".
 5610:               &Apache::loncommon::end_data_table_header_row()."\n".
 5611:               &Apache::loncommon::start_data_table_row()."\n".
 5612:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 5613:               '<td> '.$sequence_selector.' </td>'.
 5614:               &Apache::loncommon::end_data_table_row()."\n".
 5615:               &Apache::loncommon::start_data_table_row()."\n".
 5616:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 5617:               '<td> '.$file_selector.' </td>'."\n".
 5618:               &Apache::loncommon::end_data_table_row()."\n".
 5619:               &Apache::loncommon::start_data_table_row()."\n".
 5620:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 5621:               '<td> '.$format_selector.' </td>'."\n".
 5622:               &Apache::loncommon::end_data_table_row()."\n".
 5623:               &Apache::loncommon::start_data_table_row()."\n".
 5624:               '<td> '.&mt('Options').' </td>'."\n".
 5625:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
 5626:               &Apache::loncommon::end_data_table_row()."\n".
 5627:               &Apache::loncommon::start_data_table_row()."\n".
 5628:               '<td colspan="2">'."\n".
 5629:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 5630:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
 5631:               '</td>'."\n".
 5632:               &Apache::loncommon::end_data_table_row()."\n".
 5633:               &Apache::loncommon::end_data_table()."\n".
 5634:               '</form><br />');
 5635:     return;
 5636: }
 5637: 
 5638: =pod
 5639: 
 5640: =item get_scantron_config
 5641: 
 5642:    Parse and return the bubblesheet configuration line selected as a
 5643:    hash of configuration file fields.
 5644: 
 5645:  Arguments:
 5646:     which - the name of the configuration to parse from the file.
 5647: 
 5648: 
 5649:  Returns:
 5650:             If the named configuration is not in the file, an empty
 5651:             hash is returned.
 5652:     a hash with the fields
 5653:       name         - internal name for the this configuration setup
 5654:       description  - text to display to operator that describes this config
 5655:       CODElocation - if 0 or the string 'none'
 5656:                           - no CODE exists for this config
 5657:                      if -1 || the string 'letter'
 5658:                           - a CODE exists for this config and is
 5659:                             a string of letters
 5660:                      Unsupported value (but planned for future support)
 5661:                           if a positive integer
 5662:                                - The CODE exists as the first n items from
 5663:                                  the question section of the form
 5664:                           if the string 'number'
 5665:                                - The CODE exists for this config and is
 5666:                                  a string of numbers
 5667:       CODEstart   - (only matter if a CODE exists) column in the line where
 5668:                      the CODE starts
 5669:       CODElength  - length of the CODE
 5670:       IDstart     - column where the student/employee ID starts
 5671:       IDlength    - length of the student/employee ID info
 5672:       Qstart      - column where the information from the bubbled
 5673:                     'questions' start
 5674:       Qlength     - number of columns comprising a single bubble line from
 5675:                     the sheet. (usually either 1 or 10)
 5676:       Qon         - either a single character representing the character used
 5677:                     to signal a bubble was chosen in the positional setup, or
 5678:                     the string 'letter' if the letter of the chosen bubble is
 5679:                     in the final, or 'number' if a number representing the
 5680:                     chosen bubble is in the file (1->A 0->J)
 5681:       Qoff        - the character used to represent that a bubble was
 5682:                     left blank
 5683:       PaperID     - if the scanning process generates a unique number for each
 5684:                     sheet scanned the column that this ID number starts in
 5685:       PaperIDlength - number of columns that comprise the unique ID number
 5686:                       for the sheet of paper
 5687:       FirstName   - column that the first name starts in
 5688:       FirstNameLength - number of columns that the first name spans
 5689:  
 5690:       LastName    - column that the last name starts in
 5691:       LastNameLength - number of columns that the last name spans
 5692:       BubblesPerRow - number of bubbles available in each row used to 
 5693:                       bubble an answer. (If not specified, 10 assumed).
 5694: 
 5695: =cut
 5696: 
 5697: sub get_scantron_config {
 5698:     my ($which) = @_;
 5699:     my @lines = &get_scantronformat_file();
 5700:     my %config;
 5701:     #FIXME probably should move to XML it has already gotten a bit much now
 5702:     foreach my $line (@lines) {
 5703: 	my ($name,$descrip)=split(/:/,$line);
 5704: 	if ($name ne $which ) { next; }
 5705: 	chomp($line);
 5706: 	my @config=split(/:/,$line);
 5707: 	$config{'name'}=$config[0];
 5708: 	$config{'description'}=$config[1];
 5709: 	$config{'CODElocation'}=$config[2];
 5710: 	$config{'CODEstart'}=$config[3];
 5711: 	$config{'CODElength'}=$config[4];
 5712: 	$config{'IDstart'}=$config[5];
 5713: 	$config{'IDlength'}=$config[6];
 5714: 	$config{'Qstart'}=$config[7];
 5715:  	$config{'Qlength'}=$config[8];
 5716: 	$config{'Qoff'}=$config[9];
 5717: 	$config{'Qon'}=$config[10];
 5718: 	$config{'PaperID'}=$config[11];
 5719: 	$config{'PaperIDlength'}=$config[12];
 5720: 	$config{'FirstName'}=$config[13];
 5721: 	$config{'FirstNamelength'}=$config[14];
 5722: 	$config{'LastName'}=$config[15];
 5723: 	$config{'LastNamelength'}=$config[16];
 5724:         $config{'BubblesPerRow'}=$config[17];
 5725: 	last;
 5726:     }
 5727:     return %config;
 5728: }
 5729: 
 5730: =pod 
 5731: 
 5732: =item username_to_idmap
 5733: 
 5734:     creates a hash keyed by student/employee ID with values of the corresponding
 5735:     student username:domain. If a single ID occurs for more than one student,
 5736:     the status of the student is checked, and if Active, the value in the hash
 5737:     will be set to the Active student.
 5738: 
 5739:   Arguments:
 5740: 
 5741:     $classlist - reference to the class list hash. This is a hash
 5742:                  keyed by student name:domain  whose elements are references
 5743:                  to arrays containing various chunks of information
 5744:                  about the student. (See loncoursedata for more info).
 5745: 
 5746:   Returns
 5747:     %idmap - the constructed hash
 5748: 
 5749: =cut
 5750: 
 5751: sub username_to_idmap {
 5752:     my ($classlist)= @_;
 5753:     my %idmap;
 5754:     foreach my $student (keys(%$classlist)) {
 5755:         my $id = $classlist->{$student}->[&Apache::loncoursedata::CL_ID];
 5756:         unless ($id eq '') {
 5757:             if (!exists($idmap{$id})) {
 5758:                 $idmap{$id} = $student;
 5759:             } else {
 5760:                 my $status = $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS];
 5761:                 if ($status eq 'Active') {
 5762:                     $idmap{$id} = $student;
 5763:                 }
 5764:             }
 5765:         }
 5766:     }
 5767:     return %idmap;
 5768: }
 5769: 
 5770: =pod
 5771: 
 5772: =item scantron_fixup_scanline
 5773: 
 5774:    Process a requested correction to a scanline.
 5775: 
 5776:   Arguments:
 5777:     $scantron_config   - hash from &get_scantron_config()
 5778:     $scan_data         - hash of correction information 
 5779:                           (see &scantron_getfile())
 5780:     $line              - existing scanline
 5781:     $whichline         - line number of the passed in scanline
 5782:     $field             - type of change to process 
 5783:                          (either 
 5784:                           'ID'     -> correct the student/employee ID
 5785:                           'CODE'   -> correct the CODE
 5786:                           'answer' -> fixup the submitted answers)
 5787:     
 5788:    $args               - hash of additional info,
 5789:                           - 'ID' 
 5790:                                'newid' -> studentID to use in replacement
 5791:                                           of existing one
 5792:                           - 'CODE' 
 5793:                                'CODE_ignore_dup' - set to true if duplicates
 5794:                                                    should be ignored.
 5795: 	                       'CODE' - is new code or 'use_unfound'
 5796:                                         if the existing unfound code should
 5797:                                         be used as is
 5798:                           - 'answer'
 5799:                                'response' - new answer or 'none' if blank
 5800:                                'question' - the bubble line to change
 5801:                                'questionnum' - the question identifier,
 5802:                                                may include subquestion. 
 5803: 
 5804:   Returns:
 5805:     $line - the modified scanline
 5806: 
 5807:   Side effects: 
 5808:     $scan_data - may be updated
 5809: 
 5810: =cut
 5811: 
 5812: 
 5813: sub scantron_fixup_scanline {
 5814:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 5815:     if ($field eq 'ID') {
 5816: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 5817: 	    return ($line,1,'New value too large');
 5818: 	}
 5819: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 5820: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 5821: 				     $args->{'newid'});
 5822: 	}
 5823: 	substr($line,$$scantron_config{'IDstart'}-1,
 5824: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 5825: 	if ($args->{'newid'}=~/^\s*$/) {
 5826: 	    &scan_data($scan_data,"$whichline.user",
 5827: 		       $args->{'username'}.':'.$args->{'domain'});
 5828: 	}
 5829:     } elsif ($field eq 'CODE') {
 5830: 	if ($args->{'CODE_ignore_dup'}) {
 5831: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 5832: 	}
 5833: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 5834: 	if ($args->{'CODE'} ne 'use_unfound') {
 5835: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 5836: 		return ($line,1,'New CODE value too large');
 5837: 	    }
 5838: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 5839: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 5840: 	    }
 5841: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 5842: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 5843: 	}
 5844:     } elsif ($field eq 'answer') {
 5845: 	my $length=$scantron_config->{'Qlength'};
 5846: 	my $off=$scantron_config->{'Qoff'};
 5847: 	my $on=$scantron_config->{'Qon'};
 5848: 	my $answer=${off}x$length;
 5849: 	if ($args->{'response'} eq 'none') {
 5850: 	    &scan_data($scan_data,
 5851: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 5852: 	} else {
 5853: 	    if ($on eq 'letter') {
 5854: 		my @alphabet=('A'..'Z');
 5855: 		$answer=$alphabet[$args->{'response'}];
 5856: 	    } elsif ($on eq 'number') {
 5857: 		$answer=$args->{'response'}+1;
 5858: 		if ($answer == 10) { $answer = '0'; }
 5859: 	    } else {
 5860: 		substr($answer,$args->{'response'},1)=$on;
 5861: 	    }
 5862: 	    &scan_data($scan_data,
 5863: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 5864: 	}
 5865: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 5866: 	substr($line,$where-1,$length)=$answer;
 5867:     }
 5868:     return $line;
 5869: }
 5870: 
 5871: =pod
 5872: 
 5873: =item scan_data
 5874: 
 5875:     Edit or look up  an item in the scan_data hash.
 5876: 
 5877:   Arguments:
 5878:     $scan_data  - The hash (see scantron_getfile)
 5879:     $key        - shorthand of the key to edit (actual key is
 5880:                   scantronfilename_key).
 5881:     $data        - New value of the hash entry.
 5882:     $delete      - If true, the entry is removed from the hash.
 5883: 
 5884:   Returns:
 5885:     The new value of the hash table field (undefined if deleted).
 5886: 
 5887: =cut
 5888: 
 5889: 
 5890: sub scan_data {
 5891:     my ($scan_data,$key,$value,$delete)=@_;
 5892:     my $filename=$env{'form.scantron_selectfile'};
 5893:     if (defined($value)) {
 5894: 	$scan_data->{$filename.'_'.$key} = $value;
 5895:     }
 5896:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 5897:     return $scan_data->{$filename.'_'.$key};
 5898: }
 5899: 
 5900: # ----- These first few routines are general use routines.----
 5901: 
 5902: # Return the number of occurences of a pattern in a string.
 5903: 
 5904: sub occurence_count {
 5905:     my ($string, $pattern) = @_;
 5906: 
 5907:     my @matches = ($string =~ /$pattern/g);
 5908: 
 5909:     return scalar(@matches);
 5910: }
 5911: 
 5912: 
 5913: # Take a string known to have digits and convert all the
 5914: # digits into letters in the range J,A..I.
 5915: 
 5916: sub digits_to_letters {
 5917:     my ($input) = @_;
 5918: 
 5919:     my @alphabet = ('J', 'A'..'I');
 5920: 
 5921:     my @input    = split(//, $input);
 5922:     my $output ='';
 5923:     for (my $i = 0; $i < scalar(@input); $i++) {
 5924: 	if ($input[$i] =~ /\d/) {
 5925: 	    $output .= $alphabet[$input[$i]];
 5926: 	} else {
 5927: 	    $output .= $input[$i];
 5928: 	}
 5929:     }
 5930:     return $output;
 5931: }
 5932: 
 5933: =pod 
 5934: 
 5935: =item scantron_parse_scanline
 5936: 
 5937:   Decodes a scanline from the selected bubblesheet file
 5938: 
 5939:  Arguments:
 5940:     line             - The text of the bubblesheet file line to process
 5941:     whichline        - Line number
 5942:     scantron_config  - Hash describing the format of the bubblesheet lines.
 5943:     scan_data        - Hash of extra information about the scanline
 5944:                        (see scantron_getfile for more information)
 5945:     just_header      - True if should not process question answers but only
 5946:                        the stuff to the left of the answers.
 5947:     randomorder      - True if randomorder in use
 5948:     randompick       - True if randompick in use
 5949:     sequence         - Exam folder URL
 5950:     master_seq       - Ref to array containing symbs in exam folder
 5951:     symb_to_resource - Ref to hash of symbs for resources in exam folder
 5952:                        (corresponding values are resource objects)
 5953:     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
 5954:     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
 5955:                        are refs to an array of resource objects, ordered
 5956:                        according to order used for CODE, when randomorder
 5957:                        and or randompick are in use.
 5958:     respnumlookup    - Ref to hash mapping question numbers in bubble lines
 5959:                        for current line to question number used for same question
 5960:                         in "Master Sequence" (as seen by Course Coordinator).
 5961:     startline        - Ref to hash where key is question number (0 is first)
 5962:                        and value is number of first bubble line for current 
 5963:                        student or code-based randompick and/or randomorder.
 5964:     totalref         - Ref of scalar used to score total number of bubble
 5965:                        lines needed for responses in a scan line (used when
 5966:                        randompick in use. 
 5967:     
 5968:  Returns:
 5969:    Hash containing the result of parsing the scanline
 5970: 
 5971:    Keys are all proceeded by the string 'scantron.'
 5972: 
 5973:        CODE    - the CODE in use for this scanline
 5974:        useCODE - 1 if the CODE is invalid but it usage has been forced
 5975:                  by the operator
 5976:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 5977:                             CODEs were selected, but the usage has been
 5978:                             forced by the operator
 5979:        ID  - student/employee ID
 5980:        PaperID - if used, the ID number printed on the sheet when the 
 5981:                  paper was scanned
 5982:        FirstName - first name from the sheet
 5983:        LastName  - last name from the sheet
 5984: 
 5985:      if just_header was not true these key may also exist
 5986: 
 5987:        missingerror - a list of bubble ranges that are considered to be answers
 5988:                       to a single question that don't have any bubbles filled in.
 5989:                       Of the form questionnumber:firstbubblenumber:count.
 5990:        doubleerror  - a list of bubble ranges that are considered to be answers
 5991:                       to a single question that have more than one bubble filled in.
 5992:                       Of the form questionnumber::firstbubblenumber:count
 5993:    
 5994:                 In the above, count is the number of bubble responses in the
 5995:                 input line needed to represent the possible answers to the question.
 5996:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 5997:                 per line would have count = 2.
 5998: 
 5999:        maxquest     - the number of the last bubble line that was parsed
 6000: 
 6001:        (<number> starts at 1)
 6002:        <number>.answer - zero or more letters representing the selected
 6003:                          letters from the scanline for the bubble line 
 6004:                          <number>.
 6005:                          if blank there was either no bubble or there where
 6006:                          multiple bubbles, (consult the keys missingerror and
 6007:                          doubleerror if this is an error condition)
 6008: 
 6009: =cut
 6010: 
 6011: sub scantron_parse_scanline {
 6012:     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
 6013:         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
 6014:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
 6015: 
 6016:     my %record;
 6017:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
 6018:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 6019: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 6020: 	if ($$scantron_config{'CODElocation'} < 0 ||
 6021: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 6022: 	    $$scantron_config{'CODElocation'} eq 'number') {
 6023: 	    $record{'scantron.CODE'}=substr($data,
 6024: 					    $$scantron_config{'CODEstart'}-1,
 6025: 					    $$scantron_config{'CODElength'});
 6026: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 6027: 		$record{'scantron.useCODE'}=1;
 6028: 	    }
 6029: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 6030: 		$record{'scantron.CODE_ignore_dup'}=1;
 6031: 	    }
 6032: 	} else {
 6033: 	    #FIXME interpret first N questions
 6034: 	}
 6035:     }
 6036:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 6037: 				  $$scantron_config{'IDlength'});
 6038:     $record{'scantron.PaperID'}=
 6039: 	substr($data,$$scantron_config{'PaperID'}-1,
 6040: 	       $$scantron_config{'PaperIDlength'});
 6041:     $record{'scantron.FirstName'}=
 6042: 	substr($data,$$scantron_config{'FirstName'}-1,
 6043: 	       $$scantron_config{'FirstNamelength'});
 6044:     $record{'scantron.LastName'}=
 6045: 	substr($data,$$scantron_config{'LastName'}-1,
 6046: 	       $$scantron_config{'LastNamelength'});
 6047:     if ($just_header) { return \%record; }
 6048: 
 6049:     my @alphabet=('A'..'Z');
 6050:     my $questnum=0;
 6051:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 6052: 
 6053:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 6054:     if ($randompick || $randomorder) {
 6055:         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
 6056:                                          $master_seq,$symb_to_resource,
 6057:                                          $partids_by_symb,$orderedforcode,
 6058:                                          $respnumlookup,$startline);
 6059:         if ($total) {
 6060:             $lastpos = $total*$$scantron_config{'Qlength'}; 
 6061:         }
 6062:         if (ref($totalref)) {
 6063:             $$totalref = $total;
 6064:         }
 6065:     }
 6066:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 6067:     chomp($questions);		# Get rid of any trailing \n.
 6068:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 6069:     while (length($questions)) {
 6070:         my $answers_needed;
 6071:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6072:             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
 6073:         } else {
 6074: 	    $answers_needed = $bubble_lines_per_response{$questnum};
 6075:         }
 6076:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 6077:                              || 1;
 6078:         $questnum++;
 6079:         my $quest_id = $questnum;
 6080:         my $currentquest = substr($questions,0,$answer_length);
 6081:         $questions       = substr($questions,$answer_length);
 6082:         if (length($currentquest) < $answer_length) { next; }
 6083: 
 6084:         my $subdivided;
 6085:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6086:             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
 6087:         } else {
 6088:             $subdivided = $subdivided_bubble_lines{$questnum-1};
 6089:         }
 6090:         if ($subdivided =~ /,/) {
 6091:             my $subquestnum = 1;
 6092:             my $subquestions = $currentquest;
 6093:             my @subanswers_needed = split(/,/,$subdivided);
 6094:             foreach my $subans (@subanswers_needed) {
 6095:                 my $subans_length =
 6096:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 6097:                 my $currsubquest = substr($subquestions,0,$subans_length);
 6098:                 $subquestions   = substr($subquestions,$subans_length);
 6099:                 $quest_id = "$questnum.$subquestnum";
 6100:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 6101:                     ($$scantron_config{'Qon'} eq 'number')) {
 6102:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 6103:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6104:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6105:                         $randomorder,$randompick,$respnumlookup);
 6106:                 } else {
 6107:                     $ansnum = &scantron_validator_positional($ansnum,
 6108:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6109:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6110:                         $randomorder,$randompick,$respnumlookup);
 6111:                 }
 6112:                 $subquestnum ++;
 6113:             }
 6114:         } else {
 6115:             if (($$scantron_config{'Qon'} eq 'letter') ||
 6116:                 ($$scantron_config{'Qon'} eq 'number')) {
 6117:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 6118:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6119:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6120:                     $randomorder,$randompick,$respnumlookup);
 6121:             } else {
 6122:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 6123:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6124:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6125:                     $randomorder,$randompick,$respnumlookup);
 6126:             }
 6127:         }
 6128:     }
 6129:     $record{'scantron.maxquest'}=$questnum;
 6130:     return \%record;
 6131: }
 6132: 
 6133: sub get_master_seq {
 6134:     my ($resources,$master_seq,$symb_to_resource) = @_;
 6135:     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') && 
 6136:                    (ref($symb_to_resource) eq 'HASH'));
 6137:     my $resource_error;
 6138:     foreach my $resource (@{$resources}) {
 6139:         my $ressymb;
 6140:         if (ref($resource)) {
 6141:             $ressymb = $resource->symb();
 6142:             push(@{$master_seq},$ressymb);
 6143:             $symb_to_resource->{$ressymb} = $resource;
 6144:         } else {
 6145:             $resource_error = 1;
 6146:             last;
 6147:         }
 6148:     }
 6149:     return $resource_error;
 6150: }
 6151: 
 6152: sub get_respnum_lookups {
 6153:     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
 6154:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
 6155:     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
 6156:                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
 6157:                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
 6158:                    (ref($startline) eq 'HASH'));
 6159:     my ($user,$scancode);
 6160:     if ((exists($record->{'scantron.CODE'})) &&
 6161:         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
 6162:         $scancode = $record->{'scantron.CODE'};
 6163:     } else {
 6164:         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
 6165:     }
 6166:     my @mapresources =
 6167:         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
 6168:                      $orderedforcode);
 6169:     my $total = 0;
 6170:     my $count = 0;
 6171:     foreach my $resource (@mapresources) {
 6172:         my $id = $resource->id();
 6173:         my $symb = $resource->symb();
 6174:         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
 6175:             foreach my $partid (@{$partids_by_symb->{$symb}}) {
 6176:                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
 6177:                 if ($respnum ne '') {
 6178:                     $respnumlookup->{$count} = $respnum;
 6179:                     $startline->{$count} = $total;
 6180:                     $total += $bubble_lines_per_response{$respnum};
 6181:                     $count ++;
 6182:                 }
 6183:             }
 6184:         }
 6185:     }
 6186:     return $total;
 6187: }
 6188: 
 6189: sub scantron_validator_lettnum {
 6190:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 6191:         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
 6192:         $randompick,$respnumlookup) = @_;
 6193: 
 6194:     # Qon 'letter' implies for each slot in currquest we have:
 6195:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 6196:     #    about anything else (esp. a value of Qoff) for missing
 6197:     #    bubbles.
 6198:     #
 6199:     # Qon 'number' implies each slot gives a digit that indexes the
 6200:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 6201:     #    and * or ? for double bubbles on a single line.
 6202:     #
 6203: 
 6204:     my $matchon;
 6205:     if ($$scantron_config{'Qon'} eq 'letter') {
 6206:         $matchon = '[A-Z]';
 6207:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 6208:         $matchon = '\d';
 6209:     }
 6210:     my $occurrences = 0;
 6211:     my $responsenum = $questnum-1;
 6212:     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6213:        $responsenum = $respnumlookup->{$questnum-1} 
 6214:     }
 6215:     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6216:         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6217:         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6218:         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6219:         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6220:         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6221:         my @singlelines = split('',$currquest);
 6222:         foreach my $entry (@singlelines) {
 6223:             $occurrences = &occurence_count($entry,$matchon);
 6224:             if ($occurrences > 1) {
 6225:                 last;
 6226:             }
 6227:         }
 6228:     } else {
 6229:         $occurrences = &occurence_count($currquest,$matchon); 
 6230:     }
 6231:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 6232:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6233:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6234:             my $bubble = substr($currquest,$ans,1);
 6235:             if ($bubble =~ /$matchon/ ) {
 6236:                 if ($$scantron_config{'Qon'} eq 'number') {
 6237:                     if ($bubble == 0) {
 6238:                         $bubble = 10; 
 6239:                     }
 6240:                     $record->{"scantron.$ansnum.answer"} = 
 6241:                         $alphabet->[$bubble-1];
 6242:                 } else {
 6243:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 6244:                 }
 6245:             } else {
 6246:                 $record->{"scantron.$ansnum.answer"}='';
 6247:             }
 6248:             $ansnum++;
 6249:         }
 6250:     } elsif (!defined($currquest)
 6251:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 6252:             || (&occurence_count($currquest,$matchon) == 0)) {
 6253:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6254:             $record->{"scantron.$ansnum.answer"}='';
 6255:             $ansnum++;
 6256:         }
 6257:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6258:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 6259:         }
 6260:     } else {
 6261:         if ($$scantron_config{'Qon'} eq 'number') {
 6262:             $currquest = &digits_to_letters($currquest);            
 6263:         }
 6264:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6265:             my $bubble = substr($currquest,$ans,1);
 6266:             $record->{"scantron.$ansnum.answer"} = $bubble;
 6267:             $ansnum++;
 6268:         }
 6269:     }
 6270:     return $ansnum;
 6271: }
 6272: 
 6273: sub scantron_validator_positional {
 6274:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 6275:         $whichline,$alphabet,$record,$scantron_config,$scan_data,
 6276:         $randomorder,$randompick,$respnumlookup) = @_;
 6277: 
 6278:     # Otherwise there's a positional notation;
 6279:     # each bubble line requires Qlength items, and there are filled in
 6280:     # bubbles for each case where there 'Qon' characters.
 6281:     #
 6282: 
 6283:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 6284: 
 6285:     # If the split only gives us one element.. the full length of the
 6286:     # answer string, no bubbles are filled in:
 6287: 
 6288:     if ($answers_needed eq '') {
 6289:         return;
 6290:     }
 6291: 
 6292:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 6293:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6294:             $record->{"scantron.$ansnum.answer"}='';
 6295:             $ansnum++;
 6296:         }
 6297:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6298:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 6299:         }
 6300:     } elsif (scalar(@array) == 2) {
 6301:         my $location = length($array[0]);
 6302:         my $line_num = int($location / $$scantron_config{'Qlength'});
 6303:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 6304:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6305:             if ($ans eq $line_num) {
 6306:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 6307:             } else {
 6308:                 $record->{"scantron.$ansnum.answer"} = ' ';
 6309:             }
 6310:             $ansnum++;
 6311:          }
 6312:     } else {
 6313:         #  If there's more than one instance of a bubble character
 6314:         #  That's a double bubble; with positional notation we can
 6315:         #  record all the bubbles filled in as well as the
 6316:         #  fact this response consists of multiple bubbles.
 6317:         #
 6318:         my $responsenum = $questnum-1;
 6319:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6320:             $responsenum = $respnumlookup->{$questnum-1}
 6321:         }
 6322:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6323:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6324:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6325:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6326:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6327:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6328:             my $doubleerror = 0;
 6329:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 6330:                    (!$doubleerror)) {
 6331:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 6332:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 6333:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 6334:                if (length(@currarray) > 2) {
 6335:                    $doubleerror = 1;
 6336:                } 
 6337:             }
 6338:             if ($doubleerror) {
 6339:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6340:             }
 6341:         } else {
 6342:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6343:         }
 6344:         my $item = $ansnum;
 6345:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6346:             $record->{"scantron.$item.answer"} = '';
 6347:             $item ++;
 6348:         }
 6349: 
 6350:         my @ans=@array;
 6351:         my $i=0;
 6352:         my $increment = 0;
 6353:         while ($#ans) {
 6354:             $i+=length($ans[0]) + $increment;
 6355:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 6356:             my $bubble = $i%$$scantron_config{'Qlength'};
 6357:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 6358:             shift(@ans);
 6359:             $increment = 1;
 6360:         }
 6361:         $ansnum += $answers_needed;
 6362:     }
 6363:     return $ansnum;
 6364: }
 6365: 
 6366: =pod
 6367: 
 6368: =item scantron_add_delay
 6369: 
 6370:    Adds an error message that occurred during the grading phase to a
 6371:    queue of messages to be shown after grading pass is complete
 6372: 
 6373:  Arguments:
 6374:    $delayqueue  - arrary ref of hash ref of error messages
 6375:    $scanline    - the scanline that caused the error
 6376:    $errormesage - the error message
 6377:    $errorcode   - a numeric code for the error
 6378: 
 6379:  Side Effects:
 6380:    updates the $delayqueue to have a new hash ref of the error
 6381: 
 6382: =cut
 6383: 
 6384: sub scantron_add_delay {
 6385:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 6386:     push(@$delayqueue,
 6387: 	 {'line' => $scanline, 'emsg' => $errormessage,
 6388: 	  'ecode' => $errorcode }
 6389: 	 );
 6390: }
 6391: 
 6392: =pod
 6393: 
 6394: =item scantron_find_student
 6395: 
 6396:    Finds the username for the current scanline
 6397: 
 6398:   Arguments:
 6399:    $scantron_record - hash result from scantron_parse_scanline
 6400:    $scan_data       - hash of correction information 
 6401:                       (see &scantron_getfile() form more information)
 6402:    $idmap           - hash from &username_to_idmap()
 6403:    $line            - number of current scanline
 6404:  
 6405:   Returns:
 6406:    Either 'username:domain' or undef if unknown
 6407: 
 6408: =cut
 6409: 
 6410: sub scantron_find_student {
 6411:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 6412:     my $scanID=$$scantron_record{'scantron.ID'};
 6413:     if ($scanID =~ /^\s*$/) {
 6414:  	return &scan_data($scan_data,"$line.user");
 6415:     }
 6416:     foreach my $id (keys(%$idmap)) {
 6417:  	if (lc($id) eq lc($scanID)) {
 6418:  	    return $$idmap{$id};
 6419:  	}
 6420:     }
 6421:     return undef;
 6422: }
 6423: 
 6424: =pod
 6425: 
 6426: =item scantron_filter
 6427: 
 6428:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 6429:    hidden resources was selected
 6430: 
 6431: =cut
 6432: 
 6433: sub scantron_filter {
 6434:     my ($curres)=@_;
 6435: 
 6436:     if (ref($curres) && $curres->is_problem()) {
 6437: 	# if the user has asked to not have either hidden
 6438: 	# or 'randomout' controlled resources to be graded
 6439: 	# don't include them
 6440: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6441: 	    && $curres->randomout) {
 6442: 	    return 0;
 6443: 	}
 6444: 	return 1;
 6445:     }
 6446:     return 0;
 6447: }
 6448: 
 6449: =pod
 6450: 
 6451: =item scantron_process_corrections
 6452: 
 6453:    Gets correction information out of submitted form data and corrects
 6454:    the scanline
 6455: 
 6456: =cut
 6457: 
 6458: sub scantron_process_corrections {
 6459:     my ($r) = @_;
 6460:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6461:     my ($scanlines,$scan_data)=&scantron_getfile();
 6462:     my $classlist=&Apache::loncoursedata::get_classlist();
 6463:     my $which=$env{'form.scantron_line'};
 6464:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 6465:     my ($skip,$err,$errmsg);
 6466:     if ($env{'form.scantron_skip_record'}) {
 6467: 	$skip=1;
 6468:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 6469: 	my $newstudent=$env{'form.scantron_username'}.':'.
 6470: 	    $env{'form.scantron_domain'};
 6471: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 6472: 	($line,$err,$errmsg)=
 6473: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6474: 				     'ID',{'newid'=>$newid,
 6475: 				    'username'=>$env{'form.scantron_username'},
 6476: 				    'domain'=>$env{'form.scantron_domain'}});
 6477:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 6478: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 6479: 	my $newCODE;
 6480: 	my %args;
 6481: 	if      ($resolution eq 'use_unfound') {
 6482: 	    $newCODE='use_unfound';
 6483: 	} elsif ($resolution eq 'use_found') {
 6484: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 6485: 	} elsif ($resolution eq 'use_typed') {
 6486: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 6487: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 6488: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 6489: 	}
 6490: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 6491: 	    $args{'CODE_ignore_dup'}=1;
 6492: 	}
 6493: 	$args{'CODE'}=$newCODE;
 6494: 	($line,$err,$errmsg)=
 6495: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6496: 				     'CODE',\%args);
 6497:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 6498: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 6499: 	    ($line,$err,$errmsg)=
 6500: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 6501: 					 $which,'answer',
 6502: 					 { 'question'=>$question,
 6503: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 6504:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 6505: 	    if ($err) { last; }
 6506: 	}
 6507:     }
 6508:     if ($err) {
 6509:         $r->print(
 6510:             '<p class="LC_error">'
 6511:            .&mt('Unable to accept last correction, an error occurred: [_1]',
 6512:                 $errmsg)
 6513:            .'</p>');
 6514:     } else {
 6515: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 6516: 	&scantron_putfile($scanlines,$scan_data);
 6517:     }
 6518: }
 6519: 
 6520: =pod
 6521: 
 6522: =item reset_skipping_status
 6523: 
 6524:    Forgets the current set of remember skipped scanlines (and thus
 6525:    reverts back to considering all lines in the
 6526:    scantron_skipped_<filename> file)
 6527: 
 6528: =cut
 6529: 
 6530: sub reset_skipping_status {
 6531:     my ($scanlines,$scan_data)=&scantron_getfile();
 6532:     &scan_data($scan_data,'remember_skipping',undef,1);
 6533:     &scantron_putfile(undef,$scan_data);
 6534: }
 6535: 
 6536: =pod
 6537: 
 6538: =item start_skipping
 6539: 
 6540:    Marks a scanline to be skipped. 
 6541: 
 6542: =cut
 6543: 
 6544: sub start_skipping {
 6545:     my ($scan_data,$i)=@_;
 6546:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6547:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 6548: 	$remembered{$i}=2;
 6549:     } else {
 6550: 	$remembered{$i}=1;
 6551:     }
 6552:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 6553: }
 6554: 
 6555: =pod
 6556: 
 6557: =item should_be_skipped
 6558: 
 6559:    Checks whether a scanline should be skipped.
 6560: 
 6561: =cut
 6562: 
 6563: sub should_be_skipped {
 6564:     my ($scanlines,$scan_data,$i)=@_;
 6565:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 6566: 	# not redoing old skips
 6567: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 6568: 	return 0;
 6569:     }
 6570:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6571: 
 6572:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 6573: 	return 0;
 6574:     }
 6575:     return 1;
 6576: }
 6577: 
 6578: =pod
 6579: 
 6580: =item remember_current_skipped
 6581: 
 6582:    Discovers what scanlines are in the scantron_skipped_<filename>
 6583:    file and remembers them into scan_data for later use.
 6584: 
 6585: =cut
 6586: 
 6587: sub remember_current_skipped {
 6588:     my ($scanlines,$scan_data)=&scantron_getfile();
 6589:     my %to_remember;
 6590:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6591: 	if ($scanlines->{'skipped'}[$i]) {
 6592: 	    $to_remember{$i}=1;
 6593: 	}
 6594:     }
 6595: 
 6596:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 6597:     &scantron_putfile(undef,$scan_data);
 6598: }
 6599: 
 6600: =pod
 6601: 
 6602: =item check_for_error
 6603: 
 6604:     Checks if there was an error when attempting to remove a specific
 6605:     scantron_.. bubblesheet data file. Prints out an error if
 6606:     something went wrong.
 6607: 
 6608: =cut
 6609: 
 6610: sub check_for_error {
 6611:     my ($r,$result)=@_;
 6612:     if ($result ne 'ok' && $result ne 'not_found' ) {
 6613: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 6614:     }
 6615: }
 6616: 
 6617: =pod
 6618: 
 6619: =item scantron_warning_screen
 6620: 
 6621:    Interstitial screen to make sure the operator has selected the
 6622:    correct options before we start the validation phase.
 6623: 
 6624: =cut
 6625: 
 6626: sub scantron_warning_screen {
 6627:     my ($button_text,$symb)=@_;
 6628:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 6629:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6630:     my $CODElist;
 6631:     if ($scantron_config{'CODElocation'} &&
 6632: 	$scantron_config{'CODEstart'} &&
 6633: 	$scantron_config{'CODElength'}) {
 6634: 	$CODElist=$env{'form.scantron_CODElist'};
 6635: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
 6636: 	$CODElist=
 6637: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 6638: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 6639:     }
 6640:     my $lastbubblepoints;
 6641:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 6642:         $lastbubblepoints =
 6643:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
 6644:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
 6645:     }
 6646:     return ('
 6647: <p>
 6648: <span class="LC_warning">
 6649: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
 6650: </p>
 6651: <table>
 6652: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 6653: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 6654: '.$CODElist.$lastbubblepoints.'
 6655: </table>
 6656: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
 6657: '.&mt('If something is incorrect, please return to [_1]Grade/Manage/Review Bubblesheets[_2] to start over.','<a href="/adm/grades?symb='.$symb.'&command=scantron_selectphase" class="LC_info">','</a>').'</p>
 6658: 
 6659: <br />
 6660: ');
 6661: }
 6662: 
 6663: =pod
 6664: 
 6665: =item scantron_do_warning
 6666: 
 6667:    Check if the operator has picked something for all required
 6668:    fields. Error out if something is missing.
 6669: 
 6670: =cut
 6671: 
 6672: sub scantron_do_warning {
 6673:     my ($r,$symb)=@_;
 6674:     if (!$symb) {return '';}
 6675:     my $default_form_data=&defaultFormData($symb);
 6676:     $r->print(&scantron_form_start().$default_form_data);
 6677:     if ( $env{'form.selectpage'} eq '' ||
 6678: 	 $env{'form.scantron_selectfile'} eq '' ||
 6679: 	 $env{'form.scantron_format'} eq '' ) {
 6680: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
 6681: 	if ( $env{'form.selectpage'} eq '') {
 6682: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 6683: 	} 
 6684: 	if ( $env{'form.scantron_selectfile'} eq '') {
 6685: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected a file that contains the student's response data.").'</span></p>');
 6686: 	} 
 6687: 	if ( $env{'form.scantron_format'} eq '') {
 6688: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected the format of the student's response data.").'</span></p>');
 6689: 	} 
 6690:     } else {
 6691: 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
 6692:         my $bubbledbyhand=&hand_bubble_option();
 6693: 	$r->print('
 6694: '.$warning.$bubbledbyhand.'
 6695: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 6696: <input type="hidden" name="command" value="scantron_validate" />
 6697: ');
 6698:     }
 6699:     $r->print("</form><br />");
 6700:     return '';
 6701: }
 6702: 
 6703: =pod
 6704: 
 6705: =item scantron_form_start
 6706: 
 6707:     html hidden input for remembering all selected grading options
 6708: 
 6709: =cut
 6710: 
 6711: sub scantron_form_start {
 6712:     my ($max_bubble)=@_;
 6713:     my $result= <<SCANTRONFORM;
 6714: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 6715:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 6716:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 6717:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 6718:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 6719:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 6720:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 6721:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 6722:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 6723:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 6724: SCANTRONFORM
 6725: 
 6726:   my $line = 0;
 6727:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 6728:        my $chunk =
 6729: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 6730:        $chunk .=
 6731: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 6732:        $chunk .= 
 6733:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 6734:        $chunk .=
 6735:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 6736:        $chunk .=
 6737:            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
 6738:        $result .= $chunk;
 6739:        $line++;
 6740:     }
 6741:     return $result;
 6742: }
 6743: 
 6744: =pod
 6745: 
 6746: =item scantron_validate_file
 6747: 
 6748:     Dispatch routine for doing validation of a bubblesheet data file.
 6749: 
 6750:     Also processes any necessary information resets that need to
 6751:     occur before validation begins (ignore previous corrections,
 6752:     restarting the skipped records processing)
 6753: 
 6754: =cut
 6755: 
 6756: sub scantron_validate_file {
 6757:     my ($r,$symb) = @_;
 6758:     if (!$symb) {return '';}
 6759:     my $default_form_data=&defaultFormData($symb);
 6760:     
 6761:     # do the detection of only doing skipped records first before we delete
 6762:     # them when doing the corrections reset
 6763:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 6764: 	&reset_skipping_status();
 6765:     }
 6766:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 6767: 	&remember_current_skipped();
 6768: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 6769:     }
 6770: 
 6771:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 6772: 	&check_for_error($r,&scantron_remove_file('corrected'));
 6773: 	&check_for_error($r,&scantron_remove_file('skipped'));
 6774: 	&check_for_error($r,&scantron_remove_scan_data());
 6775: 	$env{'form.scantron_options_ignore'}='done';
 6776:     }
 6777: 
 6778:     if ($env{'form.scantron_corrections'}) {
 6779: 	&scantron_process_corrections($r);
 6780:     }
 6781:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 6782:     #get the student pick code ready
 6783:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 6784:     my $nav_error;
 6785:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6786:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 6787:     if ($nav_error) {
 6788:         $r->print(&navmap_errormsg());
 6789:         return '';
 6790:     }
 6791:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 6792:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 6793:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
 6794:     }
 6795:     $r->print($result);
 6796:     
 6797:     my @validate_phases=( 'sequence',
 6798: 			  'ID',
 6799: 			  'CODE',
 6800: 			  'doublebubble',
 6801: 			  'missingbubbles');
 6802:     if (!$env{'form.validatepass'}) {
 6803: 	$env{'form.validatepass'} = 0;
 6804:     }
 6805:     my $currentphase=$env{'form.validatepass'};
 6806: 
 6807: 
 6808:     my $stop=0;
 6809:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 6810: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 6811: 	$r->rflush();
 6812:      
 6813: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 6814: 	{
 6815: 	    no strict 'refs';
 6816: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 6817: 	}
 6818:     }
 6819:     if (!$stop) {
 6820: 	my $warning=&scantron_warning_screen('Start Grading',$symb);
 6821: 	$r->print(&mt('Validation process complete.').'<br />'.
 6822:                   $warning.
 6823:                   &mt('Perform verification for each student after storage of submissions?').
 6824:                   '&nbsp;<span class="LC_nobreak"><label>'.
 6825:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 6826:                   ('&nbsp;'x3).'<label>'.
 6827:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 6828:                   '</label></span><br />'.
 6829:                   &mt('Grading will take longer if you use verification.').'<br />'.
 6830:                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
 6831:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 6832:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 6833:     } else {
 6834: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 6835: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 6836:     }
 6837:     if ($stop) {
 6838: 	if ($validate_phases[$currentphase] eq 'sequence') {
 6839: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 6840: 	    $r->print(' '.&mt('this error').' <br />');
 6841: 
 6842: 	    $r->print('<p>'.&mt('Or return to [_1]Grade/Manage/Review Bubblesheets[_2] to start over.','<a href="/adm/grades?symb='.$symb.'&command=scantron_selectphase" class="LC_info">','</a>').'</p>');
 6843: 	} else {
 6844:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 6845: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 6846:             } else {
 6847:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 6848:             }
 6849: 	    $r->print(' '.&mt('using corrected info').' <br />');
 6850: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 6851: 	    $r->print(" ".&mt("this scanline saving it for later."));
 6852: 	}
 6853:     }
 6854:     $r->print(" </form><br />");
 6855:     return '';
 6856: }
 6857: 
 6858: 
 6859: =pod
 6860: 
 6861: =item scantron_remove_file
 6862: 
 6863:    Removes the requested bubblesheet data file, makes sure that
 6864:    scantron_original_<filename> is never removed
 6865: 
 6866: 
 6867: =cut
 6868: 
 6869: sub scantron_remove_file {
 6870:     my ($which)=@_;
 6871:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6872:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6873:     my $file='scantron_';
 6874:     if ($which eq 'corrected' || $which eq 'skipped') {
 6875: 	$file.=$which.'_';
 6876:     } else {
 6877: 	return 'refused';
 6878:     }
 6879:     $file.=$env{'form.scantron_selectfile'};
 6880:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 6881: }
 6882: 
 6883: 
 6884: =pod
 6885: 
 6886: =item scantron_remove_scan_data
 6887: 
 6888:    Removes all scan_data correction for the requested bubblesheet
 6889:    data file.  (In the case that both the are doing skipped records we need
 6890:    to remember the old skipped lines for the time being so that element
 6891:    persists for a while.)
 6892: 
 6893: =cut
 6894: 
 6895: sub scantron_remove_scan_data {
 6896:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6897:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6898:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 6899:     my @todelete;
 6900:     my $filename=$env{'form.scantron_selectfile'};
 6901:     foreach my $key (@keys) {
 6902: 	if ($key=~/^\Q$filename\E_/) {
 6903: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 6904: 		$key=~/remember_skipping/) {
 6905: 		next;
 6906: 	    }
 6907: 	    push(@todelete,$key);
 6908: 	}
 6909:     }
 6910:     my $result;
 6911:     if (@todelete) {
 6912: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 6913: 				       \@todelete,$cdom,$cname);
 6914:     } else {
 6915: 	$result = 'ok';
 6916:     }
 6917:     return $result;
 6918: }
 6919: 
 6920: 
 6921: =pod
 6922: 
 6923: =item scantron_getfile
 6924: 
 6925:     Fetches the requested bubblesheet data file (all 3 versions), and
 6926:     the scan_data hash
 6927:   
 6928:   Arguments:
 6929:     None
 6930: 
 6931:   Returns:
 6932:     2 hash references
 6933: 
 6934:      - first one has 
 6935:          orig      -
 6936:          corrected -
 6937:          skipped   -  each of which points to an array ref of the specified
 6938:                       file broken up into individual lines
 6939:          count     - number of scanlines
 6940:  
 6941:      - second is the scan_data hash possible keys are
 6942:        ($number refers to scanline numbered $number and thus the key affects
 6943:         only that scanline
 6944:         $bubline refers to the specific bubble line element and the aspects
 6945:         refers to that specific bubble line element)
 6946: 
 6947:        $number.user - username:domain to use
 6948:        $number.CODE_ignore_dup 
 6949:                     - ignore the duplicate CODE error 
 6950:        $number.useCODE
 6951:                     - use the CODE in the scanline as is
 6952:        $number.no_bubble.$bubline
 6953:                     - it is valid that there is no bubbled in bubble
 6954:                       at $number $bubline
 6955:        remember_skipping
 6956:                     - a frozen hash containing keys of $number and values
 6957:                       of either 
 6958:                         1 - we are on a 'do skipped records pass' and plan
 6959:                             on processing this line
 6960:                         2 - we are on a 'do skipped records pass' and this
 6961:                             scanline has been marked to skip yet again
 6962: 
 6963: =cut
 6964: 
 6965: sub scantron_getfile {
 6966:     #FIXME really would prefer a scantron directory
 6967:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6968:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6969:     my $lines;
 6970:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6971: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 6972:     my %scanlines;
 6973:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 6974:     my $temp=$scanlines{'orig'};
 6975:     $scanlines{'count'}=$#$temp;
 6976: 
 6977:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6978: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 6979:     if ($lines eq '-1') {
 6980: 	$scanlines{'corrected'}=[];
 6981:     } else {
 6982: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 6983:     }
 6984:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6985: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 6986:     if ($lines eq '-1') {
 6987: 	$scanlines{'skipped'}=[];
 6988:     } else {
 6989: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 6990:     }
 6991:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 6992:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 6993:     my %scan_data = @tmp;
 6994:     return (\%scanlines,\%scan_data);
 6995: }
 6996: 
 6997: =pod
 6998: 
 6999: =item lonnet_putfile
 7000: 
 7001:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 7002: 
 7003:  Arguments:
 7004:    $contents - data to store
 7005:    $filename - filename to store $contents into
 7006: 
 7007:  Returns:
 7008:    result value from &Apache::lonnet::finishuserfileupload
 7009: 
 7010: =cut
 7011: 
 7012: sub lonnet_putfile {
 7013:     my ($contents,$filename)=@_;
 7014:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7015:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7016:     $env{'form.sillywaytopassafilearound'}=$contents;
 7017:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 7018: 
 7019: }
 7020: 
 7021: =pod
 7022: 
 7023: =item scantron_putfile
 7024: 
 7025:     Stores the current version of the bubblesheet data files, and the
 7026:     scan_data hash. (Does not modify the original version only the
 7027:     corrected and skipped versions.
 7028: 
 7029:  Arguments:
 7030:     $scanlines - hash ref that looks like the first return value from
 7031:                  &scantron_getfile()
 7032:     $scan_data - hash ref that looks like the second return value from
 7033:                  &scantron_getfile()
 7034: 
 7035: =cut
 7036: 
 7037: sub scantron_putfile {
 7038:     my ($scanlines,$scan_data) = @_;
 7039:     #FIXME really would prefer a scantron directory
 7040:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7041:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7042:     if ($scanlines) {
 7043: 	my $prefix='scantron_';
 7044: # no need to update orig, shouldn't change
 7045: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 7046: #		    $env{'form.scantron_selectfile'});
 7047: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 7048: 			$prefix.'corrected_'.
 7049: 			$env{'form.scantron_selectfile'});
 7050: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 7051: 			$prefix.'skipped_'.
 7052: 			$env{'form.scantron_selectfile'});
 7053:     }
 7054:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 7055: }
 7056: 
 7057: =pod
 7058: 
 7059: =item scantron_get_line
 7060: 
 7061:    Returns the correct version of the scanline
 7062: 
 7063:  Arguments:
 7064:     $scanlines - hash ref that looks like the first return value from
 7065:                  &scantron_getfile()
 7066:     $scan_data - hash ref that looks like the second return value from
 7067:                  &scantron_getfile()
 7068:     $i         - number of the requested line (starts at 0)
 7069: 
 7070:  Returns:
 7071:    A scanline, (either the original or the corrected one if it
 7072:    exists), or undef if the requested scanline should be
 7073:    skipped. (Either because it's an skipped scanline, or it's an
 7074:    unskipped scanline and we are not doing a 'do skipped scanlines'
 7075:    pass.
 7076: 
 7077: =cut
 7078: 
 7079: sub scantron_get_line {
 7080:     my ($scanlines,$scan_data,$i)=@_;
 7081:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 7082:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 7083:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 7084:     return $scanlines->{'orig'}[$i]; 
 7085: }
 7086: 
 7087: =pod
 7088: 
 7089: =item scantron_todo_count
 7090: 
 7091:     Counts the number of scanlines that need processing.
 7092: 
 7093:  Arguments:
 7094:     $scanlines - hash ref that looks like the first return value from
 7095:                  &scantron_getfile()
 7096:     $scan_data - hash ref that looks like the second return value from
 7097:                  &scantron_getfile()
 7098: 
 7099:  Returns:
 7100:     $count - number of scanlines to process
 7101: 
 7102: =cut
 7103: 
 7104: sub get_todo_count {
 7105:     my ($scanlines,$scan_data)=@_;
 7106:     my $count=0;
 7107:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7108: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7109: 	if ($line=~/^[\s\cz]*$/) { next; }
 7110: 	$count++;
 7111:     }
 7112:     return $count;
 7113: }
 7114: 
 7115: =pod
 7116: 
 7117: =item scantron_put_line
 7118: 
 7119:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
 7120:     data file.
 7121: 
 7122:  Arguments:
 7123:     $scanlines - hash ref that looks like the first return value from
 7124:                  &scantron_getfile()
 7125:     $scan_data - hash ref that looks like the second return value from
 7126:                  &scantron_getfile()
 7127:     $i         - line number to update
 7128:     $newline   - contents of the updated scanline
 7129:     $skip      - if true make the line for skipping and update the
 7130:                  'skipped' file
 7131: 
 7132: =cut
 7133: 
 7134: sub scantron_put_line {
 7135:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 7136:     if ($skip) {
 7137: 	$scanlines->{'skipped'}[$i]=$newline;
 7138: 	&start_skipping($scan_data,$i);
 7139: 	return;
 7140:     }
 7141:     $scanlines->{'corrected'}[$i]=$newline;
 7142: }
 7143: 
 7144: =pod
 7145: 
 7146: =item scantron_clear_skip
 7147: 
 7148:    Remove a line from the 'skipped' file
 7149: 
 7150:  Arguments:
 7151:     $scanlines - hash ref that looks like the first return value from
 7152:                  &scantron_getfile()
 7153:     $scan_data - hash ref that looks like the second return value from
 7154:                  &scantron_getfile()
 7155:     $i         - line number to update
 7156: 
 7157: =cut
 7158: 
 7159: sub scantron_clear_skip {
 7160:     my ($scanlines,$scan_data,$i)=@_;
 7161:     if (exists($scanlines->{'skipped'}[$i])) {
 7162: 	undef($scanlines->{'skipped'}[$i]);
 7163: 	return 1;
 7164:     }
 7165:     return 0;
 7166: }
 7167: 
 7168: =pod
 7169: 
 7170: =item scantron_filter_not_exam
 7171: 
 7172:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 7173:    filter out resources that are not marked as 'exam' mode
 7174: 
 7175: =cut
 7176: 
 7177: sub scantron_filter_not_exam {
 7178:     my ($curres)=@_;
 7179:     
 7180:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 7181: 	# if the user has asked to not have either hidden
 7182: 	# or 'randomout' controlled resources to be graded
 7183: 	# don't include them
 7184: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 7185: 	    && $curres->randomout) {
 7186: 	    return 0;
 7187: 	}
 7188: 	return 1;
 7189:     }
 7190:     return 0;
 7191: }
 7192: 
 7193: =pod
 7194: 
 7195: =item scantron_validate_sequence
 7196: 
 7197:     Validates the selected sequence, checking for resource that are
 7198:     not set to exam mode.
 7199: 
 7200: =cut
 7201: 
 7202: sub scantron_validate_sequence {
 7203:     my ($r,$currentphase) = @_;
 7204: 
 7205:     my $navmap=Apache::lonnavmaps::navmap->new();
 7206:     unless (ref($navmap)) {
 7207:         $r->print(&navmap_errormsg());
 7208:         return (1,$currentphase);
 7209:     }
 7210:     my (undef,undef,$sequence)=
 7211: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7212: 
 7213:     my $map=$navmap->getResourceByUrl($sequence);
 7214: 
 7215:     $r->print('<input type="hidden" name="validate_sequence_exam"
 7216:                                     value="ignore" />');
 7217:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 7218: 	my @resources=
 7219: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 7220: 	if (@resources) {
 7221: 	    $r->print(
 7222:                 '<p class="LC_warning">'
 7223:                .&mt('Some resources in the sequence currently are not set to'
 7224:                    .' bubblesheet exam mode. Grading these resources currently may not'
 7225:                    .' work correctly.')
 7226:                .'</p>'
 7227:             );
 7228: 	    return (1,$currentphase);
 7229: 	}
 7230:     }
 7231: 
 7232:     return (0,$currentphase+1);
 7233: }
 7234: 
 7235: 
 7236: 
 7237: sub scantron_validate_ID {
 7238:     my ($r,$currentphase) = @_;
 7239:     
 7240:     #get student info
 7241:     my $classlist=&Apache::loncoursedata::get_classlist();
 7242:     my %idmap=&username_to_idmap($classlist);
 7243: 
 7244:     #get scantron line setup
 7245:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7246:     my ($scanlines,$scan_data)=&scantron_getfile();
 7247: 
 7248:     my $nav_error;
 7249:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
 7250:     if ($nav_error) {
 7251:         $r->print(&navmap_errormsg());
 7252:         return(1,$currentphase);
 7253:     }
 7254: 
 7255:     my %found=('ids'=>{},'usernames'=>{});
 7256:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7257: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7258: 	if ($line=~/^[\s\cz]*$/) { next; }
 7259: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7260: 						 $scan_data);
 7261: 	my $id=$$scan_record{'scantron.ID'};
 7262: 	my $found;
 7263: 	foreach my $checkid (keys(%idmap)) {
 7264: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 7265: 	}
 7266: 	if ($found) {
 7267: 	    my $username=$idmap{$found};
 7268: 	    if ($found{'ids'}{$found}) {
 7269: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7270: 					 $line,'duplicateID',$found);
 7271: 		return(1,$currentphase);
 7272: 	    } elsif ($found{'usernames'}{$username}) {
 7273: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7274: 					 $line,'duplicateID',$username);
 7275: 		return(1,$currentphase);
 7276: 	    }
 7277: 	    #FIXME store away line we previously saw the ID on to use above
 7278: 	    $found{'ids'}{$found}++;
 7279: 	    $found{'usernames'}{$username}++;
 7280: 	} else {
 7281: 	    if ($id =~ /^\s*$/) {
 7282: 		my $username=&scan_data($scan_data,"$i.user");
 7283: 		if (defined($username) && $found{'usernames'}{$username}) {
 7284: 		    &scantron_get_correction($r,$i,$scan_record,
 7285: 					     \%scantron_config,
 7286: 					     $line,'duplicateID',$username);
 7287: 		    return(1,$currentphase);
 7288: 		} elsif (!defined($username)) {
 7289: 		    &scantron_get_correction($r,$i,$scan_record,
 7290: 					     \%scantron_config,
 7291: 					     $line,'incorrectID');
 7292: 		    return(1,$currentphase);
 7293: 		}
 7294: 		$found{'usernames'}{$username}++;
 7295: 	    } else {
 7296: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7297: 					 $line,'incorrectID');
 7298: 		return(1,$currentphase);
 7299: 	    }
 7300: 	}
 7301:     }
 7302: 
 7303:     return (0,$currentphase+1);
 7304: }
 7305: 
 7306: 
 7307: sub scantron_get_correction {
 7308:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
 7309:         $randomorder,$randompick,$respnumlookup,$startline)=@_;
 7310: #FIXME in the case of a duplicated ID the previous line, probably need
 7311: #to show both the current line and the previous one and allow skipping
 7312: #the previous one or the current one
 7313: 
 7314:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 7315:         $r->print(
 7316:             '<p class="LC_warning">'
 7317:            .&mt('An error was detected ([_1]) for PaperID [_2]',
 7318:                 "<b>$error</b>",
 7319:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
 7320:            ."</p> \n");
 7321:     } else {
 7322:         $r->print(
 7323:             '<p class="LC_warning">'
 7324:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
 7325:                 "<b>$error</b>", $i, "<pre>$line</pre>")
 7326:            ."</p> \n");
 7327:     }
 7328:     my $message =
 7329:         '<p>'
 7330:        .&mt('The ID on the form is [_1]',
 7331:             "<tt>$$scan_record{'scantron.ID'}</tt>")
 7332:        .'<br />'
 7333:        .&mt('The name on the paper is [_1], [_2]',
 7334:             $$scan_record{'scantron.LastName'},
 7335:             $$scan_record{'scantron.FirstName'})
 7336:        .'</p>';
 7337: 
 7338:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 7339:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 7340:                            # Array populated for doublebubble or
 7341:     my @lines_to_correct;  # missingbubble errors to build javascript
 7342:                            # to validate radio button checking   
 7343: 
 7344:     if ($error =~ /ID$/) {
 7345: 	if ($error eq 'incorrectID') {
 7346:             $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
 7347: 		      "</p>\n");
 7348: 	} elsif ($error eq 'duplicateID') {
 7349:             $r->print('<p class="LC_warning">'.&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 7350: 	}
 7351: 	$r->print($message);
 7352: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 7353: 	$r->print("\n<ul><li> ");
 7354: 	#FIXME it would be nice if this sent back the user ID and
 7355: 	#could do partial userID matches
 7356: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 7357: 				       'scantron_username','scantron_domain'));
 7358: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 7359: 	$r->print("\n:\n".
 7360: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 7361: 
 7362: 	$r->print('</li>');
 7363:     } elsif ($error =~ /CODE$/) {
 7364: 	if ($error eq 'incorrectCODE') {
 7365: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 7366: 	} elsif ($error eq 'duplicateCODE') {
 7367: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE has also been used by a previous paper [_1], and CODEs are supposed to be unique.",join(', ',@{$arg}))."</p>\n");
 7368: 	}
 7369: 	$r->print("<p>".&mt('The CODE on the form is [_1]',
 7370: 			    "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
 7371:                  ."</p>\n");
 7372: 	$r->print($message);
 7373: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
 7374: 	$r->print("\n<br /> ");
 7375: 	my $i=0;
 7376: 	if ($error eq 'incorrectCODE' 
 7377: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 7378: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 7379: 	    if ($closest > 0) {
 7380: 		foreach my $testcode (@{$closest}) {
 7381: 		    my $checked='';
 7382: 		    if (!$i) { $checked=' checked="checked"'; }
 7383: 		    $r->print("
 7384:    <label>
 7385:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
 7386:        ".&mt("Use the similar CODE [_1] instead.",
 7387: 	    "<b><tt>".$testcode."</tt></b>")."
 7388:     </label>
 7389:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 7390: 		    $r->print("\n<br />");
 7391: 		    $i++;
 7392: 		}
 7393: 	    }
 7394: 	}
 7395: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 7396: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
 7397: 	    $r->print("
 7398:     <label>
 7399:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
 7400:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
 7401: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 7402:     </label>");
 7403: 	    $r->print("\n<br />");
 7404: 	}
 7405: 
 7406: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
 7407: function change_radio(field) {
 7408:     var slct=document.scantronupload.scantron_CODE_resolution;
 7409:     var i;
 7410:     for (i=0;i<slct.length;i++) {
 7411:         if (slct[i].value==field) { slct[i].checked=true; }
 7412:     }
 7413: }
 7414: ENDSCRIPT
 7415: 	my $href="/adm/pickcode?".
 7416: 	   "form=".&escape("scantronupload").
 7417: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 7418: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 7419: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 7420: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 7421: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 7422: 	    $r->print("
 7423:     <label>
 7424:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 7425:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 7426: 	     "<a target='_blank' href='$href'>","</a>")."
 7427:     </label> 
 7428:     ".&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\')" />'));
 7429: 	    $r->print("\n<br />");
 7430: 	}
 7431: 	$r->print("
 7432:     <label>
 7433:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 7434:        ".&mt("Use [_1] as the CODE.",
 7435: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 7436: 	$r->print("\n<br /><br />");
 7437:     } elsif ($error eq 'doublebubble') {
 7438: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 7439: 
 7440: 	# The form field scantron_questions is acutally a list of line numbers.
 7441: 	# represented by this form so:
 7442: 
 7443: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 7444:                                                 $respnumlookup,$startline);
 7445: 
 7446: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7447: 		  $line_list.'" />');
 7448: 	$r->print($message);
 7449: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 7450: 	foreach my $question (@{$arg}) {
 7451: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7452:                                                    $scan_record, $error,
 7453:                                                    $randomorder,$randompick,
 7454:                                                    $respnumlookup,$startline);
 7455:             push(@lines_to_correct,@linenums);
 7456: 	}
 7457:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7458:     } elsif ($error eq 'missingbubble') {
 7459: 	$r->print('<p class="LC_warning">'.&mt("There have been [_1]no[_2] bubbles scanned for some question(s)",'<b>','</b>')."</p>\n");
 7460: 	$r->print($message);
 7461: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 7462: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 7463: 
 7464: 	# The form field scantron_questions is actually a list of line numbers not
 7465: 	# a list of question numbers. Therefore:
 7466: 	#
 7467: 
 7468: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 7469:                                                 $respnumlookup,$startline);
 7470: 
 7471: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7472: 		  $line_list.'" />');
 7473: 	foreach my $question (@{$arg}) {
 7474: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7475:                                                    $scan_record, $error,
 7476:                                                    $randomorder,$randompick,
 7477:                                                    $respnumlookup,$startline);
 7478:             push(@lines_to_correct,@linenums);
 7479: 	}
 7480:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7481:     } else {
 7482: 	$r->print("\n<ul>");
 7483:     }
 7484:     $r->print("\n</li></ul>");
 7485: }
 7486: 
 7487: sub verify_bubbles_checked {
 7488:     my (@ansnums) = @_;
 7489:     my $ansnumstr = join('","',@ansnums);
 7490:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 7491:     &js_escape(\$warning);
 7492:     my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
 7493: function verify_bubble_radio(form) {
 7494:     var ansnumArray = new Array ("$ansnumstr");
 7495:     var need_bubble_count = 0;
 7496:     for (var i=0; i<ansnumArray.length; i++) {
 7497:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 7498:             var bubble_picked = 0; 
 7499:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 7500:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 7501:                     bubble_picked = 1;
 7502:                 }
 7503:             }
 7504:             if (bubble_picked == 0) {
 7505:                 need_bubble_count ++;
 7506:             }
 7507:         }
 7508:     }
 7509:     if (need_bubble_count) {
 7510:         alert("$warning");
 7511:         return;
 7512:     }
 7513:     form.submit(); 
 7514: }
 7515: ENDSCRIPT
 7516:     return $output;
 7517: }
 7518: 
 7519: =pod
 7520: 
 7521: =item  questions_to_line_list
 7522: 
 7523: Converts a list of questions into a string of comma separated
 7524: line numbers in the answer sheet used by the questions.  This is
 7525: used to fill in the scantron_questions form field.
 7526: 
 7527:   Arguments:
 7528:      questions    - Reference to an array of questions.
 7529:      randomorder  - True if randomorder in use.
 7530:      randompick   - True if randompick in use.
 7531:      respnumlookup - Reference to HASH mapping question numbers in bubble lines
 7532:                      for current line to question number used for same question
 7533:                      in "Master Seqence" (as seen by Course Coordinator).
 7534:      startline    - Reference to hash where key is question number (0 is first)
 7535:                     and key is number of first bubble line for current student
 7536:                     or code-based randompick and/or randomorder.
 7537: 
 7538: =cut
 7539: 
 7540: 
 7541: sub questions_to_line_list {
 7542:     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
 7543:     my @lines;
 7544: 
 7545:     foreach my $item (@{$questions}) {
 7546:         my $question = $item;
 7547:         my ($first,$count,$last);
 7548:         if ($item =~ /^(\d+)\.(\d+)$/) {
 7549:             $question = $1;
 7550:             my $subquestion = $2;
 7551:             my $responsenum = $question-1;
 7552:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7553:                 $responsenum = $respnumlookup->{$question-1};
 7554:                 if (ref($startline) eq 'HASH') {
 7555:                     $first = $startline->{$question-1} + 1;
 7556:                 }
 7557:             } else {
 7558:                 $first = $first_bubble_line{$responsenum} + 1;
 7559:             }
 7560:             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 7561:             my $subcount = 1;
 7562:             while ($subcount<$subquestion) {
 7563:                 $first += $subans[$subcount-1];
 7564:                 $subcount ++;
 7565:             }
 7566:             $count = $subans[$subquestion-1];
 7567:         } else {
 7568:             my $responsenum = $question-1;
 7569:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7570:                 $responsenum = $respnumlookup->{$question-1};
 7571:                 if (ref($startline) eq 'HASH') {
 7572:                     $first = $startline->{$question-1} + 1;
 7573:                 }
 7574:             } else {
 7575:                 $first = $first_bubble_line{$responsenum} + 1;
 7576:             }
 7577: 	    $count   = $bubble_lines_per_response{$responsenum};
 7578:         }
 7579:         $last = $first+$count-1;
 7580:         push(@lines, ($first..$last));
 7581:     }
 7582:     return join(',', @lines);
 7583: }
 7584: 
 7585: =pod 
 7586: 
 7587: =item prompt_for_corrections
 7588: 
 7589: Prompts for a potentially multiline correction to the
 7590: user's bubbling (factors out common code from scantron_get_correction
 7591: for multi and missing bubble cases).
 7592: 
 7593:  Arguments:
 7594:    $r           - Apache request object.
 7595:    $question    - The question number to prompt for.
 7596:    $scan_config - The scantron file configuration hash.
 7597:    $scan_record - Reference to the hash that has the the parsed scanlines.
 7598:    $error       - Type of error
 7599:    $randomorder - True if randomorder in use.
 7600:    $randompick  - True if randompick in use.
 7601:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
 7602:                     for current line to question number used for same question
 7603:                     in "Master Seqence" (as seen by Course Coordinator).
 7604:    $startline   - Reference to hash where key is question number (0 is first)
 7605:                   and value is number of first bubble line for current student
 7606:                   or code-based randompick and/or randomorder.
 7607: 
 7608: 
 7609:  Implicit inputs:
 7610:    %bubble_lines_per_response   - Starting line numbers for each question.
 7611:                                   Numbered from 0 (but question numbers are from
 7612:                                   1.
 7613:    %first_bubble_line           - Starting bubble line for each question.
 7614:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 7615:                                   type problems render as separate sub-questions, 
 7616:                                   in exam mode. This hash contains a 
 7617:                                   comma-separated list of the lines per 
 7618:                                   sub-question.
 7619:    %responsetype_per_response   - essayresponse, formularesponse,
 7620:                                   stringresponse, imageresponse, reactionresponse,
 7621:                                   and organicresponse type problem parts can have
 7622:                                   multiple lines per response if the weight
 7623:                                   assigned exceeds 10.  In this case, only
 7624:                                   one bubble per line is permitted, but more 
 7625:                                   than one line might contain bubbles, e.g.
 7626:                                   bubbling of: line 1 - J, line 2 - J, 
 7627:                                   line 3 - B would assign 22 points.  
 7628: 
 7629: =cut
 7630: 
 7631: sub prompt_for_corrections {
 7632:     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
 7633:         $randompick, $respnumlookup, $startline) = @_;
 7634:     my ($current_line,$lines);
 7635:     my @linenums;
 7636:     my $questionnum = $question;
 7637:     my ($first,$responsenum);
 7638:     if ($question =~ /^(\d+)\.(\d+)$/) {
 7639:         $question = $1;
 7640:         my $subquestion = $2;
 7641:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7642:             $responsenum = $respnumlookup->{$question-1};
 7643:             if (ref($startline) eq 'HASH') {
 7644:                 $first = $startline->{$question-1};
 7645:             }
 7646:         } else {
 7647:             $responsenum = $question-1;
 7648:             $first = $first_bubble_line{$responsenum};
 7649:         }
 7650:         $current_line = $first + 1 ;
 7651:         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 7652:         my $subcount = 1;
 7653:         while ($subcount<$subquestion) {
 7654:             $current_line += $subans[$subcount-1];
 7655:             $subcount ++;
 7656:         }
 7657:         $lines = $subans[$subquestion-1];
 7658:     } else {
 7659:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7660:             $responsenum = $respnumlookup->{$question-1};
 7661:             if (ref($startline) eq 'HASH') { 
 7662:                 $first = $startline->{$question-1};
 7663:             }
 7664:         } else {
 7665:             $responsenum = $question-1;
 7666:             $first = $first_bubble_line{$responsenum};
 7667:         }
 7668:         $current_line = $first + 1;
 7669:         $lines        = $bubble_lines_per_response{$responsenum};
 7670:     }
 7671:     if ($lines > 1) {
 7672:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 7673:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 7674:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 7675:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 7676:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 7677:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 7678:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 7679:             $r->print(
 7680:                 &mt("Although this particular question type requires handgrading, the instructions for this question in the bubblesheet exam directed students to leave [quant,_1,line] blank on their bubblesheets.",$lines)
 7681:                .'<br /><br />'
 7682:                .&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.')
 7683:                .'<br />'
 7684:                .&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.')
 7685:                .'<br />'
 7686:                .&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.")
 7687:                .'<br /><br />'
 7688:             );
 7689:         } else {
 7690:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 7691:         }
 7692:     }
 7693:     for (my $i =0; $i < $lines; $i++) {
 7694:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 7695: 	&scantron_bubble_selector($r,$scan_config,$current_line,
 7696: 	        		  $questionnum,$error,split('', $selected));
 7697:         push(@linenums,$current_line);
 7698: 	$current_line++;
 7699:     }
 7700:     if ($lines > 1) {
 7701: 	$r->print("<hr /><br />");
 7702:     }
 7703:     return @linenums;
 7704: }
 7705: 
 7706: =pod
 7707: 
 7708: =item scantron_bubble_selector
 7709:   
 7710:    Generates the html radiobuttons to correct a single bubble line
 7711:    possibly showing the existing the selected bubbles if known
 7712: 
 7713:  Arguments:
 7714:     $r           - Apache request object
 7715:     $scan_config - hash from &get_scantron_config()
 7716:     $line        - Number of the line being displayed.
 7717:     $questionnum - Question number (may include subquestion)
 7718:     $error       - Type of error.
 7719:     @selected    - Array of bubbles picked on this line.
 7720: 
 7721: =cut
 7722: 
 7723: sub scantron_bubble_selector {
 7724:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 7725:     my $max=$$scan_config{'Qlength'};
 7726: 
 7727:     my $scmode=$$scan_config{'Qon'};
 7728:     if ($scmode eq 'number' || $scmode eq 'letter') { 
 7729:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
 7730:             ($$scan_config{'BubblesPerRow'} > 0)) {
 7731:             $max=$$scan_config{'BubblesPerRow'};
 7732:             if (($scmode eq 'number') && ($max > 10)) {
 7733:                 $max = 10;
 7734:             } elsif (($scmode eq 'letter') && $max > 26) {
 7735:                 $max = 26;
 7736:             }
 7737:         } else {
 7738:             $max = 10;
 7739:         }
 7740:     }
 7741: 
 7742:     my @alphabet=('A'..'Z');
 7743:     $r->print(&Apache::loncommon::start_data_table().
 7744:               &Apache::loncommon::start_data_table_row());
 7745:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 7746:     for (my $i=0;$i<$max+1;$i++) {
 7747: 	$r->print("\n".'<td align="center">');
 7748: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 7749: 	else { $r->print('&nbsp;'); }
 7750: 	$r->print('</td>');
 7751:     }
 7752:     $r->print(&Apache::loncommon::end_data_table_row().
 7753:               &Apache::loncommon::start_data_table_row());
 7754:     for (my $i=0;$i<$max;$i++) {
 7755: 	$r->print("\n".
 7756: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 7757: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 7758:     }
 7759:     my $nobub_checked = ' ';
 7760:     if ($error eq 'missingbubble') {
 7761:         $nobub_checked = ' checked = "checked" ';
 7762:     }
 7763:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 7764: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 7765:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 7766:               $line.'" value="'.$questionnum.'" /></td>');
 7767:     $r->print(&Apache::loncommon::end_data_table_row().
 7768:               &Apache::loncommon::end_data_table());
 7769: }
 7770: 
 7771: =pod
 7772: 
 7773: =item num_matches
 7774: 
 7775:    Counts the number of characters that are the same between the two arguments.
 7776: 
 7777:  Arguments:
 7778:    $orig - CODE from the scanline
 7779:    $code - CODE to match against
 7780: 
 7781:  Returns:
 7782:    $count - integer count of the number of same characters between the
 7783:             two arguments
 7784: 
 7785: =cut
 7786: 
 7787: sub num_matches {
 7788:     my ($orig,$code) = @_;
 7789:     my @code=split(//,$code);
 7790:     my @orig=split(//,$orig);
 7791:     my $same=0;
 7792:     for (my $i=0;$i<scalar(@code);$i++) {
 7793: 	if ($code[$i] eq $orig[$i]) { $same++; }
 7794:     }
 7795:     return $same;
 7796: }
 7797: 
 7798: =pod
 7799: 
 7800: =item scantron_get_closely_matching_CODEs
 7801: 
 7802:    Cycles through all CODEs and finds the set that has the greatest
 7803:    number of same characters as the provided CODE
 7804: 
 7805:  Arguments:
 7806:    $allcodes - hash ref returned by &get_codes()
 7807:    $CODE     - CODE from the current scanline
 7808: 
 7809:  Returns:
 7810:    2 element list
 7811:     - first elements is number of how closely matching the best fit is 
 7812:       (5 means best set has 5 matching characters)
 7813:     - second element is an arrary ref containing the set of valid CODEs
 7814:       that best fit the passed in CODE
 7815: 
 7816: =cut
 7817: 
 7818: sub scantron_get_closely_matching_CODEs {
 7819:     my ($allcodes,$CODE)=@_;
 7820:     my @CODEs;
 7821:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 7822: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 7823:     }
 7824: 
 7825:     return ($#CODEs,$CODEs[-1]);
 7826: }
 7827: 
 7828: =pod
 7829: 
 7830: =item get_codes
 7831: 
 7832:    Builds a hash which has keys of all of the valid CODEs from the selected
 7833:    set of remembered CODEs.
 7834: 
 7835:  Arguments:
 7836:   $old_name - name of the set of remembered CODEs
 7837:   $cdom     - domain of the course
 7838:   $cnum     - internal course name
 7839: 
 7840:  Returns:
 7841:   %allcodes - keys are the valid CODEs, values are all 1
 7842: 
 7843: =cut
 7844: 
 7845: sub get_codes {
 7846:     my ($old_name, $cdom, $cnum) = @_;
 7847:     if (!$old_name) {
 7848: 	$old_name=$env{'form.scantron_CODElist'};
 7849:     }
 7850:     if (!$cdom) {
 7851: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 7852:     }
 7853:     if (!$cnum) {
 7854: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 7855:     }
 7856:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 7857: 				    $cdom,$cnum);
 7858:     my %allcodes;
 7859:     if ($result{"type\0$old_name"} eq 'number') {
 7860: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 7861:     } else {
 7862: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 7863:     }
 7864:     return %allcodes;
 7865: }
 7866: 
 7867: =pod
 7868: 
 7869: =item scantron_validate_CODE
 7870: 
 7871:    Validates all scanlines in the selected file to not have any
 7872:    invalid or underspecified CODEs and that none of the codes are
 7873:    duplicated if this was requested.
 7874: 
 7875: =cut
 7876: 
 7877: sub scantron_validate_CODE {
 7878:     my ($r,$currentphase) = @_;
 7879:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7880:     if ($scantron_config{'CODElocation'} &&
 7881: 	$scantron_config{'CODEstart'} &&
 7882: 	$scantron_config{'CODElength'}) {
 7883: 	if (!defined($env{'form.scantron_CODElist'})) {
 7884: 	    &FIXME_blow_up()
 7885: 	}
 7886:     } else {
 7887: 	return (0,$currentphase+1);
 7888:     }
 7889:     
 7890:     my %usedCODEs;
 7891: 
 7892:     my %allcodes=&get_codes();
 7893: 
 7894:     my $nav_error;
 7895:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
 7896:     if ($nav_error) {
 7897:         $r->print(&navmap_errormsg());
 7898:         return(1,$currentphase);
 7899:     }
 7900: 
 7901:     my ($scanlines,$scan_data)=&scantron_getfile();
 7902:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7903: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7904: 	if ($line=~/^[\s\cz]*$/) { next; }
 7905: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7906: 						 $scan_data);
 7907: 	my $CODE=$$scan_record{'scantron.CODE'};
 7908: 	my $error=0;
 7909: 	if (!&Apache::lonnet::validCODE($CODE)) {
 7910: 	    &scantron_get_correction($r,$i,$scan_record,
 7911: 				     \%scantron_config,
 7912: 				     $line,'incorrectCODE',\%allcodes);
 7913: 	    return(1,$currentphase);
 7914: 	}
 7915: 	if (%allcodes && !exists($allcodes{$CODE}) 
 7916: 	    && !$$scan_record{'scantron.useCODE'}) {
 7917: 	    &scantron_get_correction($r,$i,$scan_record,
 7918: 				     \%scantron_config,
 7919: 				     $line,'incorrectCODE',\%allcodes);
 7920: 	    return(1,$currentphase);
 7921: 	}
 7922: 	if (exists($usedCODEs{$CODE}) 
 7923: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 7924: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 7925: 	    &scantron_get_correction($r,$i,$scan_record,
 7926: 				     \%scantron_config,
 7927: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 7928: 	    return(1,$currentphase);
 7929: 	}
 7930: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 7931:     }
 7932:     return (0,$currentphase+1);
 7933: }
 7934: 
 7935: =pod
 7936: 
 7937: =item scantron_validate_doublebubble
 7938: 
 7939:    Validates all scanlines in the selected file to not have any
 7940:    bubble lines with multiple bubbles marked.
 7941: 
 7942: =cut
 7943: 
 7944: sub scantron_validate_doublebubble {
 7945:     my ($r,$currentphase) = @_;
 7946:     #get student info
 7947:     my $classlist=&Apache::loncoursedata::get_classlist();
 7948:     my %idmap=&username_to_idmap($classlist);
 7949:     my (undef,undef,$sequence)=
 7950:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 7951: 
 7952:     #get scantron line setup
 7953:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7954:     my ($scanlines,$scan_data)=&scantron_getfile();
 7955: 
 7956:     my $navmap = Apache::lonnavmaps::navmap->new();
 7957:     unless (ref($navmap)) {
 7958:         $r->print(&navmap_errormsg());
 7959:         return(1,$currentphase);
 7960:     }
 7961:     my $map=$navmap->getResourceByUrl($sequence);
 7962:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7963:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 7964:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 7965:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 7966: 
 7967:     my $nav_error;
 7968:     if (ref($map)) {
 7969:         $randomorder = $map->randomorder();
 7970:         $randompick = $map->randompick();
 7971:         if ($randomorder || $randompick) {
 7972:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 7973:             if ($nav_error) {
 7974:                 $r->print(&navmap_errormsg());
 7975:                 return(1,$currentphase);
 7976:             }
 7977:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 7978:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 7979:         }
 7980:     } else {
 7981:         $r->print(&navmap_errormsg());
 7982:         return(1,$currentphase);
 7983:     }
 7984: 
 7985:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
 7986:     if ($nav_error) {
 7987:         $r->print(&navmap_errormsg());
 7988:         return(1,$currentphase);
 7989:     }
 7990: 
 7991:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7992: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7993: 	if ($line=~/^[\s\cz]*$/) { next; }
 7994: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7995: 						 $scan_data,undef,\%idmap,$randomorder,
 7996:                                                  $randompick,$sequence,\@master_seq,
 7997:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 7998:                                                  \%orderedforcode,\%respnumlookup,\%startline);
 7999: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 8000: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 8001: 				 'doublebubble',
 8002: 				 $$scan_record{'scantron.doubleerror'},
 8003:                                  $randomorder,$randompick,\%respnumlookup,\%startline);
 8004:     	return (1,$currentphase);
 8005:     }
 8006:     return (0,$currentphase+1);
 8007: }
 8008: 
 8009: 
 8010: sub scantron_get_maxbubble {
 8011:     my ($nav_error,$scantron_config) = @_;
 8012:     if (defined($env{'form.scantron_maxbubble'}) &&
 8013: 	$env{'form.scantron_maxbubble'}) {
 8014: 	&restore_bubble_lines();
 8015: 	return $env{'form.scantron_maxbubble'};
 8016:     }
 8017: 
 8018:     my (undef, undef, $sequence) =
 8019: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8020: 
 8021:     my $navmap=Apache::lonnavmaps::navmap->new();
 8022:     unless (ref($navmap)) {
 8023:         if (ref($nav_error)) {
 8024:             $$nav_error = 1;
 8025:         }
 8026:         return;
 8027:     }
 8028:     my $map=$navmap->getResourceByUrl($sequence);
 8029:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8030:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
 8031: 
 8032:     &Apache::lonxml::clear_problem_counter();
 8033: 
 8034:     my $uname       = $env{'user.name'};
 8035:     my $udom        = $env{'user.domain'};
 8036:     my $cid         = $env{'request.course.id'};
 8037:     my $total_lines = 0;
 8038:     %bubble_lines_per_response = ();
 8039:     %first_bubble_line         = ();
 8040:     %subdivided_bubble_lines   = ();
 8041:     %responsetype_per_response = ();
 8042:     %masterseq_id_responsenum  = ();
 8043: 
 8044:     my $response_number = 0;
 8045:     my $bubble_line     = 0;
 8046:     foreach my $resource (@resources) {
 8047:         my $resid = $resource->id(); 
 8048:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
 8049:                                                           $udom,undef,$bubbles_per_row);
 8050:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 8051: 	    foreach my $part_id (@{$parts}) {
 8052:                 my $lines;
 8053: 
 8054: 	        # TODO - make this a persistent hash not an array.
 8055: 
 8056:                 # optionresponse, matchresponse and rankresponse type items 
 8057:                 # render as separate sub-questions in exam mode.
 8058:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 8059:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 8060:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 8061:                     my ($numbub,$numshown);
 8062:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 8063:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 8064:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 8065:                         }
 8066:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 8067:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 8068:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 8069:                         }
 8070:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 8071:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 8072:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 8073:                         }
 8074:                     }
 8075:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 8076:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 8077:                     }
 8078:                     my $bubbles_per_row =
 8079:                         &bubblesheet_bubbles_per_row($scantron_config);
 8080:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
 8081:                     if (($numbub % $bubbles_per_row) != 0) {
 8082:                         $inner_bubble_lines++;
 8083:                     }
 8084:                     for (my $i=0; $i<$numshown; $i++) {
 8085:                         $subdivided_bubble_lines{$response_number} .= 
 8086:                             $inner_bubble_lines.',';
 8087:                     }
 8088:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 8089:                     $lines = $numshown * $inner_bubble_lines;
 8090:                 } else {
 8091:                     $lines = $analysis->{"$part_id.bubble_lines"};
 8092:                 }
 8093: 
 8094:                 $first_bubble_line{$response_number} = $bubble_line;
 8095: 	        $bubble_lines_per_response{$response_number} = $lines;
 8096:                 $responsetype_per_response{$response_number} = 
 8097:                     $analysis->{$part_id.'.type'};
 8098:                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;  
 8099: 	        $response_number++;
 8100: 
 8101: 	        $bubble_line +=  $lines;
 8102: 	        $total_lines +=  $lines;
 8103: 	    }
 8104:         }
 8105:     }
 8106:     &Apache::lonnet::delenv('scantron.');
 8107: 
 8108:     &save_bubble_lines();
 8109:     $env{'form.scantron_maxbubble'} =
 8110: 	$total_lines;
 8111:     return $env{'form.scantron_maxbubble'};
 8112: }
 8113: 
 8114: sub bubblesheet_bubbles_per_row {
 8115:     my ($scantron_config) = @_;
 8116:     my $bubbles_per_row;
 8117:     if (ref($scantron_config) eq 'HASH') {
 8118:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
 8119:     }
 8120:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
 8121:         $bubbles_per_row = 10;
 8122:     }
 8123:     return $bubbles_per_row;
 8124: }
 8125: 
 8126: sub scantron_validate_missingbubbles {
 8127:     my ($r,$currentphase) = @_;
 8128:     #get student info
 8129:     my $classlist=&Apache::loncoursedata::get_classlist();
 8130:     my %idmap=&username_to_idmap($classlist);
 8131:     my (undef,undef,$sequence)=
 8132:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8133: 
 8134:     #get scantron line setup
 8135:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8136:     my ($scanlines,$scan_data)=&scantron_getfile();
 8137: 
 8138:     my $navmap = Apache::lonnavmaps::navmap->new();
 8139:     unless (ref($navmap)) {
 8140:         $r->print(&navmap_errormsg());
 8141:         return(1,$currentphase);
 8142:     }
 8143: 
 8144:     my $map=$navmap->getResourceByUrl($sequence);
 8145:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8146:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8147:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 8148:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8149: 
 8150:     my $nav_error;
 8151:     if (ref($map)) {
 8152:         $randomorder = $map->randomorder();
 8153:         $randompick = $map->randompick();
 8154:         if ($randomorder || $randompick) {
 8155:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8156:             if ($nav_error) {
 8157:                 $r->print(&navmap_errormsg());
 8158:                 return(1,$currentphase);
 8159:             }
 8160:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8161:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 8162:         }
 8163:     } else {
 8164:         $r->print(&navmap_errormsg());
 8165:         return(1,$currentphase);
 8166:     }
 8167: 
 8168: 
 8169:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 8170:     if ($nav_error) {
 8171:         $r->print(&navmap_errormsg());
 8172:         return(1,$currentphase);
 8173:     }
 8174: 
 8175:     if (!$max_bubble) { $max_bubble=2**31; }
 8176:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8177: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8178: 	if ($line=~/^[\s\cz]*$/) { next; }
 8179: 	my $scan_record =
 8180:             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
 8181: 				     $randomorder,$randompick,$sequence,\@master_seq,
 8182:                                      \%symb_to_resource,\%grader_partids_by_symb,
 8183:                                      \%orderedforcode,\%respnumlookup,\%startline);
 8184: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 8185: 	my @to_correct;
 8186: 	
 8187: 	# Probably here's where the error is...
 8188: 
 8189: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 8190:             my $lastbubble;
 8191:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 8192:                my $question = $1;
 8193:                my $subquestion = $2;
 8194:                my ($first,$responsenum);
 8195:                if ($randomorder || $randompick) {
 8196:                    $responsenum = $respnumlookup{$question-1};
 8197:                    $first = $startline{$question-1};
 8198:                } else {
 8199:                    $responsenum = $question-1; 
 8200:                    $first = $first_bubble_line{$responsenum};
 8201:                }
 8202:                if (!defined($first)) { next; }
 8203:                my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8204:                my $subcount = 1;
 8205:                while ($subcount<$subquestion) {
 8206:                    $first += $subans[$subcount-1];
 8207:                    $subcount ++;
 8208:                }
 8209:                my $count = $subans[$subquestion-1];
 8210:                $lastbubble = $first + $count;
 8211:             } else {
 8212:                my ($first,$responsenum);
 8213:                if ($randomorder || $randompick) {
 8214:                    $responsenum = $respnumlookup{$missing-1};
 8215:                    $first = $startline{$missing-1};
 8216:                } else {
 8217:                    $responsenum = $missing-1;
 8218:                    $first = $first_bubble_line{$responsenum};
 8219:                }
 8220:                if (!defined($first)) { next; }
 8221:                $lastbubble = $first + $bubble_lines_per_response{$responsenum};
 8222:             }
 8223:             if ($lastbubble > $max_bubble) { next; }
 8224: 	    push(@to_correct,$missing);
 8225: 	}
 8226: 	if (@to_correct) {
 8227: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 8228: 				     $line,'missingbubble',\@to_correct,
 8229:                                      $randomorder,$randompick,\%respnumlookup,
 8230:                                      \%startline);
 8231: 	    return (1,$currentphase);
 8232: 	}
 8233: 
 8234:     }
 8235:     return (0,$currentphase+1);
 8236: }
 8237: 
 8238: sub hand_bubble_option {
 8239:     my (undef, undef, $sequence) =
 8240:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8241:     return if ($sequence eq '');
 8242:     my $navmap = Apache::lonnavmaps::navmap->new();
 8243:     unless (ref($navmap)) {
 8244:         return;
 8245:     }
 8246:     my $needs_hand_bubbles;
 8247:     my $map=$navmap->getResourceByUrl($sequence);
 8248:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8249:     foreach my $res (@resources) {
 8250:         if (ref($res)) {
 8251:             if ($res->is_problem()) {
 8252:                 my $partlist = $res->parts();
 8253:                 foreach my $part (@{ $partlist }) {
 8254:                     my @types = $res->responseType($part);
 8255:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
 8256:                         $needs_hand_bubbles = 1;
 8257:                         last;
 8258:                     }
 8259:                 }
 8260:             }
 8261:         }
 8262:     }
 8263:     if ($needs_hand_bubbles) {
 8264:         my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8265:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8266:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
 8267:                &mt('If you have already graded these by bubbling sheets to indicate points awarded, [_1]what point value is assigned to a filled last bubble in each row?','<br />').
 8268:                '<label><input type="radio" name="scantron_lastbubblepoints" value="'.$bubbles_per_row.'" checked="checked" />'.&mt('[quant,_1,point]',$bubbles_per_row).'</label>&nbsp;'.&mt('or').'&nbsp;'.
 8269:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
 8270:     }
 8271:     return;
 8272: }
 8273: 
 8274: sub scantron_process_students {
 8275:     my ($r,$symb) = @_;
 8276: 
 8277:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8278:     if (!$symb) {
 8279: 	return '';
 8280:     }
 8281:     my $default_form_data=&defaultFormData($symb);
 8282: 
 8283:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8284:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config); 
 8285:     my ($scanlines,$scan_data)=&scantron_getfile();
 8286:     my $classlist=&Apache::loncoursedata::get_classlist();
 8287:     my %idmap=&username_to_idmap($classlist);
 8288:     my $navmap=Apache::lonnavmaps::navmap->new();
 8289:     unless (ref($navmap)) {
 8290:         $r->print(&navmap_errormsg());
 8291:         return '';
 8292:     }
 8293:     my $map=$navmap->getResourceByUrl($sequence);
 8294:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8295:         %grader_randomlists_by_symb);
 8296:     if (ref($map)) {
 8297:         $randomorder = $map->randomorder();
 8298:         $randompick = $map->randompick();
 8299:     } else {
 8300:         $r->print(&navmap_errormsg());
 8301:         return '';
 8302:     }
 8303:     my $nav_error;
 8304:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8305:     if ($randomorder || $randompick) {
 8306:         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8307:         if ($nav_error) {
 8308:             $r->print(&navmap_errormsg());
 8309:             return '';
 8310:         }
 8311:     }
 8312:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8313:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 8314: 
 8315:     my ($uname,$udom);
 8316:     my $result= <<SCANTRONFORM;
 8317: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 8318:   <input type="hidden" name="command" value="scantron_configphase" />
 8319:   $default_form_data
 8320: SCANTRONFORM
 8321:     $r->print($result);
 8322: 
 8323:     my @delayqueue;
 8324:     my (%completedstudents,%scandata);
 8325:     
 8326:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 8327:     my $count=&get_todo_count($scanlines,$scan_data);
 8328:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 8329:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
 8330:     $r->print('<br />');
 8331:     my $start=&Time::HiRes::time();
 8332:     my $i=-1;
 8333:     my $started;
 8334: 
 8335:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 8336:     if ($nav_error) {
 8337:         $r->print(&navmap_errormsg());
 8338:         return '';
 8339:     }
 8340: 
 8341:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 8342:     # the user and return.
 8343: 
 8344:     if ($ssi_error) {
 8345: 	$r->print("</form>");
 8346: 	&ssi_print_error($r);
 8347:         &Apache::lonnet::remove_lock($lock);
 8348: 	return '';		# Dunno why the other returns return '' rather than just returning.
 8349:     }
 8350: 
 8351:     my %lettdig = &letter_to_digits();
 8352:     my $numletts = scalar(keys(%lettdig));
 8353:     my %orderedforcode;
 8354: 
 8355:     while ($i<$scanlines->{'count'}) {
 8356:  	($uname,$udom)=('','');
 8357:  	$i++;
 8358:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8359:  	if ($line=~/^[\s\cz]*$/) { next; }
 8360: 	if ($started) {
 8361: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
 8362: 	}
 8363: 	$started=1;
 8364:         my %respnumlookup = ();
 8365:         my %startline = ();
 8366:         my $total;
 8367:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8368:                                                  $scan_data,undef,\%idmap,$randomorder,
 8369:                                                  $randompick,$sequence,\@master_seq,
 8370:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 8371:                                                  \%orderedforcode,\%respnumlookup,\%startline,
 8372:                                                  \$total);
 8373:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 8374:  					      \%idmap,$i)) {
 8375:   	    &scantron_add_delay(\@delayqueue,$line,
 8376:  				'Unable to find a student that matches',1);
 8377:  	    next;
 8378:   	}
 8379:  	if (exists $completedstudents{$uname}) {
 8380:  	    &scantron_add_delay(\@delayqueue,$line,
 8381:  				'Student '.$uname.' has multiple sheets',2);
 8382:  	    next;
 8383:  	}
 8384:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 8385:         my $user = $uname.':'.$usec;
 8386:   	($uname,$udom)=split(/:/,$uname);
 8387: 
 8388:         my $scancode;
 8389:         if ((exists($scan_record->{'scantron.CODE'})) &&
 8390:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 8391:             $scancode = $scan_record->{'scantron.CODE'};
 8392:         } else {
 8393:             $scancode = '';
 8394:         }
 8395: 
 8396:         my @mapresources = @resources;
 8397:         if ($randomorder || $randompick) {
 8398:             @mapresources = 
 8399:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
 8400:                              \%orderedforcode);
 8401:         }
 8402:         my (%partids_by_symb,$res_error);
 8403:         foreach my $resource (@mapresources) {
 8404:             my $ressymb;
 8405:             if (ref($resource)) {
 8406:                 $ressymb = $resource->symb();
 8407:             } else {
 8408:                 $res_error = 1;
 8409:                 last;
 8410:             }
 8411:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 8412:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 8413:                 my ($analysis,$parts) =
 8414:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 8415:                                               $uname,$udom,undef,$bubbles_per_row);
 8416:                 $partids_by_symb{$ressymb} = $parts;
 8417:             } else {
 8418:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
 8419:             }
 8420:         }
 8421: 
 8422:         if ($res_error) {
 8423:             &scantron_add_delay(\@delayqueue,$line,
 8424:                                 'An error occurred while grading student '.$uname,2);
 8425:             next;
 8426:         }
 8427: 
 8428: 	&Apache::lonxml::clear_problem_counter();
 8429:   	&Apache::lonnet::appenv($scan_record);
 8430: 
 8431: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 8432: 	    &scantron_putfile($scanlines,$scan_data);
 8433: 	}
 8434: 	
 8435:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 8436:                                    \@mapresources,\%partids_by_symb,
 8437:                                    $bubbles_per_row,$randomorder,$randompick,
 8438:                                    \%respnumlookup,\%startline) 
 8439:             eq 'ssi_error') {
 8440:             $ssi_error = 0; # So end of handler error message does not trigger.
 8441:             $r->print("</form>");
 8442:             &ssi_print_error($r);
 8443:             &Apache::lonnet::remove_lock($lock);
 8444:             return '';      # Why return ''?  Beats me.
 8445:         }
 8446: 
 8447:         if (($scancode) && ($randomorder || $randompick)) {
 8448:             my $parmresult =
 8449:                 &Apache::lonparmset::storeparm_by_symb($symb,
 8450:                                                        '0_examcode',2,$scancode,
 8451:                                                        'string_examcode',$uname,
 8452:                                                        $udom);
 8453:         }
 8454: 	$completedstudents{$uname}={'line'=>$line};
 8455:         if ($env{'form.verifyrecord'}) {
 8456:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 8457:             if ($randompick) {
 8458:                 if ($total) {
 8459:                     $lastpos = $total*$scantron_config{'Qlength'};
 8460:                 }
 8461:             }
 8462: 
 8463:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 8464:             chomp($studentdata);
 8465:             $studentdata =~ s/\r$//;
 8466:             my $studentrecord = '';
 8467:             my $counter = -1;
 8468:             foreach my $resource (@mapresources) {
 8469:                 my $ressymb = $resource->symb();
 8470:                 ($counter,my $recording) =
 8471:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 8472:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
 8473:                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
 8474:                                              $randompick,\%respnumlookup,\%startline);
 8475:                 $studentrecord .= $recording;
 8476:             }
 8477:             if ($studentrecord ne $studentdata) {
 8478:                 &Apache::lonxml::clear_problem_counter();
 8479:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 8480:                                            \@mapresources,\%partids_by_symb,
 8481:                                            $bubbles_per_row,$randomorder,$randompick,
 8482:                                            \%respnumlookup,\%startline) 
 8483:                     eq 'ssi_error') {
 8484:                     $ssi_error = 0; # So end of handler error message does not trigger.
 8485:                     $r->print("</form>");
 8486:                     &ssi_print_error($r);
 8487:                     &Apache::lonnet::remove_lock($lock);
 8488:                     delete($completedstudents{$uname});
 8489:                     return '';
 8490:                 }
 8491:                 $counter = -1;
 8492:                 $studentrecord = '';
 8493:                 foreach my $resource (@mapresources) {
 8494:                     my $ressymb = $resource->symb();
 8495:                     ($counter,my $recording) =
 8496:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 8497:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 8498:                                                  \%scantron_config,\%lettdig,$numletts,
 8499:                                                  $randomorder,$randompick,\%respnumlookup,
 8500:                                                  \%startline);
 8501:                     $studentrecord .= $recording;
 8502:                 }
 8503:                 if ($studentrecord ne $studentdata) {
 8504:                     $r->print('<p><span class="LC_warning">');
 8505:                     if ($scancode eq '') {
 8506:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
 8507:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 8508:                     } else {
 8509:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
 8510:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 8511:                     }
 8512:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 8513:                               &Apache::loncommon::start_data_table_header_row()."\n".
 8514:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 8515:                               &Apache::loncommon::end_data_table_header_row()."\n".
 8516:                               &Apache::loncommon::start_data_table_row().
 8517:                               '<td>'.&mt('Bubblesheet').'</td>'.
 8518:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
 8519:                               &Apache::loncommon::end_data_table_row().
 8520:                               &Apache::loncommon::start_data_table_row().
 8521:                               '<td>'.&mt('Stored submissions').'</td>'.
 8522:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
 8523:                               &Apache::loncommon::end_data_table_row().
 8524:                               &Apache::loncommon::end_data_table().'</p>');
 8525:                 } else {
 8526:                     $r->print('<br /><span class="LC_warning">'.
 8527:                              &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 />'.
 8528:                              &mt("As a consequence, this user's submission history records two tries.").
 8529:                                  '</span><br />');
 8530:                 }
 8531:             }
 8532:         }
 8533:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 8534:     } continue {
 8535: 	&Apache::lonxml::clear_problem_counter();
 8536: 	&Apache::lonnet::delenv('scantron.');
 8537:     }
 8538:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 8539:     &Apache::lonnet::remove_lock($lock);
 8540: #    my $lasttime = &Time::HiRes::time()-$start;
 8541: #    $r->print("<p>took $lasttime</p>");
 8542: 
 8543:     $r->print("</form>");
 8544:     return '';
 8545: }
 8546: 
 8547: sub graders_resources_pass {
 8548:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
 8549:         $bubbles_per_row) = @_;
 8550:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
 8551:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
 8552:         foreach my $resource (@{$resources}) {
 8553:             my $ressymb = $resource->symb();
 8554:             my ($analysis,$parts) =
 8555:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
 8556:                                           $env{'user.name'},$env{'user.domain'},
 8557:                                           1,$bubbles_per_row);
 8558:             $grader_partids_by_symb->{$ressymb} = $parts;
 8559:             if (ref($analysis) eq 'HASH') {
 8560:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 8561:                     $grader_randomlists_by_symb->{$ressymb} =
 8562:                         $analysis->{'parts_withrandomlist'};
 8563:                 }
 8564:             }
 8565:         }
 8566:     }
 8567:     return;
 8568: }
 8569: 
 8570: =pod
 8571: 
 8572: =item users_order
 8573: 
 8574:   Returns array of resources in current map, ordered based on either CODE,
 8575:   if this is a CODEd exam, or based on student's identity if this is a 
 8576:   "NAMEd" exam.
 8577: 
 8578:   Should be used when randomorder and/or randompick applied when the 
 8579:   corresponding exam was printed, prior to students completing bubblesheets 
 8580:   for the version of the exam the student received.
 8581: 
 8582: =cut
 8583: 
 8584: sub users_order  {
 8585:     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
 8586:     my @mapresources;
 8587:     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
 8588:         return @mapresources;
 8589:     }
 8590:     if ($scancode) {
 8591:         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
 8592:             @mapresources = @{$orderedforcode->{$scancode}};
 8593:         } else {
 8594:             $env{'form.CODE'} = $scancode;
 8595:             my $actual_seq =
 8596:                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 8597:                                                                $master_seq,
 8598:                                                                $user,$scancode,1);
 8599:             if (ref($actual_seq) eq 'ARRAY') {
 8600:                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
 8601:                 if (ref($orderedforcode) eq 'HASH') {
 8602:                     if (@mapresources > 0) { 
 8603:                         $orderedforcode->{$scancode} = \@mapresources;
 8604:                     }
 8605:                 }
 8606:             }
 8607:             delete($env{'form.CODE'});
 8608:         }
 8609:     } else {
 8610:         my $actual_seq =
 8611:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 8612:                                                            $master_seq,
 8613:                                                            $user,undef,1);
 8614:         if (ref($actual_seq) eq 'ARRAY') {
 8615:             @mapresources = 
 8616:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
 8617:         }
 8618:     }
 8619:     return @mapresources;
 8620: }
 8621: 
 8622: sub grade_student_bubbles {
 8623:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
 8624:         $randomorder,$randompick,$respnumlookup,$startline) = @_;
 8625:     my $uselookup = 0;
 8626:     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
 8627:         (ref($startline) eq 'HASH')) {
 8628:         $uselookup = 1;
 8629:     }
 8630: 
 8631:     if (ref($resources) eq 'ARRAY') {
 8632:         my $count = 0;
 8633:         foreach my $resource (@{$resources}) {
 8634:             my $ressymb = $resource->symb();
 8635:             my %form = ('submitted'      => 'scantron',
 8636:                         'grade_target'   => 'grade',
 8637:                         'grade_username' => $uname,
 8638:                         'grade_domain'   => $udom,
 8639:                         'grade_courseid' => $env{'request.course.id'},
 8640:                         'grade_symb'     => $ressymb,
 8641:                         'CODE'           => $scancode
 8642:                        );
 8643:             if ($bubbles_per_row ne '') {
 8644:                 $form{'bubbles_per_row'} = $bubbles_per_row;
 8645:             }
 8646:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
 8647:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
 8648:             }
 8649:             if (ref($parts) eq 'HASH') {
 8650:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 8651:                     foreach my $part (@{$parts->{$ressymb}}) {
 8652:                         if ($uselookup) {
 8653:                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
 8654:                         } else {
 8655:                             $form{'scantron_questnum_start.'.$part} =
 8656:                                 1+$env{'form.scantron.first_bubble_line.'.$count};
 8657:                         }
 8658:                         $count++;
 8659:                     }
 8660:                 }
 8661:             }
 8662:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 8663:             return 'ssi_error' if ($ssi_error);
 8664:             last if (&Apache::loncommon::connection_aborted($r));
 8665:         }
 8666:     }
 8667:     return;
 8668: }
 8669: 
 8670: sub scantron_upload_scantron_data {
 8671:     my ($r,$symb)=@_;
 8672:     my $dom = $env{'request.role.domain'};
 8673:     my $domdesc = &Apache::lonnet::domain($dom,'description');
 8674:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
 8675:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 8676: 							  'domainid',
 8677: 							  'coursename',$dom);
 8678:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
 8679:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
 8680:     my $default_form_data=&defaultFormData($symb);
 8681:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
 8682:     &js_escape(\$nofile_alert);
 8683:     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.");
 8684:     &js_escape(\$nocourseid_alert);
 8685:     $r->print(&Apache::lonhtmlcommon::scripttag('
 8686:     function checkUpload(formname) {
 8687: 	if (formname.upfile.value == "") {
 8688: 	    alert("'.$nofile_alert.'");
 8689: 	    return false;
 8690: 	}
 8691:         if (formname.courseid.value == "") {
 8692:             alert("'.$nocourseid_alert.'");
 8693:             return false;
 8694:         }
 8695: 	formname.submit();
 8696:     }
 8697: 
 8698:     function ToSyllabus() {
 8699:         var cdom = '."'$dom'".';
 8700:         var cnum = document.rules.courseid.value;
 8701:         if (cdom == "" || cdom == null) {
 8702:             return;
 8703:         }
 8704:         if (cnum == "" || cnum == null) {
 8705:            return;
 8706:         }
 8707:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
 8708:                             "height=350,width=350,scrollbars=yes,menubar=no");
 8709:         return;
 8710:     }
 8711: 
 8712: '));
 8713:     $r->print('
 8714: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
 8715: 
 8716: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 8717: '.$default_form_data.
 8718:   &Apache::lonhtmlcommon::start_pick_box().
 8719:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
 8720:   '<input name="courseid" type="text" size="30" />'.$select_link.
 8721:   &Apache::lonhtmlcommon::row_closure().
 8722:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
 8723:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
 8724:   &Apache::lonhtmlcommon::row_closure().
 8725:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
 8726:   '<input name="domainid" type="hidden" />'.$domdesc.
 8727:   &Apache::lonhtmlcommon::row_closure().
 8728:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
 8729:   '<input type="file" name="upfile" size="50" />'.
 8730:   &Apache::lonhtmlcommon::row_closure(1).
 8731:   &Apache::lonhtmlcommon::end_pick_box().'<br />
 8732: 
 8733: <input name="command" value="scantronupload_save" type="hidden" />
 8734: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 8735: </form>
 8736: ');
 8737:     return '';
 8738: }
 8739: 
 8740: 
 8741: sub scantron_upload_scantron_data_save {
 8742:     my($r,$symb)=@_;
 8743:     my $doanotherupload=
 8744: 	'<br /><form action="/adm/grades" method="post">'."\n".
 8745: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 8746: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 8747: 	'</form>'."\n";
 8748:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 8749: 	!&Apache::lonnet::allowed('usc',
 8750: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 8751: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
 8752: 	unless ($symb) {
 8753: 	    $r->print($doanotherupload);
 8754: 	}
 8755: 	return '';
 8756:     }
 8757:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 8758:     my $uploadedfile;
 8759:     $r->print('<p>'.&mt('Uploading file to [_1]','"'.$coursedata{'description'}.'"').'</p>');
 8760:     if (length($env{'form.upfile'}) < 2) {
 8761:         $r->print(
 8762:             &Apache::lonhtmlcommon::confirm_success(
 8763:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
 8764:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
 8765:     } else {
 8766:         my $result = 
 8767:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
 8768:                                             $env{'form.courseid'},$env{'form.domainid'});
 8769:         if ($result =~ m{^/uploaded/}) {
 8770:             $r->print(
 8771:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
 8772:                 &mt('Uploaded [_1] bytes of data into location: [_2]',
 8773:                         (length($env{'form.upfile'})-1),
 8774:                         '<span class="LC_filename">'.$result.'</span>'));
 8775:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
 8776:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
 8777:                                                        $env{'form.courseid'},$uploadedfile));
 8778:         } else {
 8779:             $r->print(
 8780:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
 8781:                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
 8782:                           $result,
 8783: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 8784: 	}
 8785:     }
 8786:     if ($symb) {
 8787: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
 8788:     } else {
 8789: 	$r->print($doanotherupload);
 8790:     }
 8791:     return '';
 8792: }
 8793: 
 8794: sub validate_uploaded_scantron_file {
 8795:     my ($cdom,$cname,$fname) = @_;
 8796:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
 8797:     my @lines;
 8798:     if ($scanlines ne '-1') {
 8799:         @lines=split("\n",$scanlines,-1);
 8800:     }
 8801:     my $output;
 8802:     if (@lines) {
 8803:         my (%counts,$max_match_format);
 8804:         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
 8805:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
 8806:         my %idmap = &username_to_idmap($classlist);
 8807:         foreach my $key (keys(%idmap)) {
 8808:             my $lckey = lc($key);
 8809:             $idmap{$lckey} = $idmap{$key};
 8810:         }
 8811:         my %unique_formats;
 8812:         my @formatlines = &get_scantronformat_file();
 8813:         foreach my $line (@formatlines) {
 8814:             chomp($line);
 8815:             my @config = split(/:/,$line);
 8816:             my $idstart = $config[5];
 8817:             my $idlength = $config[6];
 8818:             if (($idstart ne '') && ($idlength > 0)) {
 8819:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
 8820:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
 8821:                 } else {
 8822:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
 8823:                 }
 8824:             }
 8825:         }
 8826:         foreach my $key (keys(%unique_formats)) {
 8827:             my ($idstart,$idlength) = split(':',$key);
 8828:             %{$counts{$key}} = (
 8829:                                'found'   => 0,
 8830:                                'total'   => 0,
 8831:                               );
 8832:             foreach my $line (@lines) {
 8833:                 next if ($line =~ /^#/);
 8834:                 next if ($line =~ /^[\s\cz]*$/);
 8835:                 my $id = substr($line,$idstart-1,$idlength);
 8836:                 $id = lc($id);
 8837:                 if (exists($idmap{$id})) {
 8838:                     $counts{$key}{'found'} ++;
 8839:                 }
 8840:                 $counts{$key}{'total'} ++;
 8841:             }
 8842:             if ($counts{$key}{'total'}) {
 8843:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
 8844:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
 8845:                     $max_match_pct = $percent_match;
 8846:                     $max_match_format = $key;
 8847:                     $found_match_count = $counts{$key}{'found'};
 8848:                     $max_match_count = $counts{$key}{'total'};
 8849:                 }
 8850:             }
 8851:         }
 8852:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
 8853:             my $format_descs;
 8854:             my $numwithformat = @{$unique_formats{$max_match_format}};
 8855:             for (my $i=0; $i<$numwithformat; $i++) {
 8856:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
 8857:                 if ($i<$numwithformat-2) {
 8858:                     $format_descs .= '"<i>'.$desc.'</i>", ';
 8859:                 } elsif ($i==$numwithformat-2) {
 8860:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
 8861:                 } elsif ($i==$numwithformat-1) {
 8862:                     $format_descs .= '"<i>'.$desc.'</i>"';
 8863:                 }
 8864:             }
 8865:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
 8866:             $output .= '<br />';
 8867:             if ($found_match_count == $max_match_count) {
 8868:                 # 100% matching entries
 8869:                 $output .= &Apache::lonhtmlcommon::confirm_success(
 8870:                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
 8871:                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
 8872:                 &mt('Comparison of student IDs in the uploaded file with'.
 8873:                     ' the course roster found matches for [_1] of the [_2] entries'.
 8874:                     ' in the file (for the format defined for [_3]).',
 8875:                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
 8876:             } else {
 8877:                 # Not all entries matching? -> Show warning and additional info
 8878:                 $output .=
 8879:                     &Apache::lonhtmlcommon::confirm_success(
 8880:                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
 8881:                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
 8882:                         &mt('Not all entries could be matched!'),1).'<br />'.
 8883:                     &mt('Comparison of student IDs in the uploaded file with'.
 8884:                         ' the course roster found matches for [_1] of the [_2] entries'.
 8885:                         ' in the file (for the format defined for [_3]).',
 8886:                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
 8887:                     '<p class="LC_info">'.
 8888:                     &mt('A low percentage of matches results from one of the following:').
 8889:                     '</p><ul>'.
 8890:                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
 8891:                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
 8892:                                '<i>'.$cdom.'</i>').'</li>'.
 8893:                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
 8894:                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
 8895:                     '</ul>';
 8896:             }
 8897:         }
 8898:     } else {
 8899:         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
 8900:     }
 8901:     return $output;
 8902: }
 8903: 
 8904: sub valid_file {
 8905:     my ($requested_file)=@_;
 8906:     foreach my $filename (sort(&scantron_filenames())) {
 8907: 	if ($requested_file eq $filename) { return 1; }
 8908:     }
 8909:     return 0;
 8910: }
 8911: 
 8912: sub scantron_download_scantron_data {
 8913:     my ($r,$symb)=@_;
 8914:     my $default_form_data=&defaultFormData($symb);
 8915:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 8916:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8917:     my $file=$env{'form.scantron_selectfile'};
 8918:     if (! &valid_file($file)) {
 8919: 	$r->print('
 8920: 	<p>
 8921: 	    '.&mt('The requested filename was invalid.').'
 8922:         </p>
 8923: ');
 8924: 	return;
 8925:     }
 8926:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 8927:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 8928:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 8929:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 8930:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 8931:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 8932:     $r->print('
 8933:     <p>
 8934: 	'.&mt('[_1]Original[_2] file as uploaded by the bubblesheet scanning office.',
 8935: 	      '<a href="'.$orig.'">','</a>').'
 8936:     </p>
 8937:     <p>
 8938: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 8939: 	      '<a href="'.$corrected.'">','</a>').'
 8940:     </p>
 8941:     <p>
 8942: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 8943: 	      '<a href="'.$skipped.'">','</a>').'
 8944:     </p>
 8945: ');
 8946:     return '';
 8947: }
 8948: 
 8949: sub checkscantron_results {
 8950:     my ($r,$symb) = @_;
 8951:     if (!$symb) {return '';}
 8952:     my $cid = $env{'request.course.id'};
 8953:     my %lettdig = &letter_to_digits();
 8954:     my $numletts = scalar(keys(%lettdig));
 8955:     my $cnum = $env{'course.'.$cid.'.num'};
 8956:     my $cdom = $env{'course.'.$cid.'.domain'};
 8957:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8958:     my %record;
 8959:     my %scantron_config =
 8960:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
 8961:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8962:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
 8963:     my $classlist=&Apache::loncoursedata::get_classlist();
 8964:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 8965:     my $navmap=Apache::lonnavmaps::navmap->new();
 8966:     unless (ref($navmap)) {
 8967:         $r->print(&navmap_errormsg());
 8968:         return '';
 8969:     }
 8970:     my $map=$navmap->getResourceByUrl($sequence);
 8971:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8972:         %grader_randomlists_by_symb,%orderedforcode);
 8973:     if (ref($map)) { 
 8974:         $randomorder=$map->randomorder();
 8975:         $randompick=$map->randompick();
 8976:     }
 8977:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8978:     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8979:     if ($nav_error) {
 8980:         $r->print(&navmap_errormsg());
 8981:         return '';
 8982:     }
 8983:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8984:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 8985:     my ($uname,$udom);
 8986:     my (%scandata,%lastname,%bylast);
 8987:     $r->print('
 8988: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 8989: 
 8990:     my @delayqueue;
 8991:     my %completedstudents;
 8992: 
 8993:     my $count=&get_todo_count($scanlines,$scan_data);
 8994:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 8995:     my ($username,$domain,$started);
 8996:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 8997:     if ($nav_error) {
 8998:         $r->print(&navmap_errormsg());
 8999:         return '';
 9000:     }
 9001: 
 9002:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
 9003:     my $start=&Time::HiRes::time();
 9004:     my $i=-1;
 9005: 
 9006:     while ($i<$scanlines->{'count'}) {
 9007:         ($username,$domain,$uname)=('','','');
 9008:         $i++;
 9009:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 9010:         if ($line=~/^[\s\cz]*$/) { next; }
 9011:         if ($started) {
 9012:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
 9013:         }
 9014:         $started=1;
 9015:         my $scan_record=
 9016:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 9017:                                                      $scan_data);
 9018:         unless ($uname=&scantron_find_student($scan_record,$scan_data,
 9019:                                               \%idmap,$i)) {
 9020:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 9021:                                 'Unable to find a student that matches',1);
 9022:             next;
 9023:         }
 9024:         if (exists $completedstudents{$uname}) {
 9025:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 9026:                                 'Student '.$uname.' has multiple sheets',2);
 9027:             next;
 9028:         }
 9029:         my $pid = $scan_record->{'scantron.ID'};
 9030:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 9031:         push(@{$bylast{$lastname{$pid}}},$pid);
 9032:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 9033:         my $user = $uname.':'.$usec;
 9034:         ($username,$domain)=split(/:/,$uname);
 9035: 
 9036:         my $scancode;
 9037:         if ((exists($scan_record->{'scantron.CODE'})) &&
 9038:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 9039:             $scancode = $scan_record->{'scantron.CODE'};
 9040:         } else {
 9041:             $scancode = '';
 9042:         }
 9043: 
 9044:         my @mapresources = @resources;
 9045:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 9046:         my %respnumlookup=();
 9047:         my %startline=();
 9048:         if ($randomorder || $randompick) {
 9049:             @mapresources =
 9050:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
 9051:                              \%orderedforcode);
 9052:             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
 9053:                                              $scan_record,\@master_seq,\%symb_to_resource,
 9054:                                              \%grader_partids_by_symb,\%orderedforcode,
 9055:                                              \%respnumlookup,\%startline);
 9056:             if ($randompick && $total) {
 9057:                 $lastpos = $total*$scantron_config{'Qlength'};
 9058:             }
 9059:         }
 9060:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 9061:         chomp($scandata{$pid});
 9062:         $scandata{$pid} =~ s/\r$//;
 9063: 
 9064:         my $counter = -1;
 9065:         foreach my $resource (@mapresources) {
 9066:             my $parts;
 9067:             my $ressymb = $resource->symb();
 9068:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 9069:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 9070:                 (my $analysis,$parts) =
 9071:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 9072:                                               $username,$domain,undef,
 9073:                                               $bubbles_per_row);
 9074:             } else {
 9075:                 $parts = $grader_partids_by_symb{$ressymb};
 9076:             }
 9077:             ($counter,my $recording) =
 9078:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
 9079:                                          $scandata{$pid},$parts,
 9080:                                          \%scantron_config,\%lettdig,$numletts,
 9081:                                          $randomorder,$randompick,
 9082:                                          \%respnumlookup,\%startline);
 9083:             $record{$pid} .= $recording;
 9084:         }
 9085:     }
 9086:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 9087:     $r->print('<br />');
 9088:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 9089:     $passed = 0;
 9090:     $failed = 0;
 9091:     $numstudents = 0;
 9092:     foreach my $last (sort(keys(%bylast))) {
 9093:         if (ref($bylast{$last}) eq 'ARRAY') {
 9094:             foreach my $pid (sort(@{$bylast{$last}})) {
 9095:                 my $showscandata = $scandata{$pid};
 9096:                 my $showrecord = $record{$pid};
 9097:                 $showscandata =~ s/\s/&nbsp;/g;
 9098:                 $showrecord =~ s/\s/&nbsp;/g;
 9099:                 if ($scandata{$pid} eq $record{$pid}) {
 9100:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 9101:                     $okstudents .= '<tr class="'.$css_class.'">'.
 9102: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 9103: '</tr>'."\n".
 9104: '<tr class="'.$css_class.'">'."\n".
 9105: '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
 9106:                     $passed ++;
 9107:                 } else {
 9108:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
 9109:                     $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".
 9110: '</tr>'."\n".
 9111: '<tr class="'.$css_class.'">'."\n".
 9112: '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
 9113: '</tr>'."\n";
 9114:                     $failed ++;
 9115:                 }
 9116:                 $numstudents ++;
 9117:             }
 9118:         }
 9119:     }
 9120:     $r->print(
 9121:         '<p>'
 9122:        .&mt('Comparison of bubblesheet data (including corrections) with corresponding submission records (most recent submission) for [_1][quant,_2,student][_3] ([quant,_4,bubblesheet line] per student).',
 9123:             '<b>',
 9124:             $numstudents,
 9125:             '</b>',
 9126:             $env{'form.scantron_maxbubble'})
 9127:        .'</p>'
 9128:     );
 9129:     $r->print('<p>'
 9130:              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
 9131:              .'<br />'
 9132:              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
 9133:              .'</p>'
 9134:     );
 9135:     if ($passed) {
 9136:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
 9137:         $r->print(&Apache::loncommon::start_data_table()."\n".
 9138:                  &Apache::loncommon::start_data_table_header_row()."\n".
 9139:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 9140:                  &Apache::loncommon::end_data_table_header_row()."\n".
 9141:                  $okstudents."\n".
 9142:                  &Apache::loncommon::end_data_table().'<br />');
 9143:     }
 9144:     if ($failed) {
 9145:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
 9146:         $r->print(&Apache::loncommon::start_data_table()."\n".
 9147:                  &Apache::loncommon::start_data_table_header_row()."\n".
 9148:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 9149:                  &Apache::loncommon::end_data_table_header_row()."\n".
 9150:                  $badstudents."\n".
 9151:                  &Apache::loncommon::end_data_table()).'<br />'.
 9152:                  &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.');  
 9153:     }
 9154:     $r->print('</form><br />');
 9155:     return;
 9156: }
 9157: 
 9158: sub verify_scantron_grading {
 9159:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
 9160:         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
 9161:         $respnumlookup,$startline) = @_;
 9162:     my ($record,%expected,%startpos);
 9163:     return ($counter,$record) if (!ref($resource));
 9164:     return ($counter,$record) if (!$resource->is_problem());
 9165:     my $symb = $resource->symb();
 9166:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
 9167:     foreach my $part_id (@{$partids}) {
 9168:         $counter ++;
 9169:         $expected{$part_id} = 0;
 9170:         my $respnum = $counter;
 9171:         if ($randomorder || $randompick) {
 9172:             $respnum = $respnumlookup->{$counter};
 9173:             $startpos{$part_id} = $startline->{$counter} + 1;
 9174:         } else {
 9175:             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
 9176:         }
 9177:         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
 9178:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
 9179:             foreach my $item (@sub_lines) {
 9180:                 $expected{$part_id} += $item;
 9181:             }
 9182:         } else {
 9183:             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
 9184:         }
 9185:     }
 9186:     if ($symb) {
 9187:         my %recorded;
 9188:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
 9189:         if ($returnhash{'version'}) {
 9190:             my %lasthash=();
 9191:             my $version;
 9192:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 9193:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 9194:                     $lasthash{$key}=$returnhash{$version.':'.$key};
 9195:                 }
 9196:             }
 9197:             foreach my $key (keys(%lasthash)) {
 9198:                 if ($key =~ /\.scantron$/) {
 9199:                     my $value = &unescape($lasthash{$key});
 9200:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
 9201:                     if ($value eq '') {
 9202:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
 9203:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
 9204:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9205:                             }
 9206:                         }
 9207:                     } else {
 9208:                         my @tocheck;
 9209:                         my @items = split(//,$value);
 9210:                         if (($scantron_config->{'Qon'} eq 'letter') ||
 9211:                             ($scantron_config->{'Qon'} eq 'number')) {
 9212:                             if (@items < $expected{$part_id}) {
 9213:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
 9214:                                 my @singles = split(//,$fragment);
 9215:                                 foreach my $pos (@singles) {
 9216:                                     if ($pos eq ' ') {
 9217:                                         push(@tocheck,$pos);
 9218:                                     } else {
 9219:                                         my $next = shift(@items);
 9220:                                         push(@tocheck,$next);
 9221:                                     }
 9222:                                 }
 9223:                             } else {
 9224:                                 @tocheck = @items;
 9225:                             }
 9226:                             foreach my $letter (@tocheck) {
 9227:                                 if ($scantron_config->{'Qon'} eq 'letter') {
 9228:                                     if ($letter !~ /^[A-J]$/) {
 9229:                                         $letter = $scantron_config->{'Qoff'};
 9230:                                     }
 9231:                                     $recorded{$part_id} .= $letter;
 9232:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
 9233:                                     my $digit;
 9234:                                     if ($letter !~ /^[A-J]$/) {
 9235:                                         $digit = $scantron_config->{'Qoff'};
 9236:                                     } else {
 9237:                                         $digit = $lettdig->{$letter};
 9238:                                     }
 9239:                                     $recorded{$part_id} .= $digit;
 9240:                                 }
 9241:                             }
 9242:                         } else {
 9243:                             @tocheck = @items;
 9244:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
 9245:                                 my $curr_sub = shift(@tocheck);
 9246:                                 my $digit;
 9247:                                 if ($curr_sub =~ /^[A-J]$/) {
 9248:                                     $digit = $lettdig->{$curr_sub}-1;
 9249:                                 }
 9250:                                 if ($curr_sub eq 'J') {
 9251:                                     $digit += scalar($numletts);
 9252:                                 }
 9253:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 9254:                                     if ($j == $digit) {
 9255:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
 9256:                                     } else {
 9257:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9258:                                     }
 9259:                                 }
 9260:                             }
 9261:                         }
 9262:                     }
 9263:                 }
 9264:             }
 9265:         }
 9266:         foreach my $part_id (@{$partids}) {
 9267:             if ($recorded{$part_id} eq '') {
 9268:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
 9269:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 9270:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9271:                     }
 9272:                 }
 9273:             }
 9274:             $record .= $recorded{$part_id};
 9275:         }
 9276:     }
 9277:     return ($counter,$record);
 9278: }
 9279: 
 9280: sub letter_to_digits {
 9281:     my %lettdig = (
 9282:                     A => 1,
 9283:                     B => 2,
 9284:                     C => 3,
 9285:                     D => 4,
 9286:                     E => 5,
 9287:                     F => 6,
 9288:                     G => 7,
 9289:                     H => 8,
 9290:                     I => 9,
 9291:                     J => 0,
 9292:                   );
 9293:     return %lettdig;
 9294: }
 9295: 
 9296: 
 9297: #-------- end of section for handling grading scantron forms -------
 9298: #
 9299: #-------------------------------------------------------------------
 9300: 
 9301: #-------------------------- Menu interface -------------------------
 9302: #
 9303: #--- Href with symb and command ---
 9304: 
 9305: sub href_symb_cmd {
 9306:     my ($symb,$cmd)=@_;
 9307:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
 9308: }
 9309: 
 9310: sub grading_menu {
 9311:     my ($request,$symb) = @_;
 9312:     if (!$symb) {return '';}
 9313: 
 9314:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 9315:                   'command'=>'individual');
 9316:     
 9317:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9318: 
 9319:     $fields{'command'}='ungraded';
 9320:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9321: 
 9322:     $fields{'command'}='table';
 9323:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9324: 
 9325:     $fields{'command'}='all_for_one';
 9326:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9327: 
 9328:     $fields{'command'}='downloadfilesselect';
 9329:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9330: 
 9331:     $fields{'command'} = 'csvform';
 9332:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9333:     
 9334:     $fields{'command'} = 'processclicker';
 9335:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9336:     
 9337:     $fields{'command'} = 'scantron_selectphase';
 9338:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9339: 
 9340:     $fields{'command'} = 'initialverifyreceipt';
 9341:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9342:     
 9343:     my @menu = ({	categorytitle=>'Hand Grading',
 9344:             items =>[
 9345:                         {	linktext => 'Select individual students to grade',
 9346:                     		url => $url1a,
 9347:                     		permission => 'F',
 9348:                     		icon => 'grade_students.png',
 9349:                     		linktitle => 'Grade current resource for a selection of students.'
 9350:                         }, 
 9351:                         {       linktext => 'Grade ungraded submissions.',
 9352:                                 url => $url1b,
 9353:                                 permission => 'F',
 9354:                                 icon => 'ungrade_sub.png',
 9355:                                 linktitle => 'Grade all submissions that have not been graded yet.'
 9356:                         },
 9357: 
 9358:                         {       linktext => 'Grading table',
 9359:                                 url => $url1c,
 9360:                                 permission => 'F',
 9361:                                 icon => 'grading_table.png',
 9362:                                 linktitle => 'Grade current resource for all students.'
 9363:                         },
 9364:                         {       linktext => 'Grade page/folder for one student',
 9365:                                 url => $url1d,
 9366:                                 permission => 'F',
 9367:                                 icon => 'grade_PageFolder.png',
 9368:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
 9369:                         },
 9370:                         {       linktext => 'Download submissions',
 9371:                                 url => $url1e,
 9372:                                 permission => 'F',
 9373:                                 icon => 'download_sub.png',
 9374:                                 linktitle => 'Download all students submissions.'
 9375:                         }]},
 9376:                          { categorytitle=>'Automated Grading',
 9377:                items =>[
 9378: 
 9379:                 	    {	linktext => 'Upload Scores',
 9380:                     		url => $url2,
 9381:                     		permission => 'F',
 9382:                     		icon => 'uploadscores.png',
 9383:                     		linktitle => 'Specify a file containing the class scores for current resource.'
 9384:                 	    },
 9385:                 	    {	linktext => 'Process Clicker',
 9386:                     		url => $url3,
 9387:                     		permission => 'F',
 9388:                     		icon => 'addClickerInfoFile.png',
 9389:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
 9390:                 	    },
 9391:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
 9392:                     		url => $url4,
 9393:                     		permission => 'F',
 9394:                     		icon => 'bubblesheet.png',
 9395:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
 9396:                 	    },
 9397:                             {   linktext => 'Verify Receipt Number',
 9398:                                 url => $url5,
 9399:                                 permission => 'F',
 9400:                                 icon => 'receipt_number.png',
 9401:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
 9402:                             }
 9403: 
 9404:                     ]
 9405:             });
 9406: 
 9407:     # Create the menu
 9408:     my $Str;
 9409:     $Str .= '<form method="post" action="" name="gradingMenu">';
 9410:     $Str .= '<input type="hidden" name="command" value="" />'.
 9411:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 9412: 
 9413:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
 9414:     return $Str;    
 9415: }
 9416: 
 9417: 
 9418: sub ungraded {
 9419:     my ($request)=@_;
 9420:     &submit_options($request);
 9421: }
 9422: 
 9423: sub submit_options_sequence {
 9424:     my ($request,$symb) = @_;
 9425:     if (!$symb) {return '';}
 9426:     &commonJSfunctions($request);
 9427:     my $result;
 9428: 
 9429:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 9430:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 9431:     $result.=&selectfield(0).
 9432:             '<input type="hidden" name="command" value="pickStudentPage" />
 9433:             <div>
 9434:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 9435:             </div>
 9436:         </div>
 9437:   </form>';
 9438:     return $result;
 9439: }
 9440: 
 9441: sub submit_options_table {
 9442:     my ($request,$symb) = @_;
 9443:     if (!$symb) {return '';}
 9444:     &commonJSfunctions($request);
 9445:     my $result;
 9446: 
 9447:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 9448:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 9449: 
 9450:     $result.=&selectfield(0).
 9451:             '<input type="hidden" name="command" value="viewgrades" />
 9452:             <div>
 9453:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 9454:             </div>
 9455:         </div>
 9456:   </form>';
 9457:     return $result;
 9458: }
 9459: 
 9460: sub submit_options_download {
 9461:     my ($request,$symb) = @_;
 9462:     if (!$symb) {return '';}
 9463: 
 9464:     &commonJSfunctions($request);
 9465: 
 9466:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 9467:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 9468:     $result.='
 9469: <h2>
 9470:   '.&mt('Select Students for Which to Download Submissions').'
 9471: </h2>'.&selectfield(1).'
 9472:                 <input type="hidden" name="command" value="downloadfileslink" /> 
 9473:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 9474:             </div>
 9475:           </div>
 9476: 
 9477: 
 9478:   </form>';
 9479:     return $result;
 9480: }
 9481: 
 9482: #--- Displays the submissions first page -------
 9483: sub submit_options {
 9484:     my ($request,$symb) = @_;
 9485:     if (!$symb) {return '';}
 9486: 
 9487:     &commonJSfunctions($request);
 9488:     my $result;
 9489: 
 9490:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 9491: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 9492:     $result.=&selectfield(1).'
 9493:                 <input type="hidden" name="command" value="submission" /> 
 9494: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
 9495:             </div>
 9496:           </div>
 9497: 
 9498: 
 9499:   </form>';
 9500:     return $result;
 9501: }
 9502: 
 9503: sub selectfield {
 9504:    my ($full)=@_;
 9505:    my %options = 
 9506:           (&Apache::lonlocal::texthash(
 9507:              'yes'       => 'with submissions',
 9508:              'queued'    => 'in grading queue',
 9509:              'graded'    => 'with ungraded submissions',
 9510:              'incorrect' => 'with incorrect submissions',
 9511:              'all'       => 'with any status'),
 9512:              'select_form_order' => ['yes','queued','graded','incorrect','all']);
 9513:    my $result='<div class="LC_columnSection">
 9514:   
 9515:     <fieldset>
 9516:       <legend>
 9517:        '.&mt('Sections').'
 9518:       </legend>
 9519:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
 9520:     </fieldset>
 9521:   
 9522:     <fieldset>
 9523:       <legend>
 9524:         '.&mt('Groups').'
 9525:       </legend>
 9526:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
 9527:     </fieldset>
 9528:   
 9529:     <fieldset>
 9530:       <legend>
 9531:         '.&mt('Access Status').'
 9532:       </legend>
 9533:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
 9534:     </fieldset>';
 9535:     if ($full) {
 9536:        $result.='
 9537:     <fieldset>
 9538:       <legend>
 9539:         '.&mt('Submission Status').'
 9540:       </legend>'.
 9541:        &Apache::loncommon::select_form('all','submitonly',\%options).
 9542:    '</fieldset>';
 9543:     }
 9544:     $result.='</div><br />';
 9545:     return $result;
 9546: }
 9547: 
 9548: sub reset_perm {
 9549:     undef(%perm);
 9550: }
 9551: 
 9552: sub init_perm {
 9553:     &reset_perm();
 9554:     foreach my $test_perm ('vgr','mgr','opa') {
 9555: 
 9556: 	my $scope = $env{'request.course.id'};
 9557: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
 9558: 
 9559: 	    $scope .= '/'.$env{'request.course.sec'};
 9560: 	    if ( $perm{$test_perm}=
 9561: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
 9562: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
 9563: 	    } else {
 9564: 		delete($perm{$test_perm});
 9565: 	    }
 9566: 	}
 9567:     }
 9568: }
 9569: 
 9570: sub init_old_essays {
 9571:     my ($symb,$apath,$adom,$aname) = @_;
 9572:     if ($symb ne '') {
 9573:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
 9574:         if (keys(%essays) > 0) {
 9575:             $old_essays{$symb} = \%essays;
 9576:         }
 9577:     }
 9578:     return;
 9579: }
 9580: 
 9581: sub reset_old_essays {
 9582:     undef(%old_essays);
 9583: }
 9584: 
 9585: sub gather_clicker_ids {
 9586:     my %clicker_ids;
 9587: 
 9588:     my $classlist = &Apache::loncoursedata::get_classlist();
 9589: 
 9590:     # Set up a couple variables.
 9591:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
 9592:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
 9593:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
 9594: 
 9595:     foreach my $student (keys(%$classlist)) {
 9596:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
 9597:         my $username = $classlist->{$student}->[$username_idx];
 9598:         my $domain   = $classlist->{$student}->[$domain_idx];
 9599:         my $clickers =
 9600: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
 9601:         foreach my $id (split(/\,/,$clickers)) {
 9602:             $id=~s/^[\#0]+//;
 9603:             $id=~s/[\-\:]//g;
 9604:             if (exists($clicker_ids{$id})) {
 9605: 		$clicker_ids{$id}.=','.$username.':'.$domain;
 9606:             } else {
 9607: 		$clicker_ids{$id}=$username.':'.$domain;
 9608:             }
 9609:         }
 9610:     }
 9611:     return %clicker_ids;
 9612: }
 9613: 
 9614: sub gather_adv_clicker_ids {
 9615:     my %clicker_ids;
 9616:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 9617:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9618:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
 9619:     foreach my $element (sort(keys(%coursepersonnel))) {
 9620:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
 9621:             my ($puname,$pudom)=split(/\:/,$person);
 9622:             my $clickers =
 9623: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
 9624:             foreach my $id (split(/\,/,$clickers)) {
 9625: 		$id=~s/^[\#0]+//;
 9626:                 $id=~s/[\-\:]//g;
 9627: 		if (exists($clicker_ids{$id})) {
 9628: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
 9629: 		} else {
 9630: 		    $clicker_ids{$id}=$puname.':'.$pudom;
 9631: 		}
 9632:             }
 9633:         }
 9634:     }
 9635:     return %clicker_ids;
 9636: }
 9637: 
 9638: sub clicker_grading_parameters {
 9639:     return ('gradingmechanism' => 'scalar',
 9640:             'upfiletype' => 'scalar',
 9641:             'specificid' => 'scalar',
 9642:             'pcorrect' => 'scalar',
 9643:             'pincorrect' => 'scalar');
 9644: }
 9645: 
 9646: sub process_clicker {
 9647:     my ($r,$symb)=@_;
 9648:     if (!$symb) {return '';}
 9649:     my $result=&checkforfile_js();
 9650:     $result.=&Apache::loncommon::start_data_table().
 9651:              &Apache::loncommon::start_data_table_header_row().
 9652:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
 9653:              &Apache::loncommon::end_data_table_header_row().
 9654:              &Apache::loncommon::start_data_table_row()."<td>\n";
 9655: # Attempt to restore parameters from last session, set defaults if not present
 9656:     my %Saveable_Parameters=&clicker_grading_parameters();
 9657:     &Apache::loncommon::restore_course_settings('grades_clicker',
 9658:                                                  \%Saveable_Parameters);
 9659:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
 9660:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
 9661:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
 9662:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
 9663: 
 9664:     my %checked;
 9665:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
 9666:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
 9667:           $checked{$gradingmechanism}=' checked="checked"';
 9668:        }
 9669:     }
 9670: 
 9671:     my $upload=&mt("Evaluate File");
 9672:     my $type=&mt("Type");
 9673:     my $attendance=&mt("Award points just for participation");
 9674:     my $personnel=&mt("Correctness determined from response by course personnel");
 9675:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
 9676:     my $given=&mt("Correctness determined from given list of answers").' '.
 9677:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
 9678:     my $pcorrect=&mt("Percentage points for correct solution");
 9679:     my $pincorrect=&mt("Percentage points for incorrect solution");
 9680:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
 9681: 						   {'iclicker' => 'i>clicker',
 9682:                                                     'interwrite' => 'interwrite PRS',
 9683:                                                     'turning' => 'Turning Technologies'});
 9684:     $symb = &Apache::lonenc::check_encrypt($symb);
 9685:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
 9686: function sanitycheck() {
 9687: // Accept only integer percentages
 9688:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
 9689:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
 9690: // Find out grading choice
 9691:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 9692:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
 9693:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
 9694:       }
 9695:    }
 9696: // By default, new choice equals user selection
 9697:    newgradingchoice=gradingchoice;
 9698: // Not good to give more points for false answers than correct ones
 9699:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
 9700:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
 9701:    }
 9702: // If new choice is attendance only, and old choice was correctness-based, restore defaults
 9703:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
 9704:       document.forms.gradesupload.pcorrect.value=100;
 9705:       document.forms.gradesupload.pincorrect.value=100;
 9706:    }
 9707: // If the values are different, cannot be attendance only
 9708:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
 9709:        (gradingchoice=='attendance')) {
 9710:        newgradingchoice='personnel';
 9711:    }
 9712: // Change grading choice to new one
 9713:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 9714:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
 9715:          document.forms.gradesupload.gradingmechanism[i].checked=true;
 9716:       } else {
 9717:          document.forms.gradesupload.gradingmechanism[i].checked=false;
 9718:       }
 9719:    }
 9720: // Remember the old state
 9721:    document.forms.gradesupload.waschecked.value=newgradingchoice;
 9722: }
 9723: ENDUPFORM
 9724:     $result.= <<ENDUPFORM;
 9725: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 9726: <input type="hidden" name="symb" value="$symb" />
 9727: <input type="hidden" name="command" value="processclickerfile" />
 9728: <input type="file" name="upfile" size="50" />
 9729: <br /><label>$type: $selectform</label>
 9730: ENDUPFORM
 9731:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
 9732:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
 9733:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
 9734: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
 9735: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
 9736: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
 9737: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
 9738: <br />&nbsp;&nbsp;&nbsp;
 9739: <input type="text" name="givenanswer" size="50" />
 9740: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
 9741: ENDGRADINGFORM
 9742:          $result.='</td>'.&Apache::loncommon::end_data_table_row().
 9743:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
 9744:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
 9745: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
 9746: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 9747: </form>'
 9748: ENDPERCFORM
 9749:     $result.='</td>'.
 9750:              &Apache::loncommon::end_data_table_row().
 9751:              &Apache::loncommon::end_data_table();
 9752:     return $result;
 9753: }
 9754: 
 9755: sub process_clicker_file {
 9756:     my ($r,$symb)=@_;
 9757:     if (!$symb) {return '';}
 9758: 
 9759:     my %Saveable_Parameters=&clicker_grading_parameters();
 9760:     &Apache::loncommon::store_course_settings('grades_clicker',
 9761:                                               \%Saveable_Parameters);
 9762:     my $result='';
 9763:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
 9764: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
 9765: 	return $result;
 9766:     }
 9767:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
 9768:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
 9769:         return $result;
 9770:     }
 9771:     my $foundgiven=0;
 9772:     if ($env{'form.gradingmechanism'} eq 'given') {
 9773:         $env{'form.givenanswer'}=~s/^\s*//gs;
 9774:         $env{'form.givenanswer'}=~s/\s*$//gs;
 9775:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
 9776:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
 9777:         my @answers=split(/\,/,$env{'form.givenanswer'});
 9778:         $foundgiven=$#answers+1;
 9779:     }
 9780:     my %clicker_ids=&gather_clicker_ids();
 9781:     my %correct_ids;
 9782:     if ($env{'form.gradingmechanism'} eq 'personnel') {
 9783: 	%correct_ids=&gather_adv_clicker_ids();
 9784:     }
 9785:     if ($env{'form.gradingmechanism'} eq 'specific') {
 9786: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
 9787: 	   $correct_id=~tr/a-z/A-Z/;
 9788: 	   $correct_id=~s/\s//gs;
 9789: 	   $correct_id=~s/^[\#0]+//;
 9790:            $correct_id=~s/[\-\:]//g;
 9791:            if ($correct_id) {
 9792: 	      $correct_ids{$correct_id}='specified';
 9793:            }
 9794:         }
 9795:     }
 9796:     if ($env{'form.gradingmechanism'} eq 'attendance') {
 9797: 	$result.=&mt('Score based on attendance only');
 9798:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
 9799:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
 9800:     } else {
 9801: 	my $number=0;
 9802: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
 9803: 	foreach my $id (sort(keys(%correct_ids))) {
 9804: 	    $result.='<br /><tt>'.$id.'</tt> - ';
 9805: 	    if ($correct_ids{$id} eq 'specified') {
 9806: 		$result.=&mt('specified');
 9807: 	    } else {
 9808: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
 9809: 		$result.=&Apache::loncommon::plainname($uname,$udom);
 9810: 	    }
 9811: 	    $number++;
 9812: 	}
 9813:         $result.="</p>\n";
 9814:         if ($number==0) {
 9815:             $result .=
 9816:                  &Apache::lonhtmlcommon::confirm_success(
 9817:                      &mt('No IDs found to determine correct answer'),1);
 9818:             return $result;
 9819:         }
 9820:     }
 9821:     if (length($env{'form.upfile'}) < 2) {
 9822:         $result .=
 9823:             &Apache::lonhtmlcommon::confirm_success(
 9824:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
 9825:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
 9826:         return $result;
 9827:     }
 9828: 
 9829: # Were able to get all the info needed, now analyze the file
 9830: 
 9831:     $result.=&Apache::loncommon::studentbrowser_javascript();
 9832:     $symb = &Apache::lonenc::check_encrypt($symb);
 9833:     $result.=&Apache::loncommon::start_data_table().
 9834:              &Apache::loncommon::start_data_table_header_row().
 9835:              '<th>'.&mt('Evaluate clicker file').'</th>'.
 9836:              &Apache::loncommon::end_data_table_header_row().
 9837:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
 9838: <td>
 9839: <form method="post" action="/adm/grades" name="clickeranalysis">
 9840: <input type="hidden" name="symb" value="$symb" />
 9841: <input type="hidden" name="command" value="assignclickergrades" />
 9842: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
 9843: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
 9844: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
 9845: ENDHEADER
 9846:     if ($env{'form.gradingmechanism'} eq 'given') {
 9847:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
 9848:     } 
 9849:     my %responses;
 9850:     my @questiontitles;
 9851:     my $errormsg='';
 9852:     my $number=0;
 9853:     if ($env{'form.upfiletype'} eq 'iclicker') {
 9854: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
 9855:     }
 9856:     if ($env{'form.upfiletype'} eq 'interwrite') {
 9857:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
 9858:     }
 9859:     if ($env{'form.upfiletype'} eq 'turning') {
 9860:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
 9861:     }
 9862:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
 9863:              '<input type="hidden" name="number" value="'.$number.'" />'.
 9864:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
 9865:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
 9866:              '<br />';
 9867:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
 9868:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
 9869:        return $result;
 9870:     } 
 9871: # Remember Question Titles
 9872: # FIXME: Possibly need delimiter other than ":"
 9873:     for (my $i=0;$i<$number;$i++) {
 9874:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
 9875:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
 9876:     }
 9877:     my $correct_count=0;
 9878:     my $student_count=0;
 9879:     my $unknown_count=0;
 9880: # Match answers with usernames
 9881: # FIXME: Possibly need delimiter other than ":"
 9882:     foreach my $id (keys(%responses)) {
 9883:        if ($correct_ids{$id}) {
 9884:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
 9885:           $correct_count++;
 9886:        } elsif ($clicker_ids{$id}) {
 9887:           if ($clicker_ids{$id}=~/\,/) {
 9888: # More than one user with the same clicker!
 9889:              $result.="</td>".&Apache::loncommon::end_data_table_row().
 9890:                            &Apache::loncommon::start_data_table_row()."<td>".
 9891:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
 9892:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 9893:                            "<select name='multi".$id."'>";
 9894:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
 9895:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
 9896:              }
 9897:              $result.='</select>';
 9898:              $unknown_count++;
 9899:           } else {
 9900: # Good: found one and only one user with the right clicker
 9901:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
 9902:              $student_count++;
 9903:           }
 9904:        } else {
 9905:           $result.="</td>".&Apache::loncommon::end_data_table_row().
 9906:                            &Apache::loncommon::start_data_table_row()."<td>".
 9907:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
 9908:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 9909:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
 9910:                    "\n".&mt("Domain").": ".
 9911:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
 9912:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,0,$id);
 9913:           $unknown_count++;
 9914:        }
 9915:     }
 9916:     $result.='<hr />'.
 9917:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
 9918:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
 9919:        if ($correct_count==0) {
 9920:           $errormsg.="Found no correct answers for grading!";
 9921:        } elsif ($correct_count>1) {
 9922:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
 9923:        }
 9924:     }
 9925:     if ($number<1) {
 9926:        $errormsg.="Found no questions.";
 9927:     }
 9928:     if ($errormsg) {
 9929:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
 9930:     } else {
 9931:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
 9932:     }
 9933:     $result.='</form></td>'.
 9934:              &Apache::loncommon::end_data_table_row().
 9935:              &Apache::loncommon::end_data_table();
 9936:     return $result;
 9937: }
 9938: 
 9939: sub iclicker_eval {
 9940:     my ($questiontitles,$responses)=@_;
 9941:     my $number=0;
 9942:     my $errormsg='';
 9943:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 9944:         my %components=&Apache::loncommon::record_sep($line);
 9945:         my @entries=map {$components{$_}} (sort(keys(%components)));
 9946: 	if ($entries[0] eq 'Question') {
 9947: 	    for (my $i=3;$i<$#entries;$i+=6) {
 9948: 		$$questiontitles[$number]=$entries[$i];
 9949: 		$number++;
 9950: 	    }
 9951: 	}
 9952: 	if ($entries[0]=~/^\#/) {
 9953: 	    my $id=$entries[0];
 9954: 	    my @idresponses;
 9955: 	    $id=~s/^[\#0]+//;
 9956: 	    for (my $i=0;$i<$number;$i++) {
 9957: 		my $idx=3+$i*6;
 9958:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
 9959: 		push(@idresponses,$entries[$idx]);
 9960: 	    }
 9961: 	    $$responses{$id}=join(',',@idresponses);
 9962: 	}
 9963:     }
 9964:     return ($errormsg,$number);
 9965: }
 9966: 
 9967: sub interwrite_eval {
 9968:     my ($questiontitles,$responses)=@_;
 9969:     my $number=0;
 9970:     my $errormsg='';
 9971:     my $skipline=1;
 9972:     my $questionnumber=0;
 9973:     my %idresponses=();
 9974:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 9975:         my %components=&Apache::loncommon::record_sep($line);
 9976:         my @entries=map {$components{$_}} (sort(keys(%components)));
 9977:         if ($entries[1] eq 'Time') { $skipline=0; next; }
 9978:         if ($entries[1] eq 'Response') { $skipline=1; }
 9979:         next if $skipline;
 9980:         if ($entries[0]!=$questionnumber) {
 9981:            $questionnumber=$entries[0];
 9982:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
 9983:            $number++;
 9984:         }
 9985:         my $id=$entries[4];
 9986:         $id=~s/^[\#0]+//;
 9987:         $id=~s/^v\d*\://i;
 9988:         $id=~s/[\-\:]//g;
 9989:         $idresponses{$id}[$number]=$entries[6];
 9990:     }
 9991:     foreach my $id (keys(%idresponses)) {
 9992:        $$responses{$id}=join(',',@{$idresponses{$id}});
 9993:        $$responses{$id}=~s/^\s*\,//;
 9994:     }
 9995:     return ($errormsg,$number);
 9996: }
 9997: 
 9998: sub turning_eval {
 9999:     my ($questiontitles,$responses)=@_;
10000:     my $number=0;
10001:     my $errormsg='';
10002:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10003:         my %components=&Apache::loncommon::record_sep($line);
10004:         my @entries=map {$components{$_}} (sort(keys(%components)));
10005:         if ($#entries>$number) { $number=$#entries; }
10006:         my $id=$entries[0];
10007:         my @idresponses;
10008:         $id=~s/^[\#0]+//;
10009:         unless ($id) { next; }
10010:         for (my $idx=1;$idx<=$#entries;$idx++) {
10011:             $entries[$idx]=~s/\,/\;/g;
10012:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
10013:             push(@idresponses,$entries[$idx]);
10014:         }
10015:         $$responses{$id}=join(',',@idresponses);
10016:     }
10017:     for (my $i=1; $i<=$number; $i++) {
10018:         $$questiontitles[$i]=&mt('Question [_1]',$i);
10019:     }
10020:     return ($errormsg,$number);
10021: }
10022: 
10023: 
10024: sub assign_clicker_grades {
10025:     my ($r,$symb)=@_;
10026:     if (!$symb) {return '';}
10027: # See which part we are saving to
10028:     my $res_error;
10029:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
10030:     if ($res_error) {
10031:         return &navmap_errormsg();
10032:     }
10033: # FIXME: This should probably look for the first handgradeable part
10034:     my $part=$$partlist[0];
10035: # Start screen output
10036:     my $result=&Apache::loncommon::start_data_table().
10037:              &Apache::loncommon::start_data_table_header_row().
10038:              '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
10039:              &Apache::loncommon::end_data_table_header_row().
10040:              &Apache::loncommon::start_data_table_row().'<td>';
10041: # Get correct result
10042: # FIXME: Possibly need delimiter other than ":"
10043:     my @correct=();
10044:     my $gradingmechanism=$env{'form.gradingmechanism'};
10045:     my $number=$env{'form.number'};
10046:     if ($gradingmechanism ne 'attendance') {
10047:        foreach my $key (keys(%env)) {
10048:           if ($key=~/^form\.correct\:/) {
10049:              my @input=split(/\,/,$env{$key});
10050:              for (my $i=0;$i<=$#input;$i++) {
10051:                  if (($correct[$i]) && ($input[$i]) &&
10052:                      ($correct[$i] ne $input[$i])) {
10053:                     $result.='<br /><span class="LC_warning">'.
10054:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
10055:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
10056:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
10057:                     $correct[$i]=$input[$i];
10058:                  }
10059:              }
10060:           }
10061:        }
10062:        for (my $i=0;$i<$number;$i++) {
10063:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
10064:              $result.='<br /><span class="LC_error">'.
10065:                       &mt('No correct result given for question "[_1]"!',
10066:                           $env{'form.question:'.$i}).'</span>';
10067:           }
10068:        }
10069:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
10070:     }
10071: # Start grading
10072:     my $pcorrect=$env{'form.pcorrect'};
10073:     my $pincorrect=$env{'form.pincorrect'};
10074:     my $storecount=0;
10075:     my %users=();
10076:     foreach my $key (keys(%env)) {
10077:        my $user='';
10078:        if ($key=~/^form\.student\:(.*)$/) {
10079:           $user=$1;
10080:        }
10081:        if ($key=~/^form\.unknown\:(.*)$/) {
10082:           my $id=$1;
10083:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
10084:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
10085:           } elsif ($env{'form.multi'.$id}) {
10086:              $user=$env{'form.multi'.$id};
10087:           }
10088:        }
10089:        if ($user) {
10090:           if ($users{$user}) {
10091:              $result.='<br /><span class="LC_warning">'.
10092:                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
10093:                       '</span><br />';
10094:           }
10095:           $users{$user}=1; 
10096:           my @answer=split(/\,/,$env{$key});
10097:           my $sum=0;
10098:           my $realnumber=$number;
10099:           for (my $i=0;$i<$number;$i++) {
10100:              if  ($correct[$i] eq '-') {
10101:                 $realnumber--;
10102:              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/))  {
10103:                 if ($gradingmechanism eq 'attendance') {
10104:                    $sum+=$pcorrect;
10105:                 } elsif ($correct[$i] eq '*') {
10106:                    $sum+=$pcorrect;
10107:                 } else {
10108: # We actually grade if correct or not
10109:                    my $increment=$pincorrect;
10110: # Special case: numerical answer "0"
10111:                    if ($correct[$i] eq '0') {
10112:                       if ($answer[$i]=~/^[0\.]+$/) {
10113:                          $increment=$pcorrect;
10114:                       }
10115: # General numerical answer, both evaluate to something non-zero
10116:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
10117:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
10118:                          $increment=$pcorrect;
10119:                       }
10120: # Must be just alphanumeric
10121:                    } elsif ($answer[$i] eq $correct[$i]) {
10122:                       $increment=$pcorrect;
10123:                    }
10124:                    $sum+=$increment;
10125:                 }
10126:              }
10127:           }
10128:           my $ave=$sum/(100*$realnumber);
10129: # Store
10130:           my ($username,$domain)=split(/\:/,$user);
10131:           my %grades=();
10132:           $grades{"resource.$part.solved"}='correct_by_override';
10133:           $grades{"resource.$part.awarded"}=$ave;
10134:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
10135:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
10136:                                                  $env{'request.course.id'},
10137:                                                  $domain,$username);
10138:           if ($returncode ne 'ok') {
10139:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
10140:           } else {
10141:              $storecount++;
10142:           }
10143:        }
10144:     }
10145: # We are done
10146:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
10147:              '</td>'.
10148:              &Apache::loncommon::end_data_table_row().
10149:              &Apache::loncommon::end_data_table();
10150:     return $result;
10151: }
10152: 
10153: sub navmap_errormsg {
10154:     return '<div class="LC_error">'.
10155:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
10156:            &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>').
10157:            '</div>';
10158: }
10159: 
10160: sub startpage {
10161:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$js) = @_;
10162:     if ($nomenu) {
10163:         $r->print(&Apache::loncommon::start_page("Student's Version",$js,{'only_body' => '1'}));
10164:     } else {
10165:         unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
10166:         $r->print(&Apache::loncommon::start_page('Grading',$js,
10167:                                                  {'bread_crumbs' => $crumbs}));
10168:         &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
10169:     }
10170:     unless ($nodisplayflag) {
10171:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp));
10172:     }
10173: }
10174: 
10175: sub select_problem {
10176:     my ($r)=@_;
10177:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
10178:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1));
10179:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
10180:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
10181: }
10182: 
10183: sub handler {
10184:     my $request=$_[0];
10185:     &reset_caches();
10186:     if ($request->header_only) {
10187:         &Apache::loncommon::content_type($request,'text/html');
10188:         $request->send_http_header;
10189:         return OK;
10190:     }
10191:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
10192: 
10193: # see what command we need to execute
10194: 
10195:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
10196:     my $command=$commands[0];
10197: 
10198:     &init_perm();
10199:     if (!$env{'request.course.id'}) {
10200:         unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
10201:                 ($command =~ /^scantronupload/)) {
10202:             # Not in a course.
10203:             $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
10204:             return HTTP_NOT_ACCEPTABLE;
10205:         }
10206:     } elsif (!%perm) {
10207:         $request->internal_redirect('/adm/quickgrades');
10208:         return OK;
10209:     }
10210:     &Apache::loncommon::content_type($request,'text/html');
10211:     $request->send_http_header;
10212: 
10213:     if ($#commands > 0) {
10214: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
10215:     }
10216: 
10217: # see what the symb is
10218: 
10219:     my $symb=$env{'form.symb'};
10220:     unless ($symb) {
10221:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
10222:        $symb=&Apache::lonnet::symbread($url);
10223:     }
10224:     &Apache::lonenc::check_decrypt(\$symb);
10225: 
10226:     $ssi_error = 0;
10227:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
10228: #
10229: # Not called from a resource, but inside a course
10230: #    
10231:         &startpage($request,undef,[],1,1);
10232:         &select_problem($request);
10233:     } else {
10234: 	if ($command eq 'submission' && $perm{'vgr'}) {
10235:             my ($stuvcurrent,$stuvdisp,$versionform,$js);
10236:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
10237:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
10238:                     &choose_task_version_form($symb,$env{'form.student'},
10239:                                               $env{'form.userdom'});
10240:             }
10241:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,$stuvcurrent,$stuvdisp,undef,$js);
10242:             if ($versionform) {
10243:                 $request->print($versionform);
10244:             }
10245:             $request->print('<br clear="all" />');
10246: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
10247:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
10248:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
10249:                 &choose_task_version_form($symb,$env{'form.student'},
10250:                                           $env{'form.userdom'},
10251:                                           $env{'form.inhibitmenu'});
10252:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,$stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$js);
10253:             if ($versionform) {
10254:                 $request->print($versionform);
10255:             }
10256:             $request->print('<br clear="all" />');
10257:             $request->print(&show_previous_task_version($request,$symb));
10258: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
10259:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
10260:                                        {href=>'',text=>'Select student'}],1,1);
10261: 	    &pickStudentPage($request,$symb);
10262: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
10263:             &startpage($request,$symb,
10264:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
10265:                                        {href=>'',text=>'Select student'},
10266:                                        {href=>'',text=>'Grade student'}],1,1);
10267: 	    &displayPage($request,$symb);
10268: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
10269:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
10270:                                        {href=>'',text=>'Select student'},
10271:                                        {href=>'',text=>'Grade student'},
10272:                                        {href=>'',text=>'Store grades'}],1,1);
10273: 	    &updateGradeByPage($request,$symb);
10274: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
10275:             &startpage($request,$symb,[{href=>'',text=>'...'},
10276:                                        {href=>'',text=>'Modify grades'}]);
10277: 	    &processGroup($request,$symb);
10278: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
10279:             &startpage($request,$symb);
10280: 	    $request->print(&grading_menu($request,$symb));
10281: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
10282:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
10283: 	    $request->print(&submit_options($request,$symb));
10284:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
10285:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}]);
10286:             $request->print(&listStudents($request,$symb,'graded'));
10287:         } elsif ($command eq 'table' && $perm{'vgr'}) {
10288:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
10289:             $request->print(&submit_options_table($request,$symb));
10290:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
10291:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
10292:             $request->print(&submit_options_sequence($request,$symb));
10293: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
10294:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
10295: 	    $request->print(&viewgrades($request,$symb));
10296: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
10297:             &startpage($request,$symb,[{href=>'',text=>'...'},
10298:                                        {href=>'',text=>'Store grades'}]);
10299: 	    $request->print(&processHandGrade($request,$symb));
10300: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
10301:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
10302:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
10303:                                                                              text=>"Modify grades"},
10304:                                        {href=>'', text=>"Store grades"}]);
10305: 	    $request->print(&editgrades($request,$symb));
10306:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
10307:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
10308:             $request->print(&initialverifyreceipt($request,$symb));
10309: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
10310:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
10311:                                        {href=>'',text=>'Verification Result'}]);
10312: 	    $request->print(&verifyreceipt($request,$symb));
10313:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
10314:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
10315:             $request->print(&process_clicker($request,$symb));
10316:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
10317:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
10318:                                        {href=>'', text=>'Process clicker file'}]);
10319:             $request->print(&process_clicker_file($request,$symb));
10320:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
10321:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
10322:                                        {href=>'', text=>'Process clicker file'},
10323:                                        {href=>'', text=>'Store grades'}]);
10324:             $request->print(&assign_clicker_grades($request,$symb));
10325: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
10326:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10327: 	    $request->print(&upcsvScores_form($request,$symb));
10328: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
10329:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10330: 	    $request->print(&csvupload($request,$symb));
10331: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
10332:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10333: 	    $request->print(&csvuploadmap($request,$symb));
10334: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
10335: 	    if ($env{'form.associate'} ne 'Reverse Association') {
10336:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10337: 		$request->print(&csvuploadoptions($request,$symb));
10338: 	    } else {
10339: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
10340: 		    $env{'form.upfile_associate'} = 'reverse';
10341: 		} else {
10342: 		    $env{'form.upfile_associate'} = 'forward';
10343: 		}
10344:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10345: 		$request->print(&csvuploadmap($request,$symb));
10346: 	    }
10347: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
10348:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10349: 	    $request->print(&csvuploadassign($request,$symb));
10350: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
10351:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10352: 	    $request->print(&scantron_selectphase($request,undef,$symb));
10353:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
10354:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10355:  	    $request->print(&scantron_do_warning($request,$symb));
10356: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
10357:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10358: 	    $request->print(&scantron_validate_file($request,$symb));
10359: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
10360:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10361: 	    $request->print(&scantron_process_students($request,$symb));
10362:  	} elsif ($command eq 'scantronupload' && 
10363:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
10364: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
10365:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10366:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
10367:  	} elsif ($command eq 'scantronupload_save' &&
10368:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
10369: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
10370:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10371:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
10372:  	} elsif ($command eq 'scantron_download' &&
10373: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
10374:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10375:  	    $request->print(&scantron_download_scantron_data($request,$symb));
10376:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
10377:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10378:             $request->print(&checkscantron_results($request,$symb));
10379:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
10380:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}]);
10381:             $request->print(&submit_options_download($request,$symb));
10382:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
10383:             &startpage($request,$symb,
10384:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
10385:     {href=>'', text=>'Download submissions'}]);
10386:             &submit_download_link($request,$symb);
10387: 	} elsif ($command) {
10388:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
10389: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
10390: 	}
10391:     }
10392:     if ($ssi_error) {
10393: 	&ssi_print_error($request);
10394:     }
10395:     if ($env{'form.inhibitmenu'}) {
10396:         $request->print(&Apache::loncommon::end_page());
10397:     } else {
10398:         &Apache::lonquickgrades::endGradeScreen($request);
10399:     }
10400:     &reset_caches();
10401:     return OK;
10402: }
10403: 
10404: 1;
10405: 
10406: __END__;
10407: 
10408: 
10409: =head1 NAME
10410: 
10411: Apache::grades
10412: 
10413: =head1 SYNOPSIS
10414: 
10415: Handles the viewing of grades.
10416: 
10417: This is part of the LearningOnline Network with CAPA project
10418: described at http://www.lon-capa.org.
10419: 
10420: =head1 OVERVIEW
10421: 
10422: Do an ssi with retries:
10423: While I'd love to factor out this with the version in lonprintout,
10424: 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
10425: I'm not quite ready to invent (e.g. an ssi_with_retry object).
10426: 
10427: At least the logic that drives this has been pulled out into loncommon.
10428: 
10429: 
10430: 
10431: ssi_with_retries - Does the server side include of a resource.
10432:                      if the ssi call returns an error we'll retry it up to
10433:                      the number of times requested by the caller.
10434:                      If we still have a problem, no text is appended to the
10435:                      output and we set some global variables.
10436:                      to indicate to the caller an SSI error occurred.  
10437:                      All of this is supposed to deal with the issues described
10438:                      in LON-CAPA BZ 5631 see:
10439:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
10440:                      by informing the user that this happened.
10441: 
10442: Parameters:
10443:   resource   - The resource to include.  This is passed directly, without
10444:                interpretation to lonnet::ssi.
10445:   form       - The form hash parameters that guide the interpretation of the resource
10446:                
10447:   retries    - Number of retries allowed before giving up completely.
10448: Returns:
10449:   On success, returns the rendered resource identified by the resource parameter.
10450: Side Effects:
10451:   The following global variables can be set:
10452:    ssi_error                - If an unrecoverable error occurred this becomes true.
10453:                               It is up to the caller to initialize this to false
10454:                               if desired.
10455:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
10456:                               of the resource that could not be rendered by the ssi
10457:                               call.
10458:    ssi_error_message   - The error string fetched from the ssi response
10459:                               in the event of an error.
10460: 
10461: 
10462: =head1 HANDLER SUBROUTINE
10463: 
10464: ssi_with_retries()
10465: 
10466: =head1 SUBROUTINES
10467: 
10468: =over
10469: 
10470: =head1 Routines to display previous version of a Task for a specific student
10471: 
10472: Tasks are graded pass/fail. Students who have yet to pass a particular Task
10473: can receive another opportunity. Access to tasks is slot-based. If a slot
10474: requires a proctor to check-in the student, a new version of the Task will
10475: be created when the student is checked in to the new opportunity.
10476: 
10477: If a particular student has tried two or more versions of a particular task,
10478: the submission screen provides a user with vgr privileges (e.g., a Course
10479: Coordinator) the ability to display a previous version worked on by the
10480: student.  By default, the current version is displayed. If a previous version
10481: has been selected for display, submission data are only shown that pertain
10482: to that particular version, and the interface to submit grades is not shown.
10483: 
10484: =over 4
10485: 
10486: =item show_previous_task_version()
10487: 
10488: Displays a specified version of a student's Task, as the student sees it.
10489: 
10490: Inputs: 2
10491:         request - request object
10492:         symb    - unique symb for current instance of resource
10493: 
10494: Output: None.
10495: 
10496: Side Effects: calls &show_problem() to print version of Task, with
10497:               version contained in form item: $env{'form.previousversion'}
10498: 
10499: =item choose_task_version_form()
10500: 
10501: Displays a web form used to select which version of a student's view of a
10502: Task should be displayed.  Either launches a pop-up window, or replaces
10503: content in existing pop-up, or replaces page in main window.
10504: 
10505: Inputs: 4
10506:         symb    - unique symb for current instance of resource
10507:         uname   - username of student
10508:         udom    - domain of student
10509:         nomenu  - 1 if display is in a pop-up window, and hence no menu
10510:                   breadcrumbs etc., are displayed
10511: 
10512: Output: 4
10513:         current   - student's current version
10514:         displayed - student's version being displayed
10515:         result    - scalar containing HTML for web form used to switch to
10516:                     a different version (or a link to close window, if pop-up).
10517:         js        - javascript for processing selection in versions web form
10518: 
10519: Side Effects: None.
10520: 
10521: =item previous_display_javascript()
10522: 
10523: Inputs: 2
10524:         nomenu  - 1 if display is in a pop-up window, and hence no menu
10525:                   breadcrumbs etc., are displayed.
10526:         current - student's current version number.
10527: 
10528: Output: 1
10529:         js      - javascript for processing selection in versions web form.
10530: 
10531: Side Effects: None.
10532: 
10533: =back
10534: 
10535: =head1 Routines to process bubblesheet data.
10536: 
10537: =over 4
10538: 
10539: =item scantron_get_correction() : 
10540: 
10541:    Builds the interface screen to interact with the operator to fix a
10542:    specific error condition in a specific scanline
10543: 
10544:  Arguments:
10545:     $r           - Apache request object
10546:     $i           - number of the current scanline
10547:     $scan_record - hash ref as returned from &scantron_parse_scanline()
10548:     $scan_config - hash ref as returned from &get_scantron_config()
10549:     $line        - full contents of the current scanline
10550:     $error       - error condition, valid values are
10551:                    'incorrectCODE', 'duplicateCODE',
10552:                    'doublebubble', 'missingbubble',
10553:                    'duplicateID', 'incorrectID'
10554:     $arg         - extra information needed
10555:        For errors:
10556:          - duplicateID   - paper number that this studentID was seen before on
10557:          - duplicateCODE - array ref of the paper numbers this CODE was
10558:                            seen on before
10559:          - incorrectCODE - current incorrect CODE 
10560:          - doublebubble  - array ref of the bubble lines that have double
10561:                            bubble errors
10562:          - missingbubble - array ref of the bubble lines that have missing
10563:                            bubble errors
10564: 
10565:    $randomorder - True if exam folder has randomorder set
10566:    $randompick  - True if exam folder has randompick set
10567:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
10568:                      for current line to question number used for same question
10569:                      in "Master Seqence" (as seen by Course Coordinator).
10570:    $startline   - Reference to hash where key is question number (0 is first)
10571:                   and value is number of first bubble line for current student
10572:                   or code-based randompick and/or randomorder.
10573: 
10574: 
10575: 
10576: =item  scantron_get_maxbubble() : 
10577: 
10578:    Arguments:
10579:        $nav_error  - Reference to scalar which is a flag to indicate a
10580:                       failure to retrieve a navmap object.
10581:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
10582:        calling routine should trap the error condition and display the warning
10583:        found in &navmap_errormsg().
10584: 
10585:        $scantron_config - Reference to bubblesheet format configuration hash.
10586: 
10587:    Returns the maximum number of bubble lines that are expected to
10588:    occur. Does this by walking the selected sequence rendering the
10589:    resource and then checking &Apache::lonxml::get_problem_counter()
10590:    for what the current value of the problem counter is.
10591: 
10592:    Caches the results to $env{'form.scantron_maxbubble'},
10593:    $env{'form.scantron.bubble_lines.n'}, 
10594:    $env{'form.scantron.first_bubble_line.n'} and
10595:    $env{"form.scantron.sub_bubblelines.n"}
10596:    which are the total number of bubble lines, the number of bubble
10597:    lines for response n and number of the first bubble line for response n,
10598:    and a comma separated list of numbers of bubble lines for sub-questions
10599:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
10600: 
10601: 
10602: =item  scantron_validate_missingbubbles() : 
10603: 
10604:    Validates all scanlines in the selected file to not have any
10605:     answers that don't have bubbles that have not been verified
10606:     to be bubble free.
10607: 
10608: =item  scantron_process_students() : 
10609: 
10610:    Routine that does the actual grading of the bubblesheet information.
10611: 
10612:    The parsed scanline hash is added to %env 
10613: 
10614:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
10615:    foreach resource , with the form data of
10616: 
10617: 	'submitted'     =>'scantron' 
10618: 	'grade_target'  =>'grade',
10619: 	'grade_username'=> username of student
10620: 	'grade_domain'  => domain of student
10621: 	'grade_courseid'=> of course
10622: 	'grade_symb'    => symb of resource to grade
10623: 
10624:     This triggers a grading pass. The problem grading code takes care
10625:     of converting the bubbled letter information (now in %env) into a
10626:     valid submission.
10627: 
10628: =item  scantron_upload_scantron_data() :
10629: 
10630:     Creates the screen for adding a new bubblesheet data file to a course.
10631: 
10632: =item  scantron_upload_scantron_data_save() : 
10633: 
10634:    Adds a provided bubble information data file to the course if user
10635:    has the correct privileges to do so. 
10636: 
10637: =item  valid_file() :
10638: 
10639:    Validates that the requested bubble data file exists in the course.
10640: 
10641: =item  scantron_download_scantron_data() : 
10642: 
10643:    Shows a list of the three internal files (original, corrected,
10644:    skipped) for a specific bubblesheet data file that exists in the
10645:    course.
10646: 
10647: =item  scantron_validate_ID() : 
10648: 
10649:    Validates all scanlines in the selected file to not have any
10650:    invalid or underspecified student/employee IDs
10651: 
10652: =item navmap_errormsg() :
10653: 
10654:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
10655:    Should be called whenever the request to instantiate a navmap object fails.
10656: 
10657: =back
10658: 
10659: =back
10660: 
10661: =cut

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