File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.726: download - view: text, annotated - select for diffs
Sat Nov 8 18:26:01 2014 UTC (9 years, 5 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 6740.

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.726 2014/11/08 18:26:01 raeburn 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(&HTML::Entities::encode($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 %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:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
  865:     function checkSelect(checkBox) {
  866: 	var ctr=0;
  867: 	var sense="";
  868: 	if (checkBox.length > 1) {
  869: 	    for (var i=0; i<checkBox.length; i++) {
  870: 		if (checkBox[i].checked) {
  871: 		    ctr++;
  872: 		}
  873: 	    }
  874: 	    sense = '$lt{'multiple'}';
  875: 	} else {
  876: 	    if (checkBox.checked) {
  877: 		ctr = 1;
  878: 	    }
  879: 	    sense = '$lt{'single'}';
  880: 	}
  881: 	if (ctr == 0) {
  882: 	    alert(sense);
  883: 	    return false;
  884: 	}
  885: 	document.gradesub.submit();
  886:     }
  887: 
  888:     function reLoadList(formname) {
  889: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
  890: 	formname.command.value = 'submission';
  891: 	formname.submit();
  892:     }
  893: LISTJAVASCRIPT
  894: 
  895:     &commonJSfunctions($request);
  896:     $request->print($result);
  897: 
  898:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
  899: 	"\n";
  900: 	
  901:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
  902:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
  903:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
  904:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
  905:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
  906:                   .&Apache::lonhtmlcommon::row_closure();
  907:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
  908:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
  909:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
  910:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
  911:                   .&Apache::lonhtmlcommon::row_closure();
  912: 
  913:     my $submission_options;
  914:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  915:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
  916:     $env{'form.Status'} = $saveStatus;
  917:     $submission_options.=
  918:         '<span class="LC_nobreak">'.
  919:         '<label><input type="radio" name="lastSub" value="lastonly" /> '.
  920:         &mt('last submission').' </label></span>'."\n".
  921:         '<span class="LC_nobreak">'.
  922:         '<label><input type="radio" name="lastSub" value="last" /> '.
  923:         &mt('last submission with details').' </label></span>'."\n".
  924:         '<span class="LC_nobreak">'.
  925:         '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.
  926:         &mt('all submissions').'</label></span>'."\n".
  927:         '<span class="LC_nobreak">'.
  928:         '<label><input type="radio" name="lastSub" value="all" /> '.
  929:         &mt('all submissions with details').'</label></span>';
  930:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
  931:                   .$submission_options
  932:                   .&Apache::lonhtmlcommon::row_closure();
  933: 
  934:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
  935:                   .'<select name="increment">'
  936:                   .'<option value="1">'.&mt('Whole Points').'</option>'
  937:                   .'<option value=".5">'.&mt('Half Points').'</option>'
  938:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
  939:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
  940:                   .'</select>'
  941:                   .&Apache::lonhtmlcommon::row_closure();
  942: 
  943:     $gradeTable .= 
  944:         &build_section_inputs().
  945: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
  946: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  947: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
  948: 
  949:     if (exists($env{'form.Status'})) {
  950: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
  951:     } else {
  952:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
  953:                       .&Apache::lonhtmlcommon::StatusOptions(
  954:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
  955:                       .&Apache::lonhtmlcommon::row_closure();
  956:     }
  957: 
  958:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
  959:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
  960:                   .&Apache::lonhtmlcommon::row_closure(1)
  961:                   .&Apache::lonhtmlcommon::end_pick_box();
  962: 
  963:     $gradeTable .= '<p>'
  964:                   .&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"
  965:                   .'<input type="hidden" name="command" value="processGroup" />'
  966:                   .'</p>';
  967: 
  968: # checkall buttons
  969:     $gradeTable.=&check_script('gradesub', 'stuinfo');
  970:     $gradeTable.='<input type="button" '."\n".
  971:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
  972:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
  973:     $gradeTable.=&check_buttons();
  974:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
  975:     $gradeTable.= &Apache::loncommon::start_data_table().
  976: 	&Apache::loncommon::start_data_table_header_row();
  977:     my $loop = 0;
  978:     while ($loop < 2) {
  979: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
  980: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
  981: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
  982: 	    foreach my $part (sort(@$partlist)) {
  983: 		my $display_part=
  984: 		    &get_display_part((split(/_/,$part))[0],$symb);
  985: 		$gradeTable.=
  986: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
  987: 	    }
  988: 	} elsif ($submitonly eq 'queued') {
  989: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
  990: 	}
  991: 	$loop++;
  992: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
  993:     }
  994:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
  995: 
  996:     my $ctr = 0;
  997:     foreach my $student (sort 
  998: 			 {
  999: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 1000: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 1001: 			     }
 1002: 			     return $a cmp $b;
 1003: 			 }
 1004: 			 (keys(%$fullname))) {
 1005: 	my ($uname,$udom) = split(/:/,$student);
 1006: 
 1007: 	my %status = ();
 1008: 
 1009: 	if ($submitonly eq 'queued') {
 1010: 	    my %queue_status = 
 1011: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 1012: 							$udom,$uname);
 1013: 	    next if (!defined($queue_status{'gradingqueue'}));
 1014: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
 1015: 	}
 1016: 
 1017: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1018: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
 1019: 	    my $submitted = 0;
 1020: 	    my $graded = 0;
 1021: 	    my $incorrect = 0;
 1022: 	    foreach (keys(%status)) {
 1023: 		$submitted = 1 if ($status{$_} ne 'nothing');
 1024: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
 1025: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
 1026: 		
 1027: 		my ($foo,$partid,$foo1) = split(/\./,$_);
 1028: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 1029: 		    $submitted = 0;
 1030: 		    my ($part)=split(/\./,$partid);
 1031: 		    $gradeTable.='<input type="hidden" name="'.
 1032: 			$student.':'.$part.':submitted_by" value="'.
 1033: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
 1034: 		}
 1035: 	    }
 1036: 	    
 1037: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 1038: 				     $submitonly eq 'incorrect' ||
 1039: 				     $submitonly eq 'graded'));
 1040: 	    next if (!$graded && ($submitonly eq 'graded'));
 1041: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 1042: 	}
 1043: 
 1044: 	$ctr++;
 1045: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
 1046:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
 1047: 	if ( $perm{'vgr'} eq 'F' ) {
 1048: 	    if ($ctr%2 ==1) {
 1049: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
 1050: 	    }
 1051: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
 1052:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
 1053:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
 1054: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
 1055: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
 1056: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
 1057: 
 1058: 	    if ($submitonly ne 'all') {
 1059: 		foreach (sort(keys(%status))) {
 1060: 		    next if ($_ =~ /^resource.*?submitted_by$/);
 1061: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
 1062: 		}
 1063: 	    }
 1064: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
 1065: 	    if ($ctr%2 ==0) {
 1066: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
 1067: 	    }
 1068: 	}
 1069:     }
 1070:     if ($ctr%2 ==1) {
 1071: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
 1072: 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1073: 		foreach (@$partlist) {
 1074: 		    $gradeTable.='<td>&nbsp;</td>';
 1075: 		}
 1076: 	    } elsif ($submitonly eq 'queued') {
 1077: 		$gradeTable.='<td>&nbsp;</td>';
 1078: 	    }
 1079: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
 1080:     }
 1081: 
 1082:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
 1083:         '<input type="button" '.
 1084:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
 1085:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
 1086:     if ($ctr == 0) {
 1087: 	my $num_students=(scalar(keys(%$fullname)));
 1088: 	if ($num_students eq 0) {
 1089: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
 1090: 	} else {
 1091: 	    my $submissions='submissions';
 1092: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
 1093: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
 1094: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
 1095: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
 1096: 		&mt('No '.$submissions.' found for this resource for any students. ([quant,_1,student] checked for '.$submissions.')',
 1097: 		    $num_students).
 1098: 		'</span><br />';
 1099: 	}
 1100:     } elsif ($ctr == 1) {
 1101: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
 1102:     }
 1103:     $request->print($gradeTable);
 1104:     return '';
 1105: }
 1106: 
 1107: #---- Called from the listStudents routine
 1108: 
 1109: sub check_script {
 1110:     my ($form, $type)=@_;
 1111:     my $chkallscript= &Apache::lonhtmlcommon::scripttag('
 1112:     function checkall() {
 1113:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1114:             ele = document.forms.'.$form.'.elements[i];
 1115:             if (ele.name == "'.$type.'") {
 1116:             document.forms.'.$form.'.elements[i].checked=true;
 1117:                                        }
 1118:         }
 1119:     }
 1120: 
 1121:     function checksec() {
 1122:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1123:             ele = document.forms.'.$form.'.elements[i];
 1124:            string = document.forms.'.$form.'.chksec.value;
 1125:            if
 1126:           (ele.value.indexOf(":::SECTION"+string)>0) {
 1127:               document.forms.'.$form.'.elements[i].checked=true;
 1128:             }
 1129:         }
 1130:     }
 1131: 
 1132: 
 1133:     function uncheckall() {
 1134:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1135:             ele = document.forms.'.$form.'.elements[i];
 1136:             if (ele.name == "'.$type.'") {
 1137:             document.forms.'.$form.'.elements[i].checked=false;
 1138:                                        }
 1139:         }
 1140:     }
 1141: 
 1142: '."\n");
 1143:     return $chkallscript;
 1144: }
 1145: 
 1146: sub check_buttons {
 1147:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
 1148:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
 1149:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
 1150:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
 1151:     return $buttons;
 1152: }
 1153: 
 1154: #     Displays the submissions for one student or a group of students
 1155: sub processGroup {
 1156:     my ($request,$symb)  = @_;
 1157:     my $ctr        = 0;
 1158:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1159:     my $total      = scalar(@stuchecked)-1;
 1160: 
 1161:     foreach my $student (@stuchecked) {
 1162: 	my ($uname,$udom,$fullname) = split(/:/,$student);
 1163: 	$env{'form.student'}        = $uname;
 1164: 	$env{'form.userdom'}        = $udom;
 1165: 	$env{'form.fullname'}       = $fullname;
 1166: 	&submission($request,$ctr,$total,$symb);
 1167: 	$ctr++;
 1168:     }
 1169:     return '';
 1170: }
 1171: 
 1172: #------------------------------------------------------------------------------------
 1173: #
 1174: #-------------------------- Next few routines handles grading by student, essentially
 1175: #                           handles essay response type problem/part
 1176: #
 1177: #--- Javascript to handle the submission page functionality ---
 1178: sub sub_page_js {
 1179:     my $request = shift;
 1180: 	    my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 1181:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1182:     function updateRadio(formname,id,weight) {
 1183: 	var gradeBox = formname["GD_BOX"+id];
 1184: 	var radioButton = formname["RADVAL"+id];
 1185: 	var oldpts = formname["oldpts"+id].value;
 1186: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
 1187: 	gradeBox.value = pts;
 1188: 	var resetbox = false;
 1189: 	if (isNaN(pts) || pts < 0) {
 1190: 	    alert("$alertmsg"+pts);
 1191: 	    for (var i=0; i<radioButton.length; i++) {
 1192: 		if (radioButton[i].checked) {
 1193: 		    gradeBox.value = i;
 1194: 		    resetbox = true;
 1195: 		}
 1196: 	    }
 1197: 	    if (!resetbox) {
 1198: 		formtextbox.value = "";
 1199: 	    }
 1200: 	    return;
 1201: 	}
 1202: 
 1203: 	if (pts > weight) {
 1204: 	    var resp = confirm("You entered a value ("+pts+
 1205: 			       ") greater than the weight for the part. Accept?");
 1206: 	    if (resp == false) {
 1207: 		gradeBox.value = oldpts;
 1208: 		return;
 1209: 	    }
 1210: 	}
 1211: 
 1212: 	for (var i=0; i<radioButton.length; i++) {
 1213: 	    radioButton[i].checked=false;
 1214: 	    if (pts == i && pts != "") {
 1215: 		radioButton[i].checked=true;
 1216: 	    }
 1217: 	}
 1218: 	updateSelect(formname,id);
 1219: 	formname["stores"+id].value = "0";
 1220:     }
 1221: 
 1222:     function writeBox(formname,id,pts) {
 1223: 	var gradeBox = formname["GD_BOX"+id];
 1224: 	if (checkSolved(formname,id) == 'update') {
 1225: 	    gradeBox.value = pts;
 1226: 	} else {
 1227: 	    var oldpts = formname["oldpts"+id].value;
 1228: 	    gradeBox.value = oldpts;
 1229: 	    var radioButton = formname["RADVAL"+id];
 1230: 	    for (var i=0; i<radioButton.length; i++) {
 1231: 		radioButton[i].checked=false;
 1232: 		if (i == oldpts) {
 1233: 		    radioButton[i].checked=true;
 1234: 		}
 1235: 	    }
 1236: 	}
 1237: 	formname["stores"+id].value = "0";
 1238: 	updateSelect(formname,id);
 1239: 	return;
 1240:     }
 1241: 
 1242:     function clearRadBox(formname,id) {
 1243: 	if (checkSolved(formname,id) == 'noupdate') {
 1244: 	    updateSelect(formname,id);
 1245: 	    return;
 1246: 	}
 1247: 	gradeSelect = formname["GD_SEL"+id];
 1248: 	for (var i=0; i<gradeSelect.length; i++) {
 1249: 	    if (gradeSelect[i].selected) {
 1250: 		var selectx=i;
 1251: 	    }
 1252: 	}
 1253: 	var stores = formname["stores"+id];
 1254: 	if (selectx == stores.value) { return };
 1255: 	var gradeBox = formname["GD_BOX"+id];
 1256: 	gradeBox.value = "";
 1257: 	var radioButton = formname["RADVAL"+id];
 1258: 	for (var i=0; i<radioButton.length; i++) {
 1259: 	    radioButton[i].checked=false;
 1260: 	}
 1261: 	stores.value = selectx;
 1262:     }
 1263: 
 1264:     function checkSolved(formname,id) {
 1265: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
 1266: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
 1267: 	    if (!reply) {return "noupdate";}
 1268: 	    formname.overRideScore.value = 'yes';
 1269: 	}
 1270: 	return "update";
 1271:     }
 1272: 
 1273:     function updateSelect(formname,id) {
 1274: 	formname["GD_SEL"+id][0].selected = true;
 1275: 	return;
 1276:     }
 1277: 
 1278: //=========== Check that a point is assigned for all the parts  ============
 1279:     function checksubmit(formname,val,total,parttot) {
 1280: 	formname.gradeOpt.value = val;
 1281: 	if (val == "Save & Next") {
 1282: 	    for (i=0;i<=total;i++) {
 1283: 		for (j=0;j<parttot;j++) {
 1284: 		    var partid = formname["partid"+i+"_"+j].value;
 1285: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1286: 			var points = formname["GD_BOX"+i+"_"+partid].value;
 1287: 			if (points == "") {
 1288: 			    var name = formname["name"+i].value;
 1289: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
 1290: 			    var resp = confirm("You did not assign a score for "+studentID+
 1291: 					       ", part "+partid+". Continue?");
 1292: 			    if (resp == false) {
 1293: 				formname["GD_BOX"+i+"_"+partid].focus();
 1294: 				return false;
 1295: 			    }
 1296: 			}
 1297: 		    }
 1298: 		}
 1299: 	    }
 1300: 	}
 1301: 	formname.submit();
 1302:     }
 1303: 
 1304: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1305:     function checkSubmitPage(formname,total) {
 1306: 	noscore = new Array(100);
 1307: 	var ptr = 0;
 1308: 	for (i=1;i<total;i++) {
 1309: 	    var partid = formname["q_"+i].value;
 1310: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1311: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1312: 		var status = formname["solved"+i+"_"+partid].value;
 1313: 		if (points == "" && status != "correct_by_student") {
 1314: 		    noscore[ptr] = i;
 1315: 		    ptr++;
 1316: 		}
 1317: 	    }
 1318: 	}
 1319: 	if (ptr != 0) {
 1320: 	    var sense = ptr == 1 ? ": " : "s: ";
 1321: 	    var prolist = "";
 1322: 	    if (ptr == 1) {
 1323: 		prolist = noscore[0];
 1324: 	    } else {
 1325: 		var i = 0;
 1326: 		while (i < ptr-1) {
 1327: 		    prolist += noscore[i]+", ";
 1328: 		    i++;
 1329: 		}
 1330: 		prolist += "and "+noscore[i];
 1331: 	    }
 1332: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1333: 	    if (resp == false) {
 1334: 		return false;
 1335: 	    }
 1336: 	}
 1337: 
 1338: 	formname.submit();
 1339:     }
 1340: SUBJAVASCRIPT
 1341: }
 1342: 
 1343: #--- javascript for essay type problem --
 1344: sub sub_page_kw_js {
 1345:     my $request = shift;
 1346:     my $iconpath = $request->dir_config('lonIconsURL');
 1347:     &commonJSfunctions($request);
 1348: 
 1349:     my $inner_js_msg_central= (<<INNERJS);
 1350: <script type="text/javascript">
 1351:     function checkInput() {
 1352:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1353:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1354:       var usrctr = document.msgcenter.usrctr.value;
 1355:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1356:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1357: 
 1358:       var msgchk = "";
 1359:       if (document.msgcenter.subchk.checked) {
 1360:          msgchk = "msgsub,";
 1361:       }
 1362:       var includemsg = 0;
 1363:       for (var i=1; i<=nmsg; i++) {
 1364:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1365:           var frmmsg = document.msgcenter["msg"+i];
 1366:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1367:           var showflg = opener.document.SCORE["shownOnce"+i];
 1368:           showflg.value = "1";
 1369:           var chkbox = document.msgcenter["msgn"+i];
 1370:           if (chkbox.checked) {
 1371:              msgchk += "savemsg"+i+",";
 1372:              includemsg = 1;
 1373:           }
 1374:       }
 1375:       if (document.msgcenter.newmsgchk.checked) {
 1376:          msgchk += "newmsg"+usrctr;
 1377:          includemsg = 1;
 1378:       }
 1379:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1380:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1381:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1382:       includemsg.value = msgchk;
 1383: 
 1384:       self.close()
 1385: 
 1386:     }
 1387: </script>
 1388: INNERJS
 1389: 
 1390:     my $inner_js_highlight_central= (<<INNERJS);
 1391: <script type="text/javascript">
 1392:     function updateChoice(flag) {
 1393:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1394:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1395:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1396:       opener.document.SCORE.refresh.value = "on";
 1397:       if (opener.document.SCORE.keywords.value!=""){
 1398:          opener.document.SCORE.submit();
 1399:       }
 1400:       self.close()
 1401:     }
 1402: </script>
 1403: INNERJS
 1404: 
 1405:     my $start_page_msg_central = 
 1406:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1407: 				       {'js_ready'  => 1,
 1408: 					'only_body' => 1,
 1409: 					'bgcolor'   =>'#FFFFFF',});
 1410:     my $end_page_msg_central = 
 1411: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1412: 
 1413: 
 1414:     my $start_page_highlight_central = 
 1415:         &Apache::loncommon::start_page('Highlight Central',
 1416: 				       $inner_js_highlight_central,
 1417: 				       {'js_ready'  => 1,
 1418: 					'only_body' => 1,
 1419: 					'bgcolor'   =>'#FFFFFF',});
 1420:     my $end_page_highlight_central = 
 1421: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1422: 
 1423:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1424:     $docopen=~s/^document\.//;
 1425:     my %lt = &Apache::lonlocal::texthash(
 1426:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
 1427:                 plse => 'Please select a word or group of words from document and then click this link.',
 1428:                 adds => 'Add selection to keyword list? Edit if desired.',
 1429:                 comp => 'Compose Message for: ',
 1430:                 incl => 'Include',
 1431:                 type => 'Type',
 1432:                 subj => 'Subject',
 1433:                 mesa => 'Message',
 1434:                 new  => 'New',
 1435:                 save => 'Save',
 1436:                 canc => 'Cancel',
 1437:                 kehi => 'Keyword Highlight Options',
 1438:                 txtc => 'Text Color',
 1439:                 font => 'Font Size',
 1440:                 fnst => 'Font Style',
 1441:                 col1 => 'red',
 1442:                 col2 => 'green',
 1443:                 col3 => 'blue',
 1444:                 siz1 => 'normal',
 1445:                 siz2 => '+1',
 1446:                 siz3 => '+2',
 1447:                 sty1 => 'normal',
 1448:                 sty2 => 'italic',
 1449:                 sty3 => 'bold',
 1450:              );
 1451:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1452: 
 1453: //===================== Show list of keywords ====================
 1454:   function keywords(formname) {
 1455:     var nret = prompt("$lt{'keyw'}",formname.keywords.value);
 1456:     if (nret==null) return;
 1457:     formname.keywords.value = nret;
 1458: 
 1459:     if (formname.keywords.value != "") {
 1460: 	formname.refresh.value = "on";
 1461: 	formname.submit();
 1462:     }
 1463:     return;
 1464:   }
 1465: 
 1466: //===================== Script to view submitted by ==================
 1467:   function viewSubmitter(submitter) {
 1468:     document.SCORE.refresh.value = "on";
 1469:     document.SCORE.NCT.value = "1";
 1470:     document.SCORE.unamedom0.value = submitter;
 1471:     document.SCORE.submit();
 1472:     return;
 1473:   }
 1474: 
 1475: //===================== Script to add keyword(s) ==================
 1476:   function getSel() {
 1477:     if (document.getSelection) txt = document.getSelection();
 1478:     else if (document.selection) txt = document.selection.createRange().text;
 1479:     else return;
 1480:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1481:     if (cleantxt=="") {
 1482: 	alert("$lt{'plse'}");
 1483: 	return;
 1484:     }
 1485:     var nret = prompt("$lt{'adds'}",cleantxt);
 1486:     if (nret==null) return;
 1487:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1488:     if (document.SCORE.keywords.value != "") {
 1489: 	document.SCORE.refresh.value = "on";
 1490: 	document.SCORE.submit();
 1491:     }
 1492:     return;
 1493:   }
 1494: 
 1495: //====================== Script for composing message ==============
 1496:    // preload images
 1497:    img1 = new Image();
 1498:    img1.src = "$iconpath/mailbkgrd.gif";
 1499:    img2 = new Image();
 1500:    img2.src = "$iconpath/mailto.gif";
 1501: 
 1502:   function msgCenter(msgform,usrctr,fullname) {
 1503:     var Nmsg  = msgform.savemsgN.value;
 1504:     savedMsgHeader(Nmsg,usrctr,fullname);
 1505:     var subject = msgform.msgsub.value;
 1506:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1507:     re = /msgsub/;
 1508:     var shwsel = "";
 1509:     if (re.test(msgchk)) { shwsel = "checked" }
 1510:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1511:     displaySubject(checkEntities(subject),shwsel);
 1512:     for (var i=1; i<=Nmsg; i++) {
 1513: 	var testmsg = "savemsg"+i+",";
 1514: 	re = new RegExp(testmsg,"g");
 1515: 	shwsel = "";
 1516: 	if (re.test(msgchk)) { shwsel = "checked" }
 1517: 	var message = document.SCORE["savemsg"+i].value;
 1518: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1519: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1520: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1521:     }
 1522:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1523:     shwsel = "";
 1524:     re = /newmsg/;
 1525:     if (re.test(msgchk)) { shwsel = "checked" }
 1526:     newMsg(newmsg,shwsel);
 1527:     msgTail(); 
 1528:     return;
 1529:   }
 1530: 
 1531:   function checkEntities(strx) {
 1532:     if (strx.length == 0) return strx;
 1533:     var orgStr = ["&", "<", ">", '"']; 
 1534:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1535:     var counter = 0;
 1536:     while (counter < 4) {
 1537: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1538: 	counter++;
 1539:     }
 1540:     return strx;
 1541:   }
 1542: 
 1543:   function strReplace(strx, orgStr, newStr) {
 1544:     return strx.split(orgStr).join(newStr);
 1545:   }
 1546: 
 1547:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1548:     var height = 70*Nmsg+250;
 1549:     if (height > 600) {
 1550: 	height = 600;
 1551:     }
 1552:     var xpos = (screen.width-600)/2;
 1553:     xpos = (xpos < 0) ? '0' : xpos;
 1554:     var ypos = (screen.height-height)/2-30;
 1555:     ypos = (ypos < 0) ? '0' : ypos;
 1556: 
 1557:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
 1558:     pWin.focus();
 1559:     pDoc = pWin.document;
 1560:     pDoc.$docopen;
 1561:     pDoc.write('$start_page_msg_central');
 1562: 
 1563:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1564:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1565:     pDoc.write("<h1>&nbsp;$lt{'comp'}\"+fullname+\"<\\/h1>");
 1566: 
 1567:     pDoc.write('<table style="border:1px solid black;"><tr>');
 1568:     pDoc.write("<td><b>$lt{'incl'}<\\/b><\\/td><td><b>$lt{'type'}<\\/b><\\/td><td><b>$lt{'mesa'}<\\/td><\\/tr>");
 1569: }
 1570:     function displaySubject(msg,shwsel) {
 1571:     pDoc = pWin.document;
 1572:     pDoc.write("<tr>");
 1573:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1574:     pDoc.write("<td>$lt{'subj'}<\\/td>");
 1575:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"40\\" maxlength=\\"80\\"><\\/td><\\/tr>");
 1576: }
 1577: 
 1578:   function displaySavedMsg(ctr,msg,shwsel) {
 1579:     pDoc = pWin.document;
 1580:     pDoc.write("<tr>");
 1581:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1582:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
 1583:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
 1584: }
 1585: 
 1586:   function newMsg(newmsg,shwsel) {
 1587:     pDoc = pWin.document;
 1588:     pDoc.write("<tr>");
 1589:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1590:     pDoc.write("<td align=\\"center\\">$lt{'new'}<\\/td>");
 1591:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
 1592: }
 1593: 
 1594:   function msgTail() {
 1595:     pDoc = pWin.document;
 1596:     //pDoc.write("<\\/table>");
 1597:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1598:     pDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1599:     pDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
 1600:     pDoc.write("<\\/form>");
 1601:     pDoc.write('$end_page_msg_central');
 1602:     pDoc.close();
 1603: }
 1604: 
 1605: //====================== Script for keyword highlight options ==============
 1606:   function kwhighlight() {
 1607:     var kwclr    = document.SCORE.kwclr.value;
 1608:     var kwsize   = document.SCORE.kwsize.value;
 1609:     var kwstyle  = document.SCORE.kwstyle.value;
 1610:     var redsel = "";
 1611:     var grnsel = "";
 1612:     var blusel = "";
 1613:     var txtcol1 = "$lt{'col1'}";
 1614:     var txtcol2 = "$lt{'col2'}";
 1615:     var txtcol3 = "$lt{'col3'}";
 1616:     var txtsiz1 = "$lt{'siz1'}";
 1617:     var txtsiz2 = "$lt{'siz2'}";
 1618:     var txtsiz3 = "$lt{'siz3'}";
 1619:     var txtsty1 = "$lt{'sty1'}";
 1620:     var txtsty2 = "$lt{'sty2'}";
 1621:     var txtsty3 = "$lt{'sty3'}";
 1622:     if (kwclr=="red")   {var redsel="checked='checked'"};
 1623:     if (kwclr=="green") {var grnsel="checked='checked'"};
 1624:     if (kwclr=="blue")  {var blusel="checked='checked'"};
 1625:     var sznsel = "";
 1626:     var sz1sel = "";
 1627:     var sz2sel = "";
 1628:     if (kwsize=="0")  {var sznsel="checked='checked'"};
 1629:     if (kwsize=="+1") {var sz1sel="checked='checked'"};
 1630:     if (kwsize=="+2") {var sz2sel="checked='checked'"};
 1631:     var synsel = "";
 1632:     var syisel = "";
 1633:     var sybsel = "";
 1634:     if (kwstyle=="")    {var synsel="checked='checked'"};
 1635:     if (kwstyle=="<i>") {var syisel="checked='checked'"};
 1636:     if (kwstyle=="<b>") {var sybsel="checked='checked'"};
 1637:     highlightCentral();
 1638:     highlightbody('red',txtcol1,redsel,'0',txtsiz1,sznsel,'',txtsty1,synsel);
 1639:     highlightbody('green',txtcol2,grnsel,'+1',txtsiz2,sz1sel,'<i>',txtsty2,syisel);
 1640:     highlightbody('blue',txtcol3,blusel,'+2',txtsiz3,sz2sel,'<b>',txtsty3,sybsel);
 1641:     highlightend();
 1642:     return;
 1643:   }
 1644: 
 1645:   function highlightCentral() {
 1646: //    if (window.hwdWin) window.hwdWin.close();
 1647:     var xpos = (screen.width-400)/2;
 1648:     xpos = (xpos < 0) ? '0' : xpos;
 1649:     var ypos = (screen.height-330)/2-30;
 1650:     ypos = (ypos < 0) ? '0' : ypos;
 1651: 
 1652:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1653:     hwdWin.focus();
 1654:     var hDoc = hwdWin.document;
 1655:     hDoc.$docopen;
 1656:     hDoc.write('$start_page_highlight_central');
 1657:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1658:     hDoc.write("<h1>$lt{'kehi'}<\\/h1>");
 1659: 
 1660:     hDoc.write('<table border="0" width="100%"><tr style="background-color:#A1D676">');
 1661:     hDoc.write("<th>$lt{'txtc'}<\\/th><th>$lt{'font'}<\\/th><th>$lt{'fnst'}<\\/th><\\/tr>");
 1662:   }
 1663: 
 1664:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1665:     var hDoc = hwdWin.document;
 1666:     hDoc.write("<tr>");
 1667:     hDoc.write("<td align=\\"left\\">");
 1668:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+" \\/>&nbsp;"+clrtxt+"<\\/td>");
 1669:     hDoc.write("<td align=\\"left\\">");
 1670:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+" \\/>&nbsp;"+sztxt+"<\\/td>");
 1671:     hDoc.write("<td align=\\"left\\">");
 1672:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+" \\/>&nbsp;"+sytxt+"<\\/td>");
 1673:     hDoc.write("<\\/tr>");
 1674:   }
 1675: 
 1676:   function highlightend() { 
 1677:     var hDoc = hwdWin.document;
 1678:     hDoc.write("<\\/table><br \\/>");
 1679:     hDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\" \\/>&nbsp;&nbsp;");
 1680:     hDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\" \\/><br /><br />");
 1681:     hDoc.write("<\\/form>");
 1682:     hDoc.write('$end_page_highlight_central');
 1683:     hDoc.close();
 1684:   }
 1685: 
 1686: SUBJAVASCRIPT
 1687: }
 1688: 
 1689: sub get_increment {
 1690:     my $increment = $env{'form.increment'};
 1691:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1692:         $increment != .1) {
 1693:         $increment = 1;
 1694:     }
 1695:     return $increment;
 1696: }
 1697: 
 1698: sub gradeBox_start {
 1699:     return (
 1700:         &Apache::loncommon::start_data_table()
 1701:        .&Apache::loncommon::start_data_table_header_row()
 1702:        .'<th>'.&mt('Part').'</th>'
 1703:        .'<th>'.&mt('Points').'</th>'
 1704:        .'<th>&nbsp;</th>'
 1705:        .'<th>'.&mt('Assign Grade').'</th>'
 1706:        .'<th>'.&mt('Weight').'</th>'
 1707:        .'<th>'.&mt('Grade Status').'</th>'
 1708:        .&Apache::loncommon::end_data_table_header_row()
 1709:     );
 1710: }
 1711: 
 1712: sub gradeBox_end {
 1713:     return (
 1714:         &Apache::loncommon::end_data_table()
 1715:     );
 1716: }
 1717: #--- displays the grading box, used in essay type problem and grading by page/sequence
 1718: sub gradeBox {
 1719:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 1720:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1721: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 1722:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 1723:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
 1724:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
 1725:     $wgt       = ($wgt > 0 ? $wgt : '1');
 1726:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 1727: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 1728:     my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 1729:     my $display_part= &get_display_part($partid,$symb);
 1730:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 1731: 				       [$partid]);
 1732:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 1733:     if ($last_resets{$partid}) {
 1734:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 1735:     }
 1736:     my $result=&Apache::loncommon::start_data_table_row();
 1737:     my $ctr = 0;
 1738:     my $thisweight = 0;
 1739:     my $increment = &get_increment();
 1740: 
 1741:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 1742:     while ($thisweight<=$wgt) {
 1743: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 1744:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 1745: 	    $thisweight.')" value="'.$thisweight.'" '.
 1746: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 1747: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 1748:         $thisweight += $increment;
 1749: 	$ctr++;
 1750:     }
 1751:     $radio.='</tr></table>';
 1752: 
 1753:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 1754: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 1755: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 1756: 	$wgt.')" /></td>'."\n";
 1757:     $line.='<td>/'.$wgt.' '.$wgtmsg.
 1758: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 1759: 	' </td>'."\n";
 1760:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
 1761: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 1762:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 1763: 	$line.='<option></option>'.
 1764: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
 1765:     } else {
 1766: 	$line.='<option selected="selected"></option>'.
 1767: 	    '<option value="excused" >'.&mt('excused').'</option>';
 1768:     }
 1769:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
 1770: 
 1771: 
 1772:     $result .= 
 1773: 	    '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
 1774:     $result.=&Apache::loncommon::end_data_table_row();
 1775:     $result.=&Apache::loncommon::start_data_table_row().'<td colspan="6">';
 1776:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 1777: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 1778: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 1779: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 1780:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 1781:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 1782:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 1783:         $aggtries.'" />'."\n";
 1784:     my $res_error;
 1785:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
 1786:     $result.='</td>'.&Apache::loncommon::end_data_table_row();
 1787:     if ($res_error) {
 1788:         return &navmap_errormsg();
 1789:     }
 1790:     return $result;
 1791: }
 1792: 
 1793: sub handback_box {
 1794:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
 1795:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error_pointer);
 1796:     my (@respids);
 1797:     my @part_response_id = &flatten_responseType($responseType);
 1798:     foreach my $part_response_id (@part_response_id) {
 1799:     	my ($part,$resp) = @{ $part_response_id };
 1800:         if ($part eq $partid) {
 1801:             push(@respids,$resp);
 1802:         }
 1803:     }
 1804:     my $result;
 1805:     foreach my $respid (@respids) {
 1806: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 1807: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 1808: 	next if (!@$files);
 1809: 	my $file_counter = 0;
 1810: 	foreach my $file (@$files) {
 1811: 	    if ($file =~ /\/portfolio\//) {
 1812:                 $file_counter++;
 1813:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 1814:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
 1815:     	        $file_disp = "$name.$ext";
 1816:     	        $file = $file_path.$file_disp;
 1817:     	        $result.=&mt('Return commented version of [_1] to student.',
 1818:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 1819:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 1820:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
 1821: 	    }
 1822: 	}
 1823:         if ($file_counter) {
 1824:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
 1825:                        '<span class="LC_info">'.
 1826:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
 1827:         }
 1828:     }
 1829:     return $result;    
 1830: }
 1831: 
 1832: sub show_problem {
 1833:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 1834:     my $rendered;
 1835:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 1836:     &Apache::lonxml::remember_problem_counter();
 1837:     if ($mode eq 'both' or $mode eq 'text') {
 1838: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 1839: 						       $env{'request.course.id'},
 1840: 						       undef,\%form);
 1841:     }
 1842:     if ($removeform) {
 1843: 	$rendered=~s|<form(.*?)>||g;
 1844: 	$rendered=~s|</form>||g;
 1845: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 1846:     }
 1847:     my $companswer;
 1848:     if ($mode eq 'both' or $mode eq 'answer') {
 1849: 	&Apache::lonxml::restore_problem_counter();
 1850: 	$companswer=
 1851: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 1852: 						    $env{'request.course.id'},
 1853: 						    %form);
 1854:     }
 1855:     if ($removeform) {
 1856: 	$companswer=~s|<form(.*?)>||g;
 1857: 	$companswer=~s|</form>||g;
 1858: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 1859:     }
 1860:     my $renderheading = &mt('View of the problem');
 1861:     my $answerheading = &mt('Correct answer');
 1862:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 1863:         my $stu_fullname = $env{'form.fullname'};
 1864:         if ($stu_fullname eq '') {
 1865:             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
 1866:         }
 1867:         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
 1868:         if ($forwhom ne '') {
 1869:             $renderheading = &mt('View of the problem for[_1]',$forwhom);
 1870:             $answerheading = &mt('Correct answer for[_1]',$forwhom);
 1871:         }
 1872:     }
 1873:     $rendered=
 1874:         '<div class="LC_Box">'
 1875:        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
 1876:        .$rendered
 1877:        .'</div>';
 1878:     $companswer=
 1879:         '<div class="LC_Box">'
 1880:        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
 1881:        .$companswer
 1882:        .'</div>';
 1883:     my $result;
 1884:     if ($mode eq 'both') {
 1885:         $result=$rendered.$companswer;
 1886:     } elsif ($mode eq 'text') {
 1887:         $result=$rendered;
 1888:     } elsif ($mode eq 'answer') {
 1889:         $result=$companswer;
 1890:     }
 1891:     return $result;
 1892: }
 1893: 
 1894: sub files_exist {
 1895:     my ($r, $symb) = @_;
 1896:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1897: 
 1898:     foreach my $student (@students) {
 1899:         my ($uname,$udom,$fullname) = split(/:/,$student);
 1900:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 1901: 					      $udom,$uname);
 1902:         my ($string,$timestamp)= &get_last_submission(\%record);
 1903:         foreach my $submission (@$string) {
 1904:             my ($partid,$respid) =
 1905: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 1906:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 1907: 					   \%record);
 1908:             return 1 if (@$files);
 1909:         }
 1910:     }
 1911:     return 0;
 1912: }
 1913: 
 1914: sub download_all_link {
 1915:     my ($r,$symb) = @_;
 1916:     unless (&files_exist($r, $symb)) {
 1917:        $r->print(&mt('There are currently no submitted documents.'));
 1918:        return;
 1919:     }
 1920: 
 1921:     my $all_students = 
 1922: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 1923: 
 1924:     my $parts =
 1925: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 1926: 
 1927:     my $identifier = &Apache::loncommon::get_cgi_id();
 1928:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 1929:                              'cgi.'.$identifier.'.symb' => $symb,
 1930:                              'cgi.'.$identifier.'.parts' => $parts,});
 1931:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 1932: 	      &mt('Download All Submitted Documents').'</a>');
 1933:     return;
 1934: }
 1935: 
 1936: sub submit_download_link {
 1937:     my ($request,$symb) = @_;
 1938:     if (!$symb) { return ''; }
 1939: #FIXME: Figure out which type of problem this is and provide appropriate download
 1940:     &download_all_link($request,$symb);
 1941: }
 1942: 
 1943: sub build_section_inputs {
 1944:     my $section_inputs;
 1945:     if ($env{'form.section'} eq '') {
 1946:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 1947:     } else {
 1948:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 1949:         foreach my $section (@sections) {
 1950:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 1951:         }
 1952:     }
 1953:     return $section_inputs;
 1954: }
 1955: 
 1956: # --------------------------- show submissions of a student, option to grade 
 1957: sub submission {
 1958:     my ($request,$counter,$total,$symb) = @_;
 1959:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 1960:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 1961:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 1962:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 1963: 
 1964:     my $probtitle=&Apache::lonnet::gettitle($symb); 
 1965:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 1966: 
 1967:     if (!&canview($usec)) {
 1968:         $request->print(
 1969:             '<span class="LC_warning">'.
 1970:             &mt('Unable to view requested student.').
 1971:             ' '.&mt('([_1] in section [_2] in course id [_3])',
 1972:                         $uname.':'.$udom,$usec,$env{'request.course.id'}).
 1973:             '</span>');
 1974: 	return;
 1975:     }
 1976: 
 1977:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 1978:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 1979:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 1980:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 1981:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1982: 	'" src="'.$request->dir_config('lonIconsURL').
 1983: 	'/check.gif" height="16" border="0" />';
 1984: 
 1985:     # header info
 1986:     if ($counter == 0) {
 1987: 	&sub_page_js($request);
 1988: 	&sub_page_kw_js($request);
 1989: 
 1990: 	# option to display problem, only once else it cause problems 
 1991:         # with the form later since the problem has a form.
 1992: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 1993: 	    my $mode;
 1994: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 1995: 		$mode='both';
 1996: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 1997: 		$mode='text';
 1998: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 1999: 		$mode='answer';
 2000: 	    }
 2001: 	    &Apache::lonxml::clear_problem_counter();
 2002: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 2003: 	}
 2004: 
 2005: 	# kwclr is the only variable that is guaranteed not to be blank 
 2006:         # if this subroutine has been called once.
 2007: 	my %keyhash = ();
 2008: #	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
 2009:         if (1) {
 2010: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 2011: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 2012: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 2013: 
 2014: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2015: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 2016: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 2017: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 2018: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 2019: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
 2020: 		$keyhash{$symb.'_subject'} : $probtitle;
 2021: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 2022: 	}
 2023: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 2024: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 2025: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 2026: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 2027: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 2028: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 2029: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 2030: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 2031: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 2032: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 2033: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 2034: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 2035: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 2036: 			&build_section_inputs().
 2037: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 2038: 			'<input type="hidden" name="NCT"'.
 2039: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 2040: #	if ($env{'form.handgrade'} eq 'yes') {
 2041:         if (1) {
 2042: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 2043: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 2044: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 2045: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
 2046: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 2047: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 2048: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 2049: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
 2050: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
 2051: 	    }
 2052: 	}
 2053: 	
 2054: 	my ($cts,$prnmsg) = (1,'');
 2055: 	while ($cts <= $env{'form.savemsgN'}) {
 2056: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 2057: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 2058: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 2059: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 2060: 		'" />'."\n".
 2061: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 2062: 	    $cts++;
 2063: 	}
 2064: 	$request->print($prnmsg);
 2065: 
 2066: #	if ($env{'form.handgrade'} eq 'yes') {
 2067:         if (1) {
 2068: 
 2069:             my %lt = &Apache::lonlocal::texthash(
 2070:                           keyh => 'Keyword Highlighting for Essays',
 2071:                           keyw => 'Keyword Options',
 2072:                           list => 'List',
 2073:                           past => 'Paste Selection to List',
 2074:                           high => 'Highlight Attribute',
 2075:                      );    
 2076: #
 2077: # Print out the keyword options line
 2078: #
 2079: 	    $request->print(
 2080:                 '<div class="LC_columnSection">'
 2081:                .'<fieldset><legend>'.$lt{'keyh'}.'</legend>'
 2082:                .&Apache::lonhtmlcommon::funclist_from_array(
 2083:                     ['<a href="javascript:keywords(document.SCORE);" target="_self">'.$lt{'list'}.'</a>',
 2084:                      '<a href="#" onmousedown="javascript:getSel(); return false"
 2085:  class="page">'.$lt{'past'}.'</a>',
 2086:                      '<a href="javascript:kwhighlight();" target="_self">'.$lt{'high'}.'</a>'],
 2087:                     {legend => $lt{'keyw'}})
 2088:                .'</fieldset></div>'
 2089:             );
 2090: 
 2091: #
 2092: # Load the other essays for similarity check
 2093: #
 2094:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 2095: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 2096: 	    $apath=&escape($apath);
 2097: 	    $apath=~s/\W/\_/gs;
 2098:             &init_old_essays($symb,$apath,$adom,$aname);
 2099:         }
 2100:     }
 2101: 
 2102: # This is where output for one specific student would start
 2103:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
 2104:     $request->print(
 2105:         "\n\n"
 2106:        .'<div class="LC_grade_show_user'.$add_class.'">'
 2107:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
 2108:        ."\n"
 2109:     );
 2110: 
 2111:     # Show additional functions if allowed
 2112:     if ($perm{'vgr'}) {
 2113:         $request->print(
 2114:             &Apache::loncommon::track_student_link(
 2115:                 'View recent activity',
 2116:                 $uname,$udom,'check')
 2117:            .' '
 2118:         );
 2119:     }
 2120:     if ($perm{'opa'}) {
 2121:         $request->print(
 2122:             &Apache::loncommon::pprmlink(
 2123:                 &mt('Set/Change parameters'),
 2124:                 $uname,$udom,$symb,'check'));
 2125:     }
 2126: 
 2127:     # Show Problem
 2128:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2129: 	my $mode;
 2130: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2131: 	    $mode='both';
 2132: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2133: 	    $mode='text';
 2134: 	} elsif ($env{'form.vAns'} eq 'all') {
 2135: 	    $mode='answer';
 2136: 	}
 2137: 	&Apache::lonxml::clear_problem_counter();
 2138: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2139:     }
 2140: 
 2141:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2142:     my $res_error;
 2143:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2144:     if ($res_error) {
 2145:         $request->print(&navmap_errormsg());
 2146:         return;
 2147:     }
 2148: 
 2149:     # Display student info
 2150:     $request->print(($counter == 0 ? '' : '<br />'));
 2151: 
 2152:     my $result='<div class="LC_Box">'
 2153:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
 2154:     $result.='<input type="hidden" name="name'.$counter.
 2155:              '" value="'.$env{'form.fullname'}.'" />'."\n";
 2156: #    if ($env{'form.handgrade'} eq 'no') {
 2157:     if (1) {
 2158:         $result.='<p class="LC_info">'
 2159:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
 2160:                 ."</p>\n";
 2161:     }
 2162: 
 2163:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
 2164:     my $fullname;
 2165:     my $col_fullnames = [];
 2166: #    if ($env{'form.handgrade'} eq 'yes') {
 2167:     if (1) {
 2168: 	(my $sub_result,$fullname,$col_fullnames)=
 2169: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2170: 				 $counter);
 2171: 	$result.=$sub_result;
 2172:     }
 2173:     $request->print($result."\n");
 2174:     
 2175:     # print student answer/submission
 2176:     # Options are (1) Handgraded submission only
 2177:     #             (2) Last submission, includes submission that is not handgraded 
 2178:     #                  (for multi-response type part)
 2179:     #             (3) Last submission plus the parts info
 2180:     #             (4) The whole record for this student
 2181:     
 2182:     my ($string,$timestamp)= &get_last_submission(\%record);
 2183: 	
 2184:     my $lastsubonly;
 2185: 
 2186:     if ($$timestamp eq '') {
 2187:         $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
 2188:     } else {
 2189:         $lastsubonly =
 2190:             '<div class="LC_grade_submissions_body">'
 2191:            .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
 2192: 
 2193: 	my %seenparts;
 2194: 	my @part_response_id = &flatten_responseType($responseType);
 2195: 	foreach my $part (@part_response_id) {
 2196: 	    next if ($env{'form.lastSub'} eq 'hdgrade' 
 2197: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
 2198: 
 2199: 	    my ($partid,$respid) = @{ $part };
 2200: 	    my $display_part=&get_display_part($partid,$symb);
 2201: 	    if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2202: 		if (exists($seenparts{$partid})) { next; }
 2203: 		$seenparts{$partid}=1;
 2204:                 $request->print(
 2205:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2206:                     ' <b>'.&mt('Collaborative submission by: [_1]',
 2207:                                '<a href="javascript:viewSubmitter(\''.
 2208:                                $env{"form.$uname:$udom:$partid:submitted_by"}.
 2209:                                '\');" target="_self">'.
 2210:                                $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
 2211:                     '<br />');
 2212: 		next;
 2213: 		}
 2214: 	    my $responsetype = $responseType->{$partid}->{$respid};
 2215: 	    if (!exists($record{"resource.$partid.$respid.submission"})) {
 2216:                 $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
 2217:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2218:                     ' <span class="LC_internal_info">'.
 2219:                     '('.&mt('Response ID: [_1]',$respid).')'.
 2220:                     '</span>&nbsp; &nbsp;'.
 2221: 	       	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
 2222: 		next;
 2223: 	    }
 2224: 	    foreach my $submission (@$string) {
 2225: 		my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2226: 		if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2227: 		my ($ressub,$hide,$draft,$subval) = split(/:/,$submission,4);
 2228: 		# Similarity check
 2229:                 my $similar='';
 2230:                 my ($type,$trial,$rndseed);
 2231:                 if ($hide eq 'rand') {
 2232:                     $type = 'randomizetry';
 2233:                     $trial = $record{"resource.$partid.tries"};
 2234:                     $rndseed = $record{"resource.$partid.rndseed"};
 2235:                 }
 2236: 	        if ($env{'form.checkPlag'}) {
 2237:     		    my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2238: 		        &most_similar($uname,$udom,$symb,$subval);
 2239: 		    if ($osim) {
 2240: 			$osim=int($osim*100.0);
 2241: 			my %old_course_desc = 
 2242: 			    &Apache::lonnet::coursedescription($ocrsid,
 2243: 							{'one_time' => 1});
 2244: 
 2245:                         if ($hide eq 'anon') {
 2246:                             $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
 2247:                                      &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
 2248:                         } else {
 2249: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
 2250: 				&mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
 2251: 				    $osim,
 2252: 				    &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
 2253: 				        $old_course_desc{'description'},
 2254: 				        $old_course_desc{'num'},
 2255: 				        $old_course_desc{'domain'}).
 2256: 				    '</span></h3><blockquote><i>'.
 2257: 				    &keywords_highlight($oessay).
 2258: 				    '</i></blockquote><hr />';
 2259:                         }
 2260: 	            }
 2261: 		}
 2262: 		my $order=&get_order($partid,$respid,$symb,$uname,$udom,
 2263:                                      undef,$type,$trial,$rndseed);
 2264:                 if ($env{'form.lastSub'} eq 'lastonly' || $env{'form.lastSub'} eq 'datesub' || $env{'form.lastSub'} =~ /^(last|all)$/ || ($env{'form.lastSub'} eq 'hdgrade' && 
 2265: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
 2266: 		    my $display_part=&get_display_part($partid,$symb);
 2267:                     $lastsubonly.='<div class="LC_grade_submission_part">'.
 2268:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2269:                         ' <span class="LC_internal_info">'.
 2270:                         '('.&mt('Response ID: [_1]',$respid).')'.
 2271:                         '</span>&nbsp; &nbsp;';
 2272: 		    my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2273:                         
 2274: 		    if (@$files) {
 2275:                         if ($hide eq 'anon') {
 2276:                             $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
 2277:                         } else {
 2278:                             $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
 2279:                                         .'<br /><span class="LC_warning">';
 2280:                             if(@$files == 1) {
 2281:                                 $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
 2282:                             } else {
 2283:                                 $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
 2284:                             }
 2285:                             $lastsubonly .= '</span>';                         
 2286:                             foreach my $file (@$files) {
 2287:                                 &Apache::lonnet::allowuploaded('/adm/grades',$file);
 2288:                                 $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
 2289:                             }
 2290:                         }
 2291: 			$lastsubonly.='<br />';
 2292:                     }
 2293:                     if ($hide eq 'anon') {
 2294:                         $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>'; 
 2295:                     } else {
 2296:              	        $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>';
 2297:                         if ($draft) {
 2298:                             $lastsubonly.= ' <span class="LC_warning">'.&mt('Draft Copy').'</span>';
 2299:                         }
 2300:                         $subval =
 2301: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
 2302: 					 $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
 2303:                         if ($responsetype eq 'essay') {
 2304:                             $subval =~ s{\n}{<br />}g;
 2305:                         }
 2306:                         $lastsubonly.=$subval."\n";
 2307:                     }
 2308: 	            if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2309: 		    $lastsubonly.='</div>';
 2310: 		}
 2311:             }
 2312: 	}
 2313: 	$lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
 2314:     }
 2315:     $request->print($lastsubonly);
 2316:     if ($env{'form.lastSub'} eq 'datesub') {
 2317:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2318: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2319:   
 2320:     } 
 2321:     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2322:         my $identifier = (&canmodify($usec)? $counter : '');
 2323:         $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2324: 								 $env{'request.course.id'},
 2325: 								 $last,'.submission',
 2326: 								 'Apache::grades::keywords_highlight',
 2327:                                                                  $usec,$identifier));
 2328:     }
 2329:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2330: 	.$udom.'" />'."\n");
 2331:     # return if view submission with no grading option
 2332:     if (!&canmodify($usec)) {
 2333: 	$request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
 2334: 	return;
 2335:     } else {
 2336: 	$request->print('</div>'."\n");
 2337:     }
 2338: 
 2339:     # essay grading message center
 2340: #    if ($env{'form.handgrade'} eq 'yes') {
 2341:     if (1) {
 2342: 	my $result='<div class="LC_grade_message_center">';
 2343:     
 2344: 	$result.='<div class="LC_grade_message_center_header">'.
 2345: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
 2346: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2347: 	my $msgfor = $givenn.' '.$lastname;
 2348: 	if (scalar(@$col_fullnames) > 0) {
 2349: 	    my $lastone = pop(@$col_fullnames);
 2350: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2351: 	}
 2352: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2353: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2354: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
 2355: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2356: 	    ',\''.$msgfor.'\');" target="_self">'.
 2357: 	    &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
 2358: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2359: 	    ' <img src="'.$request->dir_config('lonIconsURL').
 2360: 	    '/mailbkgrd.gif" width="14" height="10" alt="" name="mailicon'.$counter.'" />'."\n".
 2361: 	    '<br />&nbsp;('.
 2362: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
 2363: 	$result.='</div></div>';
 2364: 	$request->print($result);
 2365:     }
 2366: 
 2367:     my %seen = ();
 2368:     my @partlist;
 2369:     my @gradePartRespid;
 2370:     my @part_response_id = &flatten_responseType($responseType);
 2371:     $request->print(
 2372:         '<div class="LC_Box">'
 2373:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
 2374:     );
 2375:     $request->print(&gradeBox_start());
 2376:     foreach my $part_response_id (@part_response_id) {
 2377:     	my ($partid,$respid) = @{ $part_response_id };
 2378: 	my $part_resp = join('_',@{ $part_response_id });
 2379: 	next if ($seen{$partid} > 0);
 2380: 	$seen{$partid}++;
 2381: 	next if ($$handgrade{$part_resp} ne 'yes' 
 2382: 		 && $env{'form.lastSub'} eq 'hdgrade');
 2383: 	push(@partlist,$partid);
 2384: 	push(@gradePartRespid,$partid.'.'.$respid);
 2385: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2386:     }
 2387:     $request->print(&gradeBox_end()); # </div>
 2388:     $request->print('</div>');
 2389: 
 2390:     $request->print('<div class="LC_grade_info_links">');
 2391:     $request->print('</div>');
 2392: 
 2393:     $result='<input type="hidden" name="partlist'.$counter.
 2394: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2395:     $result.='<input type="hidden" name="gradePartRespid'.
 2396: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2397:     my $ctr = 0;
 2398:     while ($ctr < scalar(@partlist)) {
 2399: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2400: 	    $partlist[$ctr].'" />'."\n";
 2401: 	$ctr++;
 2402:     }
 2403:     $request->print($result.''."\n");
 2404: 
 2405: # Done with printing info for one student
 2406: 
 2407:     $request->print('</div>');#LC_grade_show_user
 2408: 
 2409: 
 2410:     # print end of form
 2411:     if ($counter == $total) {
 2412:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
 2413: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2414: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
 2415: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2416: 	my $ntstu ='<select name="NTSTU">'.
 2417: 	    '<option>1</option><option>2</option>'.
 2418: 	    '<option>3</option><option>5</option>'.
 2419: 	    '<option>7</option><option>10</option></select>'."\n";
 2420: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2421: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2422:         $endform.=&mt('[_1]student(s)',$ntstu);
 2423: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2424: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2425: 	    '<input type="button" value="'.&mt('Next').'" '.
 2426: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2427:         $endform.='<span class="LC_warning">'.
 2428:                   &mt('(Next and Previous (student) do not save the scores.)').
 2429:                   '</span>'."\n" ;
 2430:         $endform.="<input type='hidden' value='".&get_increment().
 2431:             "' name='increment' />";
 2432: 	$endform.='</td></tr></table></form>';
 2433: 	$request->print($endform);
 2434:     }
 2435:     return '';
 2436: }
 2437: 
 2438: sub check_collaborators {
 2439:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2440:     my ($result,@col_fullnames);
 2441:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2442:     foreach my $part (keys(%$handgrade)) {
 2443: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2444: 					'.maxcollaborators',
 2445: 					$symb,$udom,$uname);
 2446: 	next if ($ncol <= 0);
 2447: 	$part =~ s/\_/\./g;
 2448: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2449: 	my (@good_collaborators, @bad_collaborators);
 2450: 	foreach my $possible_collaborator
 2451: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2452: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2453: 	    next if ($possible_collaborator eq '');
 2454: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
 2455: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2456: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2457: 	    # Doing this grep allows 'fuzzy' specification
 2458: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2459: 			       keys(%$classlist));
 2460: 	    if (! scalar(@matches)) {
 2461: 		push(@bad_collaborators, $possible_collaborator);
 2462: 	    } else {
 2463: 		push(@good_collaborators, @matches);
 2464: 	    }
 2465: 	}
 2466: 	if (scalar(@good_collaborators) != 0) {
 2467: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
 2468: 	    foreach my $name (@good_collaborators) {
 2469: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2470: 		push(@col_fullnames, $givenn.' '.$lastname);
 2471: 		$result.='<li>'.$fullname->{$name}.'</li>';
 2472: 	    }
 2473: 	    $result.='</ol><br />'."\n";
 2474: 	    my ($part)=split(/\./,$part);
 2475: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2476: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2477: 		"\n";
 2478: 	}
 2479: 	if (scalar(@bad_collaborators) > 0) {
 2480: 	    $result.='<div class="LC_warning">';
 2481: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2482: 	    $result .= '</div>';
 2483: 	}         
 2484: 	if (scalar(@bad_collaborators > $ncol)) {
 2485: 	    $result .= '<div class="LC_warning">';
 2486: 	    $result .= &mt('This student has submitted too many '.
 2487: 		'collaborators.  Maximum is [_1].',$ncol);
 2488: 	    $result .= '</div>';
 2489: 	}
 2490:     }
 2491:     return ($result,$fullname,\@col_fullnames);
 2492: }
 2493: 
 2494: #--- Retrieve the last submission for all the parts
 2495: sub get_last_submission {
 2496:     my ($returnhash)=@_;
 2497:     my (@string,$timestamp,%lasthidden);
 2498:     if ($$returnhash{'version'}) {
 2499: 	my %lasthash=();
 2500: 	my ($version);
 2501: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2502: 	    foreach my $key (sort(split(/\:/,
 2503: 					$$returnhash{$version.':keys'}))) {
 2504: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2505: 		$timestamp = 
 2506: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2507: 	    }
 2508: 	}
 2509:         my (%typeparts,%randombytry);
 2510:         my $showsurv = 
 2511:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
 2512:         foreach my $key (sort(keys(%lasthash))) {
 2513:             if ($key =~ /\.type$/) {
 2514:                 if (($lasthash{$key} eq 'anonsurvey') || 
 2515:                     ($lasthash{$key} eq 'anonsurveycred') ||
 2516:                     ($lasthash{$key} eq 'randomizetry')) {
 2517:                     my ($ign,@parts) = split(/\./,$key);
 2518:                     pop(@parts);
 2519:                     my $id = join('.',@parts);
 2520:                     if ($lasthash{$key} eq 'randomizetry') {
 2521:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
 2522:                     } else {
 2523:                         unless ($showsurv) {
 2524:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
 2525:                         }
 2526:                     }
 2527:                     delete($lasthash{$key});
 2528:                 }
 2529:             }
 2530:         }
 2531:         my @hidden = keys(%typeparts);
 2532:         my @randomize = keys(%randombytry);
 2533: 	foreach my $key (keys(%lasthash)) {
 2534: 	    next if ($key !~ /\.submission$/);
 2535:             my $hide;
 2536:             if (@hidden) {
 2537:                 foreach my $id (@hidden) {
 2538:                     if ($key =~ /^\Q$id\E/) {
 2539:                         $hide = 'anon';
 2540:                         last;
 2541:                     }
 2542:                 }
 2543:             }
 2544:             unless ($hide) {
 2545:                 if (@randomize) {
 2546:                     foreach my $id (@hidden) {
 2547:                         if ($key =~ /^\Q$id\E/) {
 2548:                             $hide = 'rand';
 2549:                             last;
 2550:                         }
 2551:                     }
 2552:                 }
 2553:             }
 2554: 	    my ($partid,$foo) = split(/submission$/,$key);
 2555: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ? 1 : 0;
 2556:             push(@string, join(':', $key, $hide, $draft, (
 2557:                 ref($lasthash{$key}) eq 'ARRAY' ?
 2558:                     join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
 2559: 	}
 2560:     }
 2561:     if (!@string) {
 2562: 	$string[0] =
 2563: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
 2564:     }
 2565:     return (\@string,\$timestamp);
 2566: }
 2567: 
 2568: #--- High light keywords, with style choosen by user.
 2569: sub keywords_highlight {
 2570:     my $string    = shift;
 2571:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2572:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2573:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2574:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2575:     foreach my $keyword (@keylist) {
 2576: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2577:     }
 2578:     return $string;
 2579: }
 2580: 
 2581: # For Tasks provide a mechanism to display previous version for one specific student
 2582: 
 2583: sub show_previous_task_version {
 2584:     my ($request,$symb) = @_;
 2585:     if ($symb eq '') {
 2586:         $request->print(
 2587:             '<span class="LC_error">'.
 2588:             &mt('Unable to handle ambiguous references.').
 2589:             '</span>');
 2590:         return '';
 2591:     }
 2592:     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
 2593:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 2594:     if (!&canview($usec)) {
 2595:         $request->print(
 2596:             '<span class="LC_warning">'.
 2597:             &mt('Unable to view previous version for requested student.').
 2598:             ' '.&mt('([_1] in section [_2] in course id [_3])',
 2599:                     $uname.':'.$udom,$usec,$env{'request.course.id'}).
 2600:             '</span>');
 2601:         return;
 2602:     }
 2603:     my $mode = 'both';
 2604:     my $isTask = ($symb =~/\.task$/);
 2605:     if ($isTask) {
 2606:         if ($env{'form.previousversion'} =~ /^\d+$/) {
 2607:             if ($env{'form.fullname'} eq '') {
 2608:                 $env{'form.fullname'} =
 2609:                     &Apache::loncommon::plainname($uname,$udom,'lastname');
 2610:             }
 2611:             my $probtitle=&Apache::lonnet::gettitle($symb);
 2612:             $request->print("\n\n".
 2613:                             '<div class="LC_grade_show_user">'.
 2614:                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 2615:                             '</h2>'."\n");
 2616:             &Apache::lonxml::clear_problem_counter();
 2617:             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
 2618:                             {'previousversion' => $env{'form.previousversion'} }));
 2619:             $request->print("\n</div>");
 2620:         }
 2621:     }
 2622:     return;
 2623: }
 2624: 
 2625: sub choose_task_version_form {
 2626:     my ($symb,$uname,$udom,$nomenu) = @_;
 2627:     my $isTask = ($symb =~/\.task$/);
 2628:     my ($current,$version,$result,$js,$displayed,$rowtitle);
 2629:     if ($isTask) {
 2630:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 2631:                                               $udom,$uname);
 2632:         if (($record{'resource.0.version'} eq '') ||
 2633:             ($record{'resource.0.version'} < 2)) {
 2634:             return ($record{'resource.0.version'},
 2635:                     $record{'resource.0.version'},$result,$js);
 2636:         } else {
 2637:             $current = $record{'resource.0.version'};
 2638:         }
 2639:         if ($env{'form.previousversion'}) {
 2640:             $displayed = $env{'form.previousversion'};
 2641:             $rowtitle = &mt('Choose another version:')
 2642:         } else {
 2643:             $displayed = $current;
 2644:             $rowtitle = &mt('Show earlier version:');
 2645:         }
 2646:         $result = '<div class="LC_left_float">';
 2647:         my $list;
 2648:         my $numversions = 0;
 2649:         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
 2650:             if ($i == $current) {
 2651:                 if (!$env{'form.previousversion'} || $nomenu) {
 2652:                     next;
 2653:                 } else {
 2654:                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
 2655:                     $numversions ++;
 2656:                 }
 2657:             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
 2658:                 unless ($i == $env{'form.previousversion'}) {
 2659:                     $numversions ++;
 2660:                 }
 2661:                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
 2662:             }
 2663:         }
 2664:         if ($numversions) {
 2665:             $symb = &HTML::Entities::encode($symb,'<>"&');
 2666:             $result .=
 2667:                 '<form name="getprev" method="post" action=""'.
 2668:                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
 2669:                 &Apache::loncommon::start_data_table().
 2670:                 &Apache::loncommon::start_data_table_row().
 2671:                 '<th align="left">'.$rowtitle.'</th>'.
 2672:                 '<td><select name="version">'.
 2673:                 '<option>'.&mt('Select').'</option>'.
 2674:                 $list.
 2675:                 '</select></td>'.
 2676:                 &Apache::loncommon::end_data_table_row();
 2677:             unless ($nomenu) {
 2678:                 $result .= &Apache::loncommon::start_data_table_row().
 2679:                 '<th align="left">'.&mt('Open in new window').'</th>'.
 2680:                 '<td><span class="LC_nobreak">'.
 2681:                 '<label><input type="radio" name="prevwin" value="1" />'.
 2682:                 &mt('Yes').'</label>'.
 2683:                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
 2684:                 '</span></td>'.
 2685:                 &Apache::loncommon::end_data_table_row();
 2686:             }
 2687:             $result .=
 2688:                 &Apache::loncommon::start_data_table_row().
 2689:                 '<th align="left">&nbsp;</th>'.
 2690:                 '<td>'.
 2691:                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
 2692:                 '</td>'.
 2693:                 &Apache::loncommon::end_data_table_row().
 2694:                 &Apache::loncommon::end_data_table().
 2695:                 '</form>';
 2696:             $js = &previous_display_javascript($nomenu,$current);
 2697:         } elsif ($displayed && $nomenu) {
 2698:             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
 2699:         } else {
 2700:             $result .= &mt('No previous versions to show for this student');
 2701:         }
 2702:         $result .= '</div>';
 2703:     }
 2704:     return ($current,$displayed,$result,$js);
 2705: }
 2706: 
 2707: sub previous_display_javascript {
 2708:     my ($nomenu,$current) = @_;
 2709:     my $js = <<"JSONE";
 2710: <script type="text/javascript">
 2711: // <![CDATA[
 2712: function previousVersion(uname,udom,symb) {
 2713:     var current = '$current';
 2714:     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
 2715:     var prevstr = new RegExp("^\\\\d+\$");
 2716:     if (!prevstr.test(version)) {
 2717:         return false;
 2718:     }
 2719:     var url = '';
 2720:     if (version == current) {
 2721:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
 2722:     } else {
 2723:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
 2724:     }
 2725: JSONE
 2726:     if ($nomenu) {
 2727:         $js .= <<"JSTWO";
 2728:     document.location.href = url;
 2729: JSTWO
 2730:     } else {
 2731:         $js .= <<"JSTHREE";
 2732:     var newwin = 0;
 2733:     for (var i=0; i<document.getprev.prevwin.length; i++) {
 2734:         if (document.getprev.prevwin[i].checked == true) {
 2735:             newwin = document.getprev.prevwin[i].value;
 2736:         }
 2737:     }
 2738:     if (newwin == 1) {
 2739:         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
 2740:         url = url+'&inhibitmenu=yes';
 2741:         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
 2742:             previousWin = window.open(url,'',options,1);
 2743:         } else {
 2744:             previousWin.location.href = url;
 2745:         }
 2746:         previousWin.focus();
 2747:         return false;
 2748:     } else {
 2749:         document.location.href = url;
 2750:         return false;
 2751:     }
 2752: JSTHREE
 2753:     }
 2754:     $js .= <<"ENDJS";
 2755:     return false;
 2756: }
 2757: // ]]>
 2758: </script>
 2759: ENDJS
 2760: 
 2761: }
 2762: 
 2763: #--- Called from submission routine
 2764: sub processHandGrade {
 2765:     my ($request,$symb) = @_;
 2766:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2767:     my $button = $env{'form.gradeOpt'};
 2768:     my $ngrade = $env{'form.NCT'};
 2769:     my $ntstu  = $env{'form.NTSTU'};
 2770:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2771:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 2772: 
 2773:     if ($button eq 'Save & Next') {
 2774: 	my $ctr = 0;
 2775: 	while ($ctr < $ngrade) {
 2776: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 2777: 	    my ($errorflag,$pts,$wgt,$numhidden) = 
 2778:                 &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 2779: 	    if ($errorflag eq 'no_score') {
 2780: 		$ctr++;
 2781: 		next;
 2782: 	    }
 2783: 	    if ($errorflag eq 'not_allowed') {
 2784: 		$request->print(
 2785:                     '<span class="LC_error">'
 2786:                    .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
 2787:                    .'</span>');
 2788: 		$ctr++;
 2789: 		next;
 2790: 	    }
 2791:             if ($numhidden) {
 2792:                 $request->print(
 2793:                     '<span class="LC_info">'
 2794:                    .&mt('For [_1]: [quant,_2,transaction] hidden',"$uname:$udom",$numhidden)
 2795:                    .'</span><br />');
 2796:             }
 2797: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 2798: 	    my ($subject,$message,$msgstatus) = ('','','');
 2799: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 2800:             my ($feedurl,$showsymb) =
 2801: 		&get_feedurl_and_symb($symb,$uname,$udom);
 2802: 	    my $messagetail;
 2803: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 2804: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 2805: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 2806: 		$subject.=' ['.$restitle.']';
 2807: 		my (@msgnum) = split(/,/,$includemsg);
 2808: 		foreach (@msgnum) {
 2809: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 2810: 		}
 2811: 		$message =&Apache::lonfeedback::clear_out_html($message);
 2812: 		if ($env{'form.withgrades'.$ctr}) {
 2813: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 2814: 		    $messagetail = " for <a href=\"".
 2815: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
 2816: 		}
 2817: 		$msgstatus = 
 2818:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 2819: 						     $message.$messagetail,
 2820:                                                      undef,$feedurl,undef,
 2821:                                                      undef,undef,$showsymb,
 2822:                                                      $restitle);
 2823: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
 2824: 				$msgstatus.'<br />');
 2825: 	    }
 2826: 	    if ($env{'form.collaborator'.$ctr}) {
 2827: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 2828: 		foreach my $collabstr (@collabstrs) {
 2829: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 2830: 		    foreach my $collaborator (@collaborators) {
 2831: 			my ($errorflag,$pts,$wgt) = 
 2832: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 2833: 					   $env{'form.unamedom'.$ctr},$part);
 2834: 			if ($errorflag eq 'not_allowed') {
 2835: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 2836: 			    next;
 2837: 			} elsif ($message ne '') {
 2838: 			    my ($baseurl,$showsymb) = 
 2839: 				&get_feedurl_and_symb($symb,$collaborator,
 2840: 						      $udom);
 2841: 			    if ($env{'form.withgrades'.$ctr}) {
 2842: 				$messagetail = " for <a href=\"".
 2843:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
 2844: 			    }
 2845: 			    $msgstatus = 
 2846: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 2847: 			}
 2848: 		    }
 2849: 		}
 2850: 	    }
 2851: 	    $ctr++;
 2852: 	}
 2853:     }
 2854: 
 2855: #    if ($env{'form.handgrade'} eq 'yes') {
 2856:     if (1) {
 2857: 	# Keywords sorted in alphabatical order
 2858: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2859: 	my %keyhash = ();
 2860: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 2861: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 2862: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 2863: 	$env{'form.keywords'} = join(' ',@keywords);
 2864: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 2865: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 2866: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 2867: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 2868: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 2869: 
 2870: 	# message center - Order of message gets changed. Blank line is eliminated.
 2871: 	# New messages are saved in env for the next student.
 2872: 	# All messages are saved in nohist_handgrade.db
 2873: 	my ($ctr,$idx) = (1,1);
 2874: 	while ($ctr <= $env{'form.savemsgN'}) {
 2875: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 2876: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 2877: 		$idx++;
 2878: 	    }
 2879: 	    $ctr++;
 2880: 	}
 2881: 	$ctr = 0;
 2882: 	while ($ctr < $ngrade) {
 2883: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 2884: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2885: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2886: 		$idx++;
 2887: 	    }
 2888: 	    $ctr++;
 2889: 	}
 2890: 	$env{'form.savemsgN'} = --$idx;
 2891: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 2892: 	my $putresult = &Apache::lonnet::put
 2893: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 2894:     }
 2895:     # Called by Save & Refresh from Highlight Attribute Window
 2896:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 2897:     if ($env{'form.refresh'} eq 'on') {
 2898: 	my ($ctr,$total) = (0,0);
 2899: 	while ($ctr < $ngrade) {
 2900: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 2901: 	    $ctr++;
 2902: 	}
 2903: 	$env{'form.NTSTU'}=$ngrade;
 2904: 	$ctr = 0;
 2905: 	while ($ctr < $total) {
 2906: 	    my $processUser = $env{'form.unamedom'.$ctr};
 2907: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2908: 	    $env{'form.fullname'} = $$fullname{$processUser};
 2909: 	    &submission($request,$ctr,$total-1,$symb);
 2910: 	    $ctr++;
 2911: 	}
 2912: 	return '';
 2913:     }
 2914: 
 2915:     # Get the next/previous one or group of students
 2916:     my $firststu = $env{'form.unamedom0'};
 2917:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 2918:     my $ctr = 2;
 2919:     while ($laststu eq '') {
 2920: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 2921: 	$ctr++;
 2922: 	$laststu = $firststu if ($ctr > $ngrade);
 2923:     }
 2924: 
 2925:     my (@parsedlist,@nextlist);
 2926:     my ($nextflg) = 0;
 2927:     foreach my $item (sort 
 2928: 	     {
 2929: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 2930: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 2931: 		 }
 2932: 		 return $a cmp $b;
 2933: 	     } (keys(%$fullname))) {
 2934: # FIXME: this is fishy, looks like the button label
 2935: 	if ($nextflg == 1 && $button =~ /Next$/) {
 2936: 	    push(@parsedlist,$item);
 2937: 	}
 2938: 	$nextflg = 1 if ($item eq $laststu);
 2939: 	if ($button eq 'Previous') {
 2940: 	    last if ($item eq $firststu);
 2941: 	    push(@parsedlist,$item);
 2942: 	}
 2943:     }
 2944:     $ctr = 0;
 2945: # FIXME: this is fishy, looks like the button label
 2946:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 2947:     my $res_error;
 2948:     my ($partlist) = &response_type($symb,\$res_error);
 2949:     if ($res_error) {
 2950:         $request->print(&navmap_errormsg());
 2951:         return;
 2952:     }
 2953:     foreach my $student (@parsedlist) {
 2954: 	my $submitonly=$env{'form.submitonly'};
 2955: 	my ($uname,$udom) = split(/:/,$student);
 2956: 	
 2957: 	if ($submitonly eq 'queued') {
 2958: 	    my %queue_status = 
 2959: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 2960: 							$udom,$uname);
 2961: 	    next if (!defined($queue_status{'gradingqueue'}));
 2962: 	}
 2963: 
 2964: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 2965: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2966: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 2967: 	    my $submitted = 0;
 2968: 	    my $ungraded = 0;
 2969: 	    my $incorrect = 0;
 2970: 	    foreach my $item (keys(%status)) {
 2971: 		$submitted = 1 if ($status{$item} ne 'nothing');
 2972: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 2973: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 2974: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 2975: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 2976: 		    $submitted = 0;
 2977: 		}
 2978: 	    }
 2979: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 2980: 				     $submitonly eq 'incorrect' ||
 2981: 				     $submitonly eq 'graded'));
 2982: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 2983: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 2984: 	}
 2985: 	push(@nextlist,$student) if ($ctr < $ntstu);
 2986: 	last if ($ctr == $ntstu);
 2987: 	$ctr++;
 2988:     }
 2989: 
 2990:     $ctr = 0;
 2991:     my $total = scalar(@nextlist)-1;
 2992: 
 2993:     foreach (sort(@nextlist)) {
 2994: 	my ($uname,$udom,$submitter) = split(/:/);
 2995: 	$env{'form.student'}  = $uname;
 2996: 	$env{'form.userdom'}  = $udom;
 2997: 	$env{'form.fullname'} = $$fullname{$_};
 2998: 	&submission($request,$ctr,$total,$symb);
 2999: 	$ctr++;
 3000:     }
 3001:     if ($total < 0) {
 3002: 	my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
 3003: 	$request->print($the_end);
 3004:     }
 3005:     return '';
 3006: }
 3007: 
 3008: #---- Save the score and award for each student, if changed
 3009: sub saveHandGrade {
 3010:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 3011:     my @version_parts;
 3012:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 3013: 					   $env{'request.course.id'});
 3014:     if (!&canmodify($usec)) { return('not_allowed'); }
 3015:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 3016:     my @parts_graded;
 3017:     my %newrecord  = ();
 3018:     my ($pts,$wgt,$totchg) = ('','',0);
 3019:     my %aggregate = ();
 3020:     my $aggregateflag = 0;
 3021:     if ($env{'form.HIDE'.$newflg}) {
 3022:         my $numchgs = &makehidden($newflg,\%record,$symb,$domain,$stuname);
 3023:         $totchg += $numchgs;
 3024:     }
 3025:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 3026:     foreach my $new_part (@parts) {
 3027: 	#collaborator ($submi may vary for different parts
 3028: 	if ($submitter && $new_part ne $part) { next; }
 3029: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 3030: 	if ($dropMenu eq 'excused') {
 3031: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 3032: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 3033: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 3034: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 3035: 		}
 3036: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3037: 	    }
 3038: 	} elsif ($dropMenu eq 'reset status'
 3039: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 3040: 	    foreach my $key (keys(%record)) {
 3041: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 3042: 	    }
 3043: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3044: 		"$env{'user.name'}:$env{'user.domain'}";
 3045:             my $totaltries = $record{'resource.'.$part.'.tries'};
 3046: 
 3047:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 3048: 					       [$new_part]);
 3049:             my $aggtries =$totaltries;
 3050:             if ($last_resets{$new_part}) {
 3051:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 3052: 					   $new_part);
 3053:             }
 3054: 
 3055:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 3056:             if ($aggtries > 0) {
 3057:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3058:                 $aggregateflag = 1;
 3059:             }
 3060: 	} elsif ($dropMenu eq '') {
 3061: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 3062: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 3063: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 3064: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 3065: 		next;
 3066: 	    }
 3067: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 3068: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 3069: 	    my $partial= $pts/$wgt;
 3070: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 3071: 		#do not update score for part if not changed.
 3072:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 3073: 		next;
 3074: 	    } else {
 3075: 	        push(@parts_graded,$new_part);
 3076: 	    }
 3077: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 3078: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 3079: 	    }
 3080: 	    my $reckey = 'resource.'.$new_part.'.solved';
 3081: 	    if ($partial == 0) {
 3082: 		if ($record{$reckey} ne 'incorrect_by_override') {
 3083: 		    $newrecord{$reckey} = 'incorrect_by_override';
 3084: 		}
 3085: 	    } else {
 3086: 		if ($record{$reckey} ne 'correct_by_override') {
 3087: 		    $newrecord{$reckey} = 'correct_by_override';
 3088: 		}
 3089: 	    }	    
 3090: 	    if ($submitter && 
 3091: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 3092: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 3093: 	    }
 3094: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3095: 		"$env{'user.name'}:$env{'user.domain'}";
 3096: 	}
 3097: 	# unless problem has been graded, set flag to version the submitted files
 3098: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 3099: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 3100: 	        $dropMenu eq 'reset status')
 3101: 	   {
 3102: 	    push(@version_parts,$new_part);
 3103: 	}
 3104:     }
 3105:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3106:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3107: 
 3108:     if (%newrecord) {
 3109:         if (@version_parts) {
 3110:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 3111:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 3112: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 3113: 	    foreach my $new_part (@version_parts) {
 3114: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 3115: 				$new_part,\%newrecord);
 3116: 	    }
 3117:         }
 3118: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 3119: 				$env{'request.course.id'},$domain,$stuname);
 3120: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 3121: 				     $cdom,$cnum,$domain,$stuname);
 3122:     }
 3123:     if ($aggregateflag) {
 3124:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3125: 			      $cdom,$cnum);
 3126:     }
 3127:     return ('',$pts,$wgt,$totchg);
 3128: }
 3129: 
 3130: sub makehidden {
 3131:     my ($newflg,$record,$symb,$domain,$stuname) = @_;
 3132:     return unless (ref($record) eq 'HASH');
 3133:     my %modified;
 3134:     my $numchanged = 0;
 3135:     my ($version,$parts) = split(/:/,$env{'form.HIDE'.$newflg},2);
 3136:     if (exists($record->{$version.':keys'})) {
 3137:         my $partsregexp = $parts;
 3138:         $partsregexp =~ s/,/|/g;
 3139:         foreach my $key (split(/\:/,$record->{$version.':keys'})) {
 3140:             if ($key =~ /^resource\.(?:$partsregexp)\.([^\.]+)$/) {
 3141:                  my $item = $1;
 3142:                  unless (($item eq 'solved') || ($item =~ /^award(|msg|ed)$/)) {
 3143:                      $modified{$key} = $record->{$version.':'.$key};
 3144:                  }
 3145:             } elsif ($key =~ m{^(resource\.(?:$partsregexp)\.[^\.]+\.)(.+)$}) {
 3146:                 $modified{$1.'hidden'.$2} = $record->{$version.':'.$key};
 3147:             } elsif ($key =~ /^(ip|timestamp|host)$/) {
 3148:                 $modified{$key} = $record->{$version.':'.$key};
 3149:             }
 3150:         }
 3151:         if (keys(%modified)) {
 3152:             if (&Apache::lonnet::putstore($env{'request.course.id'},$symb,$version,\%modified,
 3153:                                           $domain,$stuname) eq 'ok') {
 3154:                 $numchanged ++;
 3155:             }
 3156:         }
 3157:     }
 3158:     return $numchanged;
 3159: }
 3160: 
 3161: sub check_and_remove_from_queue {
 3162:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 3163:     my @ungraded_parts;
 3164:     foreach my $part (@{$parts}) {
 3165: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 3166: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 3167: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 3168: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 3169: 		) {
 3170: 	    push(@ungraded_parts, $part);
 3171: 	}
 3172:     }
 3173:     if ( !@ungraded_parts ) {
 3174: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 3175: 					       $cnum,$domain,$stuname);
 3176:     }
 3177: }
 3178: 
 3179: sub handback_files {
 3180:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 3181:     my $portfolio_root = '/userfiles/portfolio';
 3182:     my $res_error;
 3183:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3184:     if ($res_error) {
 3185:         $request->print('<br />'.&navmap_errormsg().'<br />');
 3186:         return;
 3187:     }
 3188:     my @handedback;
 3189:     my $file_msg;
 3190:     my @part_response_id = &flatten_responseType($responseType);
 3191:     foreach my $part_response_id (@part_response_id) {
 3192:     	my ($part_id,$resp_id) = @{ $part_response_id };
 3193: 	my $part_resp = join('_',@{ $part_response_id });
 3194:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
 3195:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
 3196:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3' 
 3197:                 if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
 3198:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
 3199:                     my ($directory,$answer_file) = 
 3200:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
 3201:                     my ($answer_name,$answer_ver,$answer_ext) =
 3202: 		        &file_name_version_ext($answer_file);
 3203: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 3204:                     my $getpropath = 1;
 3205:                     my ($dir_list,$listerror) = 
 3206:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
 3207:                                                  $domain,$stuname,$getpropath);
 3208: 		    my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
 3209:                     # fix filename
 3210:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 3211:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 3212:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
 3213:             	                                $save_file_name);
 3214:                     if ($result !~ m|^/uploaded/|) {
 3215:                         $request->print('<br /><span class="LC_error">'.
 3216:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 3217:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
 3218:                                         '</span>');
 3219:                     } else {
 3220:                         # mark the file as read only
 3221:                         push(@handedback,$save_file_name);
 3222: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 3223: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 3224: 			}
 3225:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 3226: 			$file_msg.= '<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
 3227:                     }
 3228:                     $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>'));
 3229:                 }
 3230:             }
 3231:         }
 3232:     }
 3233:     if (@handedback > 0) {
 3234:         $request->print('<br />');
 3235:         my @what = ($symb,$env{'request.course.id'},'handback');
 3236:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
 3237:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});    
 3238:         my ($subject,$message);
 3239:         if (scalar(@handedback) == 1) {
 3240:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
 3241:             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
 3242:         } else {
 3243:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
 3244:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
 3245:         }
 3246:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
 3247:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
 3248:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
 3249:         my ($feedurl,$showsymb) =
 3250:             &get_feedurl_and_symb($symb,$domain,$stuname);
 3251:         my $restitle = &Apache::lonnet::gettitle($symb);
 3252:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
 3253:         my $msgstatus =
 3254:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
 3255:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
 3256:                  $restitle);
 3257:         if ($msgstatus) {
 3258:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
 3259:         }
 3260:     }
 3261:     return;
 3262: }
 3263: 
 3264: sub get_feedurl_and_symb {
 3265:     my ($symb,$uname,$udom) = @_;
 3266:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3267:     $url = &Apache::lonnet::clutter($url);
 3268:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 3269: 					$symb,$udom,$uname);
 3270:     if ($encrypturl =~ /^yes$/i) {
 3271: 	&Apache::lonenc::encrypted(\$url,1);
 3272: 	&Apache::lonenc::encrypted(\$symb,1);
 3273:     }
 3274:     return ($url,$symb);
 3275: }
 3276: 
 3277: sub get_submitted_files {
 3278:     my ($udom,$uname,$partid,$respid,$record) = @_;
 3279:     my @files;
 3280:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 3281:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 3282:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 3283:     	    push(@files,$file_url.$file);
 3284:         }
 3285:     }
 3286:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 3287:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 3288:     }
 3289:     return (\@files);
 3290: }
 3291: 
 3292: # ----------- Provides number of tries since last reset.
 3293: sub get_num_tries {
 3294:     my ($record,$last_reset,$part) = @_;
 3295:     my $timestamp = '';
 3296:     my $num_tries = 0;
 3297:     if ($$record{'version'}) {
 3298:         for (my $version=$$record{'version'};$version>=1;$version--) {
 3299:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 3300:                 $timestamp = $$record{$version.':timestamp'};
 3301:                 if ($timestamp > $last_reset) {
 3302:                     $num_tries ++;
 3303:                 } else {
 3304:                     last;
 3305:                 }
 3306:             }
 3307:         }
 3308:     }
 3309:     return $num_tries;
 3310: }
 3311: 
 3312: # ----------- Determine decrements required in aggregate totals 
 3313: sub decrement_aggs {
 3314:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 3315:     my %decrement = (
 3316:                         attempts => 0,
 3317:                         users => 0,
 3318:                         correct => 0
 3319:                     );
 3320:     $decrement{'attempts'} = $aggtries;
 3321:     if ($solvedstatus =~ /^correct/) {
 3322:         $decrement{'correct'} = 1;
 3323:     }
 3324:     if ($aggtries == $totaltries) {
 3325:         $decrement{'users'} = 1;
 3326:     }
 3327:     foreach my $type (keys(%decrement)) {
 3328:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 3329:     }
 3330:     return;
 3331: }
 3332: 
 3333: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 3334: sub get_last_resets {
 3335:     my ($symb,$courseid,$partids) =@_;
 3336:     my %last_resets;
 3337:     my $cdom = $env{'course.'.$courseid.'.domain'};
 3338:     my $cname = $env{'course.'.$courseid.'.num'};
 3339:     my @keys;
 3340:     foreach my $part (@{$partids}) {
 3341: 	push(@keys,"$symb\0$part\0resettime");
 3342:     }
 3343:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 3344: 				     $cdom,$cname);
 3345:     foreach my $part (@{$partids}) {
 3346: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 3347:     }
 3348:     return %last_resets;
 3349: }
 3350: 
 3351: # ----------- Handles creating versions for portfolio files as answers
 3352: sub version_portfiles {
 3353:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 3354:     my $version_parts = join('|',@$v_flag);
 3355:     my @returned_keys;
 3356:     my $parts = join('|', @$parts_graded);
 3357:     my $portfolio_root = '/userfiles/portfolio';
 3358:     foreach my $key (keys(%$record)) {
 3359:         my $new_portfiles;
 3360:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 3361:             my @versioned_portfiles;
 3362:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 3363:             foreach my $file (@portfiles) {
 3364:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 3365:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 3366: 		my ($answer_name,$answer_ver,$answer_ext) =
 3367: 		    &file_name_version_ext($answer_file);
 3368:                 my $getpropath = 1;    
 3369:                 my ($dir_list,$listerror) = 
 3370:                     &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,
 3371:                                              $stu_name,$getpropath);
 3372:                 my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
 3373:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
 3374:                 if ($new_answer ne 'problem getting file') {
 3375:                     push(@versioned_portfiles, $directory.$new_answer);
 3376:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
 3377:                         [$directory.$new_answer],
 3378:                         [$symb,$env{'request.course.id'},'graded']);
 3379:                 }
 3380:             }
 3381:             $$record{$key} = join(',',@versioned_portfiles);
 3382:             push(@returned_keys,$key);
 3383:         }
 3384:     } 
 3385:     return (@returned_keys);   
 3386: }
 3387: 
 3388: sub get_next_version {
 3389:     my ($answer_name, $answer_ext, $dir_list) = @_;
 3390:     my $version;
 3391:     if (ref($dir_list) eq 'ARRAY') {
 3392:         foreach my $row (@{$dir_list}) {
 3393:             my ($file) = split(/\&/,$row,2);
 3394:             my ($file_name,$file_version,$file_ext) =
 3395: 	        &file_name_version_ext($file);
 3396:             if (($file_name eq $answer_name) && 
 3397: 	        ($file_ext eq $answer_ext)) {
 3398:                      # gets here if filename and extension match, 
 3399:                      # regardless of version
 3400:                 if ($file_version ne '') {
 3401:                     # a versioned file is found  so save it for later
 3402:                     if ($file_version > $version) {
 3403: 		        $version = $file_version;
 3404: 	            }
 3405:                 }
 3406:             }
 3407:         }
 3408:     }
 3409:     $version ++;
 3410:     return($version);
 3411: }
 3412: 
 3413: sub version_selected_portfile {
 3414:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 3415:     my ($answer_name,$answer_ver,$answer_ext) =
 3416:         &file_name_version_ext($file_name);
 3417:     my $new_answer;
 3418:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 3419:     if($env{'form.copy'} eq '-1') {
 3420:         $new_answer = 'problem getting file';
 3421:     } else {
 3422:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 3423:         my $copy_result = &Apache::lonnet::finishuserfileupload(
 3424:                             $stu_name,$domain,'copy',
 3425: 		        '/portfolio'.$directory.$new_answer);
 3426:     }    
 3427:     return ($new_answer);
 3428: }
 3429: 
 3430: sub file_name_version_ext {
 3431:     my ($file)=@_;
 3432:     my @file_parts = split(/\./, $file);
 3433:     my ($name,$version,$ext);
 3434:     if (@file_parts > 1) {
 3435: 	$ext=pop(@file_parts);
 3436: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 3437: 	    $version=pop(@file_parts);
 3438: 	}
 3439: 	$name=join('.',@file_parts);
 3440:     } else {
 3441: 	$name=join('.',@file_parts);
 3442:     }
 3443:     return($name,$version,$ext);
 3444: }
 3445: 
 3446: #--------------------------------------------------------------------------------------
 3447: #
 3448: #-------------------------- Next few routines handles grading by section or whole class
 3449: #
 3450: #--- Javascript to handle grading by section or whole class
 3451: sub viewgrades_js {
 3452:     my ($request) = shift;
 3453: 
 3454:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3455:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
 3456:    function writePoint(partid,weight,point) {
 3457: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3458: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3459: 	if (point == "textval") {
 3460: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3461: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3462: 		alert("$alertmsg"+parseFloat(point));
 3463: 		var resetbox = false;
 3464: 		for (var i=0; i<radioButton.length; i++) {
 3465: 		    if (radioButton[i].checked) {
 3466: 			textbox.value = i;
 3467: 			resetbox = true;
 3468: 		    }
 3469: 		}
 3470: 		if (!resetbox) {
 3471: 		    textbox.value = "";
 3472: 		}
 3473: 		return;
 3474: 	    }
 3475: 	    if (parseFloat(point) > parseFloat(weight)) {
 3476: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3477: 				   ") greater than the weight for the part. Accept?");
 3478: 		if (resp == false) {
 3479: 		    textbox.value = "";
 3480: 		    return;
 3481: 		}
 3482: 	    }
 3483: 	    for (var i=0; i<radioButton.length; i++) {
 3484: 		radioButton[i].checked=false;
 3485: 		if (parseFloat(point) == i) {
 3486: 		    radioButton[i].checked=true;
 3487: 		}
 3488: 	    }
 3489: 
 3490: 	} else {
 3491: 	    textbox.value = parseFloat(point);
 3492: 	}
 3493: 	for (i=0;i<document.classgrade.total.value;i++) {
 3494: 	    var user = document.classgrade["ctr"+i].value;
 3495: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3496: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3497: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3498: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3499: 	    if (saveval != "correct") {
 3500: 		scorename.value = point;
 3501: 		if (selname[0].selected != true) {
 3502: 		    selname[0].selected = true;
 3503: 		}
 3504: 	    }
 3505: 	}
 3506: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3507:     }
 3508: 
 3509:     function writeRadText(partid,weight) {
 3510: 	var selval   = document.classgrade["SELVAL_"+partid];
 3511: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3512:         var override = document.classgrade["FORCE_"+partid].checked;
 3513: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3514: 	if (selval[1].selected || selval[2].selected) {
 3515: 	    for (var i=0; i<radioButton.length; i++) {
 3516: 		radioButton[i].checked=false;
 3517: 
 3518: 	    }
 3519: 	    textbox.value = "";
 3520: 
 3521: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3522: 		var user = document.classgrade["ctr"+i].value;
 3523: 		user = user.replace(new RegExp(':', 'g'),"_");
 3524: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3525: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3526: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3527: 		if ((saveval != "correct") || override) {
 3528: 		    scorename.value = "";
 3529: 		    if (selval[1].selected) {
 3530: 			selname[1].selected = true;
 3531: 		    } else {
 3532: 			selname[2].selected = true;
 3533: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3534: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3535: 		    }
 3536: 		}
 3537: 	    }
 3538: 	} else {
 3539: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3540: 		var user = document.classgrade["ctr"+i].value;
 3541: 		user = user.replace(new RegExp(':', 'g'),"_");
 3542: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3543: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3544: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3545: 		if ((saveval != "correct") || override) {
 3546: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3547: 		    selname[0].selected = true;
 3548: 		}
 3549: 	    }
 3550: 	}	    
 3551:     }
 3552: 
 3553:     function changeSelect(partid,user) {
 3554: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3555: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3556: 	var point  = textbox.value;
 3557: 	var weight = document.classgrade["weight_"+partid].value;
 3558: 
 3559: 	if (isNaN(point) || parseFloat(point) < 0) {
 3560: 	    alert("$alertmsg"+parseFloat(point));
 3561: 	    textbox.value = "";
 3562: 	    return;
 3563: 	}
 3564: 	if (parseFloat(point) > parseFloat(weight)) {
 3565: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3566: 			       ") greater than the weight of the part. Accept?");
 3567: 	    if (resp == false) {
 3568: 		textbox.value = "";
 3569: 		return;
 3570: 	    }
 3571: 	}
 3572: 	selval[0].selected = true;
 3573:     }
 3574: 
 3575:     function changeOneScore(partid,user) {
 3576: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3577: 	if (selval[1].selected || selval[2].selected) {
 3578: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3579: 	    if (selval[2].selected) {
 3580: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3581: 	    }
 3582:         }
 3583:     }
 3584: 
 3585:     function resetEntry(numpart) {
 3586: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3587: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3588: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3589: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3590: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3591: 	    for (var i=0; i<radioButton.length; i++) {
 3592: 		radioButton[i].checked=false;
 3593: 
 3594: 	    }
 3595: 	    textbox.value = "";
 3596: 	    selval[0].selected = true;
 3597: 
 3598: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3599: 		var user = document.classgrade["ctr"+i].value;
 3600: 		user = user.replace(new RegExp(':', 'g'),"_");
 3601: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3602: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3603: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3604: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3605: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3606: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3607: 		if (saveselval == "excused") {
 3608: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3609: 		} else {
 3610: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3611: 		}
 3612: 	    }
 3613: 	}
 3614:     }
 3615: 
 3616: VIEWJAVASCRIPT
 3617: }
 3618: 
 3619: #--- show scores for a section or whole class w/ option to change/update a score
 3620: sub viewgrades {
 3621:     my ($request,$symb) = @_;
 3622:     &viewgrades_js($request);
 3623: 
 3624:     #need to make sure we have the correct data for later EXT calls, 
 3625:     #thus invalidate the cache
 3626:     &Apache::lonnet::devalidatecourseresdata(
 3627:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3628:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3629:     &Apache::lonnet::clear_EXT_cache_status();
 3630: 
 3631:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3632: 
 3633:     #view individual student submission form - called using Javascript viewOneStudent
 3634:     $result.=&jscriptNform($symb);
 3635: 
 3636:     #beginning of class grading form
 3637:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3638:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3639: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3640: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3641: 	&build_section_inputs().
 3642: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3643: 
 3644:     my ($common_header,$specific_header);
 3645:     if ($env{'form.section'} eq 'all') {
 3646: 	$common_header = &mt('Assign Common Grade to Class');
 3647:         $specific_header = &mt('Assign Grade to Specific Students in Class');
 3648:     } elsif ($env{'form.section'} eq 'none') {
 3649:         $common_header = &mt('Assign Common Grade to Students in no Section');
 3650: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
 3651:     } else {
 3652:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3653:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
 3654: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
 3655:     }
 3656:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
 3657:     #radio buttons/text box for assigning points for a section or class.
 3658:     #handles different parts of a problem
 3659:     my $res_error;
 3660:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3661:     if ($res_error) {
 3662:         return &navmap_errormsg();
 3663:     }
 3664:     my %weight = ();
 3665:     my $ctsparts = 0;
 3666:     my %seen = ();
 3667:     my @part_response_id = &flatten_responseType($responseType);
 3668:     foreach my $part_response_id (@part_response_id) {
 3669:     	my ($partid,$respid) = @{ $part_response_id };
 3670: 	my $part_resp = join('_',@{ $part_response_id });
 3671: 	next if $seen{$partid};
 3672: 	$seen{$partid}++;
 3673: 	my $handgrade=$$handgrade{$part_resp};
 3674: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 3675: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 3676: 
 3677: 	my $display_part=&get_display_part($partid,$symb);
 3678: 	my $radio.='<table border="0"><tr>';  
 3679: 	my $ctr = 0;
 3680: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 3681: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 3682: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 3683: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 3684: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 3685: 	    $ctr++;
 3686: 	}
 3687: 	$radio.='</tr></table>';
 3688: 	my $line = '<input type="text" name="TEXTVAL_'.
 3689: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
 3690: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 3691: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 3692:         $line.= '<td><b>'.&mt('Grade Status').':</b>'.
 3693:             '<select name="SELVAL_'.$partid.'" '.
 3694:             'onchange="javascript:writeRadText(\''.$partid.'\','.
 3695:                 $weight{$partid}.')"> '.
 3696: 	    '<option selected="selected"> </option>'.
 3697: 	    '<option value="excused">'.&mt('excused').'</option>'.
 3698: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 3699: 	    '</select></td>'.
 3700:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 3701: 	$line.='<input type="hidden" name="partid_'.
 3702: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 3703: 	$line.='<input type="hidden" name="weight_'.
 3704: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 3705: 
 3706: 	$result.=
 3707: 	    &Apache::loncommon::start_data_table_row()."\n".
 3708: 	    '<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>'.
 3709: 	    &Apache::loncommon::end_data_table_row()."\n";
 3710: 	$ctsparts++;
 3711:     }
 3712:     $result.=&Apache::loncommon::end_data_table()."\n".
 3713: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 3714:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 3715: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
 3716: 
 3717:     #table listing all the students in a section/class
 3718:     #header of table
 3719:     $result.= '<h3>'.$specific_header.'</h3>'.
 3720:               &Apache::loncommon::start_data_table().
 3721: 	      &Apache::loncommon::start_data_table_header_row().
 3722: 	      '<th>'.&mt('No.').'</th>'.
 3723: 	      '<th>'.&nameUserString('header')."</th>\n";
 3724:     my $partserror;
 3725:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3726:     if ($partserror) {
 3727:         return &navmap_errormsg();
 3728:     }
 3729:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 3730:     my @partids = ();
 3731:     foreach my $part (@parts) {
 3732: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3733:         my $narrowtext = &mt('Tries');
 3734: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 3735: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 3736: 	my ($partid) = &split_part_type($part);
 3737:         push(@partids,$partid);
 3738: #
 3739: # FIXME: Looks like $display looks at English text
 3740: #
 3741: 	my $display_part=&get_display_part($partid,$symb);
 3742: 	if ($display =~ /^Partial Credit Factor/) {
 3743: 	    $result.='<th>'.
 3744: 		&mt('Score Part: [_1][_2](weight = [_3])',
 3745: 		    $display_part,'<br />',$weight{$partid}).'</th>'."\n";
 3746: 	    next;
 3747: 	    
 3748: 	} else {
 3749: 	    if ($display =~ /Problem Status/) {
 3750: 		my $grade_status_mt = &mt('Grade Status');
 3751: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 3752: 	    }
 3753: 	    my $part_mt = &mt('Part:');
 3754: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 3755: 	}
 3756: 
 3757: 	$result.='<th>'.$display.'</th>'."\n";
 3758:     }
 3759:     $result.=&Apache::loncommon::end_data_table_header_row();
 3760: 
 3761:     my %last_resets = 
 3762: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 3763: 
 3764:     #get info for each student
 3765:     #list all the students - with points and grade status
 3766:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3767:     my $ctr = 0;
 3768:     foreach (sort 
 3769: 	     {
 3770: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3771: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3772: 		 }
 3773: 		 return $a cmp $b;
 3774: 	     } (keys(%$fullname))) {
 3775: 	$ctr++;
 3776: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 3777: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
 3778:     }
 3779:     $result.=&Apache::loncommon::end_data_table();
 3780:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 3781:     $result.='<input type="button" value="'.&mt('Save').'" '.
 3782: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
 3783:     if (scalar(%$fullname) eq 0) {
 3784: 	my $colspan=3+scalar(@parts);
 3785: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3786:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 3787: 	$result='<span class="LC_warning">'.
 3788: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 3789: 	        $section_display, $stu_status).
 3790: 	    '</span>';
 3791:     }
 3792:     return $result;
 3793: }
 3794: 
 3795: #--- call by previous routine to display each student
 3796: sub viewstudentgrade {
 3797:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 3798:     my ($uname,$udom) = split(/:/,$student);
 3799:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 3800:     my %aggregates = (); 
 3801:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 3802: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
 3803: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
 3804: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 3805: 	'\');" target="_self">'.$fullname.'</a> '.
 3806: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 3807:     $student=~s/:/_/; # colon doen't work in javascript for names
 3808:     foreach my $apart (@$parts) {
 3809: 	my ($part,$type) = &split_part_type($apart);
 3810: 	my $score=$record{"resource.$part.$type"};
 3811:         $result.='<td align="center">';
 3812:         my ($aggtries,$totaltries);
 3813:         unless (exists($aggregates{$part})) {
 3814: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 3815: 
 3816: 	    $aggtries = $totaltries;
 3817:             if ($$last_resets{$part}) {  
 3818:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 3819: 					   $part);
 3820:             }
 3821:             $result.='<input type="hidden" name="'.
 3822:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 3823:             $result.='<input type="hidden" name="'.
 3824:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 3825:             $aggregates{$part} = 1;
 3826:         }
 3827: 	if ($type eq 'awarded') {
 3828: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 3829: 	    $result.='<input type="hidden" name="'.
 3830: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 3831: 	    $result.='<input type="text" name="'.
 3832: 		'GD_'.$student.'_'.$part.'_awarded" '.
 3833:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
 3834: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 3835: 	} elsif ($type eq 'solved') {
 3836: 	    my ($status,$foo)=split(/_/,$score,2);
 3837: 	    $status = 'nothing' if ($status eq '');
 3838: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 3839: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 3840: 	    $result.='&nbsp;<select name="'.
 3841: 		'GD_'.$student.'_'.$part.'_solved" '.
 3842:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 3843: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 3844: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 3845: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 3846: 	    $result.="</select>&nbsp;</td>\n";
 3847: 	} else {
 3848: 	    $result.='<input type="hidden" name="'.
 3849: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 3850: 		    "\n";
 3851: 	    $result.='<input type="text" name="'.
 3852: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 3853: 		'value="'.$score.'" size="4" /></td>'."\n";
 3854: 	}
 3855:     }
 3856:     $result.=&Apache::loncommon::end_data_table_row();
 3857:     return $result;
 3858: }
 3859: 
 3860: #--- change scores for all the students in a section/class
 3861: #    record does not get update if unchanged
 3862: sub editgrades {
 3863:     my ($request,$symb) = @_;
 3864: 
 3865:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3866:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 3867:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
 3868: 
 3869:     my $result= &Apache::loncommon::start_data_table().
 3870: 	&Apache::loncommon::start_data_table_header_row().
 3871: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 3872: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 3873:     my %scoreptr = (
 3874: 		    'correct'  =>'correct_by_override',
 3875: 		    'incorrect'=>'incorrect_by_override',
 3876: 		    'excused'  =>'excused',
 3877: 		    'ungraded' =>'ungraded_attempted',
 3878:                     'credited' =>'credit_attempted',
 3879: 		    'nothing'  => '',
 3880: 		    );
 3881:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 3882: 
 3883:     my (@partid);
 3884:     my %weight = ();
 3885:     my %columns = ();
 3886:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 3887: 
 3888:     my $partserror;
 3889:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3890:     if ($partserror) {
 3891:         return &navmap_errormsg();
 3892:     }
 3893:     my $header;
 3894:     while ($ctr < $env{'form.totalparts'}) {
 3895: 	my $partid = $env{'form.partid_'.$ctr};
 3896: 	push(@partid,$partid);
 3897: 	$weight{$partid} = $env{'form.weight_'.$partid};
 3898: 	$ctr++;
 3899:     }
 3900:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3901:     foreach my $partid (@partid) {
 3902: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 3903: 	    '<th align="center">'.&mt('New Score').'</th>';
 3904: 	$columns{$partid}=2;
 3905: 	foreach my $stores (@parts) {
 3906: 	    my ($part,$type) = &split_part_type($stores);
 3907: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 3908: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 3909: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 3910: 	    $display =~ s/\[Part: \Q$part\E\]//;
 3911:             my $narrowtext = &mt('Tries');
 3912: 	    $display =~ s/Number of Attempts/$narrowtext/;
 3913: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 3914: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 3915: 	    $columns{$partid}+=2;
 3916: 	}
 3917:     }
 3918:     foreach my $partid (@partid) {
 3919: 	my $display_part=&get_display_part($partid,$symb);
 3920: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 3921: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 3922: 	    '</th>';
 3923: 
 3924:     }
 3925:     $result .= &Apache::loncommon::end_data_table_header_row().
 3926: 	&Apache::loncommon::start_data_table_header_row().
 3927: 	$header.
 3928: 	&Apache::loncommon::end_data_table_header_row();
 3929:     my @noupdate;
 3930:     my ($updateCtr,$noupdateCtr) = (1,1);
 3931:     for ($i=0; $i<$env{'form.total'}; $i++) {
 3932: 	my $line;
 3933: 	my $user = $env{'form.ctr'.$i};
 3934: 	my ($uname,$udom)=split(/:/,$user);
 3935: 	my %newrecord;
 3936: 	my $updateflag = 0;
 3937: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 3938: 	my $usec=$classlist->{"$uname:$udom"}[5];
 3939: 	if (!&canmodify($usec)) {
 3940: 	    my $numcols=scalar(@partid)*4+2;
 3941: 	    push(@noupdate,
 3942: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
 3943: 		 &mt('Not allowed to modify student')."</span></td></tr>");
 3944: 	    next;
 3945: 	}
 3946:         my %aggregate = ();
 3947:         my $aggregateflag = 0;
 3948: 	$user=~s/:/_/; # colon doen't work in javascript for names
 3949: 	foreach (@partid) {
 3950: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 3951: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 3952: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 3953: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3954: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 3955: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 3956: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 3957: 	    my $score;
 3958: 	    if ($partial eq '') {
 3959: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3960: 	    } elsif ($partial > 0) {
 3961: 		$score = 'correct_by_override';
 3962: 	    } elsif ($partial == 0) {
 3963: 		$score = 'incorrect_by_override';
 3964: 	    }
 3965: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 3966: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 3967: 
 3968: 	    $newrecord{'resource.'.$_.'.regrader'}=
 3969: 		"$env{'user.name'}:$env{'user.domain'}";
 3970: 	    if ($dropMenu eq 'reset status' &&
 3971: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 3972: 		$newrecord{'resource.'.$_.'.tries'} = '';
 3973: 		$newrecord{'resource.'.$_.'.solved'} = '';
 3974: 		$newrecord{'resource.'.$_.'.award'} = '';
 3975: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 3976: 		$updateflag = 1;
 3977:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 3978:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 3979:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 3980:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 3981:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3982:                     $aggregateflag = 1;
 3983:                 }
 3984: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 3985: 		$updateflag = 1;
 3986: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 3987: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 3988: 		$rec_update++;
 3989: 	    }
 3990: 
 3991: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3992: 		'<td align="center">'.$awarded.
 3993: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 3994: 
 3995: 
 3996: 	    my $partid=$_;
 3997: 	    foreach my $stores (@parts) {
 3998: 		my ($part,$type) = &split_part_type($stores);
 3999: 		if ($part !~ m/^\Q$partid\E/) { next;}
 4000: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 4001: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 4002: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 4003: 		if ($awarded ne '' && $awarded ne $old_aw) {
 4004: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 4005: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 4006: 		    $updateflag=1;
 4007: 		}
 4008: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 4009: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 4010: 	    }
 4011: 	}
 4012: 	$line.="\n";
 4013: 
 4014: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4015: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4016: 
 4017: 	if ($updateflag) {
 4018: 	    $count++;
 4019: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 4020: 				    $udom,$uname);
 4021: 
 4022: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 4023: 					      $cnum,$udom,$uname)) {
 4024: 		# need to figure out if should be in queue.
 4025: 		my %record =  
 4026: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 4027: 					     $udom,$uname);
 4028: 		my $all_graded = 1;
 4029: 		my $none_graded = 1;
 4030: 		foreach my $part (@parts) {
 4031: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 4032: 			$all_graded = 0;
 4033: 		    } else {
 4034: 			$none_graded = 0;
 4035: 		    }
 4036: 		}
 4037: 
 4038: 		if ($all_graded || $none_graded) {
 4039: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 4040: 							   $symb,$cdom,$cnum,
 4041: 							   $udom,$uname);
 4042: 		}
 4043: 	    }
 4044: 
 4045: 	    $result.=&Apache::loncommon::start_data_table_row().
 4046: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 4047: 		&Apache::loncommon::end_data_table_row();
 4048: 	    $updateCtr++;
 4049: 	} else {
 4050: 	    push(@noupdate,
 4051: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 4052: 	    $noupdateCtr++;
 4053: 	}
 4054:         if ($aggregateflag) {
 4055:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4056: 				  $cdom,$cnum);
 4057:         }
 4058:     }
 4059:     if (@noupdate) {
 4060: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
 4061: 	my $numcols=scalar(@partid)*4+2;
 4062: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 4063: 	    '<td align="center" colspan="'.$numcols.'">'.
 4064: 	    &mt('No Changes Occurred For the Students Below').
 4065: 	    '</td>'.
 4066: 	    &Apache::loncommon::end_data_table_row();
 4067: 	foreach my $line (@noupdate) {
 4068: 	    $result.=
 4069: 		&Apache::loncommon::start_data_table_row().
 4070: 		$line.
 4071: 		&Apache::loncommon::end_data_table_row();
 4072: 	}
 4073:     }
 4074:     $result .= &Apache::loncommon::end_data_table();
 4075:     my $msg = '<p><b>'.
 4076: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 4077: 	    $rec_update,$count).'</b><br />'.
 4078: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 4079: 	'</b></p>';
 4080:     return $title.$msg.$result;
 4081: }
 4082: 
 4083: sub split_part_type {
 4084:     my ($partstr) = @_;
 4085:     my ($temp,@allparts)=split(/_/,$partstr);
 4086:     my $type=pop(@allparts);
 4087:     my $part=join('_',@allparts);
 4088:     return ($part,$type);
 4089: }
 4090: 
 4091: #------------- end of section for handling grading by section/class ---------
 4092: #
 4093: #----------------------------------------------------------------------------
 4094: 
 4095: 
 4096: #----------------------------------------------------------------------------
 4097: #
 4098: #-------------------------- Next few routines handles grading by csv upload
 4099: #
 4100: #--- Javascript to handle csv upload
 4101: sub csvupload_javascript_reverse_associate {
 4102:     my $error1=&mt('You need to specify the username or the student/employee ID');
 4103:     my $error2=&mt('You need to specify at least one grading field');
 4104:   return(<<ENDPICK);
 4105:   function verify(vf) {
 4106:     var foundsomething=0;
 4107:     var founduname=0;
 4108:     var foundID=0;
 4109:     for (i=0;i<=vf.nfields.value;i++) {
 4110:       tw=eval('vf.f'+i+'.selectedIndex');
 4111:       if (i==0 && tw!=0) { foundID=1; }
 4112:       if (i==1 && tw!=0) { founduname=1; }
 4113:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 4114:     }
 4115:     if (founduname==0 && foundID==0) {
 4116: 	alert('$error1');
 4117: 	return;
 4118:     }
 4119:     if (foundsomething==0) {
 4120: 	alert('$error2');
 4121: 	return;
 4122:     }
 4123:     vf.submit();
 4124:   }
 4125:   function flip(vf,tf) {
 4126:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4127:     var i;
 4128:     for (i=0;i<=vf.nfields.value;i++) {
 4129:       //can not pick the same destination field for both name and domain
 4130:       if (((i ==0)||(i ==1)) && 
 4131:           ((tf==0)||(tf==1)) && 
 4132:           (i!=tf) &&
 4133:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4134:         eval('vf.f'+i+'.selectedIndex=0;')
 4135:       }
 4136:     }
 4137:   }
 4138: ENDPICK
 4139: }
 4140: 
 4141: sub csvupload_javascript_forward_associate {
 4142:     my $error1=&mt('You need to specify the username or the student/employee ID');
 4143:     my $error2=&mt('You need to specify at least one grading field');
 4144:   return(<<ENDPICK);
 4145:   function verify(vf) {
 4146:     var foundsomething=0;
 4147:     var founduname=0;
 4148:     var foundID=0;
 4149:     for (i=0;i<=vf.nfields.value;i++) {
 4150:       tw=eval('vf.f'+i+'.selectedIndex');
 4151:       if (tw==1) { foundID=1; }
 4152:       if (tw==2) { founduname=1; }
 4153:       if (tw>3) { foundsomething=1; }
 4154:     }
 4155:     if (founduname==0 && foundID==0) {
 4156: 	alert('$error1');
 4157: 	return;
 4158:     }
 4159:     if (foundsomething==0) {
 4160: 	alert('$error2');
 4161: 	return;
 4162:     }
 4163:     vf.submit();
 4164:   }
 4165:   function flip(vf,tf) {
 4166:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4167:     var i;
 4168:     //can not pick the same destination field twice
 4169:     for (i=0;i<=vf.nfields.value;i++) {
 4170:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4171:         eval('vf.f'+i+'.selectedIndex=0;')
 4172:       }
 4173:     }
 4174:   }
 4175: ENDPICK
 4176: }
 4177: 
 4178: sub csvuploadmap_header {
 4179:     my ($request,$symb,$datatoken,$distotal)= @_;
 4180:     my $javascript;
 4181:     if ($env{'form.upfile_associate'} eq 'reverse') {
 4182: 	$javascript=&csvupload_javascript_reverse_associate();
 4183:     } else {
 4184: 	$javascript=&csvupload_javascript_forward_associate();
 4185:     }
 4186: 
 4187:     $symb = &Apache::lonenc::check_encrypt($symb);
 4188:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
 4189:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
 4190:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
 4191:     my $reverse=&mt("Reverse Association");
 4192:     $request->print(<<ENDPICK);
 4193: <br />
 4194: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 4195: <input type="hidden" name="associate"  value="" />
 4196: <input type="hidden" name="phase"      value="three" />
 4197: <input type="hidden" name="datatoken"  value="$datatoken" />
 4198: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 4199: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 4200: <input type="hidden" name="upfile_associate" 
 4201:                                        value="$env{'form.upfile_associate'}" />
 4202: <input type="hidden" name="symb"       value="$symb" />
 4203: <input type="hidden" name="command"    value="csvuploadoptions" />
 4204: <hr />
 4205: ENDPICK
 4206:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
 4207:     return '';
 4208: 
 4209: }
 4210: 
 4211: sub csvupload_fields {
 4212:     my ($symb,$errorref) = @_;
 4213:     my (@parts) = &getpartlist($symb,$errorref);
 4214:     if (ref($errorref)) {
 4215:         if ($$errorref) {
 4216:             return;
 4217:         }
 4218:     }
 4219: 
 4220:     my @fields=(['ID','Student/Employee ID'],
 4221: 		['username','Student Username'],
 4222: 		['domain','Student Domain']);
 4223:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 4224:     foreach my $part (sort(@parts)) {
 4225: 	my @datum;
 4226: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 4227: 	my $name=$part;
 4228: 	if  (!$display) { $display = $name; }
 4229: 	@datum=($name,$display);
 4230: 	if ($name=~/^stores_(.*)_awarded/) {
 4231: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 4232: 	}
 4233: 	push(@fields,\@datum);
 4234:     }
 4235:     return (@fields);
 4236: }
 4237: 
 4238: sub csvuploadmap_footer {
 4239:     my ($request,$i,$keyfields) =@_;
 4240:     my $buttontext = &mt('Assign Grades');
 4241:     $request->print(<<ENDPICK);
 4242: </table>
 4243: <input type="hidden" name="nfields" value="$i" />
 4244: <input type="hidden" name="keyfields" value="$keyfields" />
 4245: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
 4246: </form>
 4247: ENDPICK
 4248: }
 4249: 
 4250: sub checkforfile_js {
 4251:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 4252:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
 4253:     function checkUpload(formname) {
 4254: 	if (formname.upfile.value == "") {
 4255: 	    alert("$alertmsg");
 4256: 	    return false;
 4257: 	}
 4258: 	formname.submit();
 4259:     }
 4260: CSVFORMJS
 4261:     return $result;
 4262: }
 4263: 
 4264: sub upcsvScores_form {
 4265:     my ($request,$symb) = @_;
 4266:     if (!$symb) {return '';}
 4267:     my $result=&checkforfile_js();
 4268:     $result.=&Apache::loncommon::start_data_table().
 4269:              &Apache::loncommon::start_data_table_header_row().
 4270:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
 4271:              &Apache::loncommon::end_data_table_header_row().
 4272:              &Apache::loncommon::start_data_table_row().'<td>';
 4273:     my $upload=&mt("Upload Scores");
 4274:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 4275:     my $ignore=&mt('Ignore First Line');
 4276:     $symb = &Apache::lonenc::check_encrypt($symb);
 4277:     $result.=<<ENDUPFORM;
 4278: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4279: <input type="hidden" name="symb" value="$symb" />
 4280: <input type="hidden" name="command" value="csvuploadmap" />
 4281: $upfile_select
 4282: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 4283: </form>
 4284: ENDUPFORM
 4285:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 4286:                            &mt("How do I create a CSV file from a spreadsheet")).
 4287:              '</td>'.
 4288:             &Apache::loncommon::end_data_table_row().
 4289:             &Apache::loncommon::end_data_table();
 4290:     return $result;
 4291: }
 4292: 
 4293: 
 4294: sub csvuploadmap {
 4295:     my ($request,$symb)= @_;
 4296:     if (!$symb) {return '';}
 4297: 
 4298:     my $datatoken;
 4299:     if (!$env{'form.datatoken'}) {
 4300: 	$datatoken=&Apache::loncommon::upfile_store($request);
 4301:     } else {
 4302: 	$datatoken=$env{'form.datatoken'};
 4303: 	&Apache::loncommon::load_tmp_file($request);
 4304:     }
 4305:     my @records=&Apache::loncommon::upfile_record_sep();
 4306:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 4307:     my ($i,$keyfields);
 4308:     if (@records) {
 4309:         my $fieldserror;
 4310: 	my @fields=&csvupload_fields($symb,\$fieldserror);
 4311:         if ($fieldserror) {
 4312:             $request->print(&navmap_errormsg());
 4313:             return;
 4314:         }
 4315: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 4316: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 4317: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 4318: 							  \@fields);
 4319: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 4320: 	    chop($keyfields);
 4321: 	} else {
 4322: 	    unshift(@fields,['none','']);
 4323: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 4324: 							    \@fields);
 4325:             foreach my $rec (@records) {
 4326:                 my %temp = &Apache::loncommon::record_sep($rec);
 4327:                 if (%temp) {
 4328:                     $keyfields=join(',',sort(keys(%temp)));
 4329:                     last;
 4330:                 }
 4331:             }
 4332: 	}
 4333:     }
 4334:     &csvuploadmap_footer($request,$i,$keyfields);
 4335: 
 4336:     return '';
 4337: }
 4338: 
 4339: sub csvuploadoptions {
 4340:     my ($request,$symb)= @_;
 4341:     my $overwrite=&mt('Overwrite any existing score');
 4342:     $request->print(<<ENDPICK);
 4343: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4344: <input type="hidden" name="command"    value="csvuploadassign" />
 4345: <p>
 4346: <label>
 4347:    <input type="checkbox" name="overwite_scores" checked="checked" />
 4348:    $overwrite
 4349: </label>
 4350: </p>
 4351: ENDPICK
 4352:     my %fields=&get_fields();
 4353:     if (!defined($fields{'domain'})) {
 4354: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 4355: 	$request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
 4356:     }
 4357:     foreach my $key (sort(keys(%env))) {
 4358: 	if ($key !~ /^form\.(.*)$/) { next; }
 4359: 	my $cleankey=$1;
 4360: 	if ($cleankey eq 'command') { next; }
 4361: 	$request->print('<input type="hidden" name="'.$cleankey.
 4362: 			'"  value="'.$env{$key}.'" />'."\n");
 4363:     }
 4364:     # FIXME do a check for any duplicated user ids...
 4365:     # FIXME do a check for any invalid user ids?...
 4366:     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
 4367: <hr /></form>'."\n");
 4368:     return '';
 4369: }
 4370: 
 4371: sub get_fields {
 4372:     my %fields;
 4373:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 4374:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 4375: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 4376: 	    if ($env{'form.f'.$i} ne 'none') {
 4377: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 4378: 	    }
 4379: 	} else {
 4380: 	    if ($env{'form.f'.$i} ne 'none') {
 4381: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 4382: 	    }
 4383: 	}
 4384:     }
 4385:     return %fields;
 4386: }
 4387: 
 4388: sub csvuploadassign {
 4389:     my ($request,$symb)= @_;
 4390:     if (!$symb) {return '';}
 4391:     my $error_msg = '';
 4392:     &Apache::loncommon::load_tmp_file($request);
 4393:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 4394:     my %fields=&get_fields();
 4395:     my $courseid=$env{'request.course.id'};
 4396:     my ($classlist) = &getclasslist('all',0);
 4397:     my @notallowed;
 4398:     my @skipped;
 4399:     my @warnings;
 4400:     my $countdone=0;
 4401:     foreach my $grade (@gradedata) {
 4402: 	my %entries=&Apache::loncommon::record_sep($grade);
 4403: 	my $domain;
 4404: 	if ($entries{$fields{'domain'}}) {
 4405: 	    $domain=$entries{$fields{'domain'}};
 4406: 	} else {
 4407: 	    $domain=$env{'form.default_domain'};
 4408: 	}
 4409: 	$domain=~s/\s//g;
 4410: 	my $username=$entries{$fields{'username'}};
 4411: 	$username=~s/\s//g;
 4412: 	if (!$username) {
 4413: 	    my $id=$entries{$fields{'ID'}};
 4414: 	    $id=~s/\s//g;
 4415: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 4416: 	    $username=$ids{$id};
 4417: 	}
 4418: 	if (!exists($$classlist{"$username:$domain"})) {
 4419: 	    my $id=$entries{$fields{'ID'}};
 4420: 	    $id=~s/\s//g;
 4421: 	    if ($id) {
 4422: 		push(@skipped,"$id:$domain");
 4423: 	    } else {
 4424: 		push(@skipped,"$username:$domain");
 4425: 	    }
 4426: 	    next;
 4427: 	}
 4428: 	my $usec=$classlist->{"$username:$domain"}[5];
 4429: 	if (!&canmodify($usec)) {
 4430: 	    push(@notallowed,"$username:$domain");
 4431: 	    next;
 4432: 	}
 4433: 	my %points;
 4434: 	my %grades;
 4435: 	foreach my $dest (keys(%fields)) {
 4436: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 4437: 		$dest eq 'domain') { next; }
 4438: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 4439: 	    if ($dest=~/stores_(.*)_points/) {
 4440: 		my $part=$1;
 4441: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 4442: 					      $symb,$domain,$username);
 4443:                 if ($wgt) {
 4444:                     $entries{$fields{$dest}}=~s/\s//g;
 4445:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 4446:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 4447:                                           : 'correct_by_override';
 4448:                     if ($pcr>1) {
 4449:                        push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
 4450:                     }
 4451:                     $grades{"resource.$part.awarded"}=$pcr;
 4452:                     $grades{"resource.$part.solved"}=$award;
 4453:                     $points{$part}=1;
 4454:                 } else {
 4455:                     $error_msg = "<br />" .
 4456:                         &mt("Some point values were assigned"
 4457:                             ." for problems with a weight "
 4458:                             ."of zero. These values were "
 4459:                             ."ignored.");
 4460:                 }
 4461: 	    } else {
 4462: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 4463: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 4464: 		my $store_key=$dest;
 4465: 		$store_key=~s/^stores/resource/;
 4466: 		$store_key=~s/_/\./g;
 4467: 		$grades{$store_key}=$entries{$fields{$dest}};
 4468: 	    }
 4469: 	}
 4470: 	if (! %grades) { 
 4471:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 4472:         } else {
 4473: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 4474: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 4475: 					   $env{'request.course.id'},
 4476: 					   $domain,$username);
 4477: 	   if ($result eq 'ok') {
 4478: # Successfully stored
 4479: 	      $request->print('.');
 4480: # Remove from grading queue
 4481:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
 4482:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
 4483:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
 4484:                                              $domain,$username);
 4485:               $countdone++;
 4486:            } else {
 4487: 	      $request->print("<p><span class=\"LC_error\">".
 4488:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 4489:                                   "$username:$domain",$result)."</span></p>");
 4490: 	   }
 4491: 	   $request->rflush();
 4492:         }
 4493:     }
 4494:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
 4495:     if (@warnings) {
 4496:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
 4497:         $request->print(join(', ',@warnings));
 4498:     }
 4499:     if (@skipped) {
 4500: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
 4501:         $request->print(join(', ',@skipped));
 4502:     }
 4503:     if (@notallowed) {
 4504: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
 4505: 	$request->print(join(', ',@notallowed));
 4506:     }
 4507:     $request->print("<br />\n");
 4508:     return $error_msg;
 4509: }
 4510: #------------- end of section for handling csv file upload ---------
 4511: #
 4512: #-------------------------------------------------------------------
 4513: #
 4514: #-------------- Next few routines handle grading by page/sequence
 4515: #
 4516: #--- Select a page/sequence and a student to grade
 4517: sub pickStudentPage {
 4518:     my ($request,$symb) = @_;
 4519: 
 4520:     my $alertmsg = &mt('Please select the student you wish to grade.');
 4521:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
 4522: 
 4523: function checkPickOne(formname) {
 4524:     if (radioSelection(formname.student) == null) {
 4525: 	alert("$alertmsg");
 4526: 	return;
 4527:     }
 4528:     ptr = pullDownSelection(formname.selectpage);
 4529:     formname.page.value = formname["page"+ptr].value;
 4530:     formname.title.value = formname["title"+ptr].value;
 4531:     formname.submit();
 4532: }
 4533: 
 4534: LISTJAVASCRIPT
 4535:     &commonJSfunctions($request);
 4536: 
 4537:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4538:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4539:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4540: 
 4541:     my $result='<h3><span class="LC_info">&nbsp;'.
 4542: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 4543: 
 4544:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 4545:     my $map_error;
 4546:     my ($titles,$symbx) = &getSymbMap($map_error);
 4547:     if ($map_error) {
 4548:         $request->print(&navmap_errormsg());
 4549:         return; 
 4550:     }
 4551:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 4552: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 4553: #    my $type=($curpage =~ /\.(page|sequence)/);
 4554: 
 4555:     # Collection of hidden fields
 4556:     my $ctr=0;
 4557:     foreach (@$titles) {
 4558:         my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4559:         $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 4560:         $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 4561:         $ctr++;
 4562:     }
 4563:     $result.='<input type="hidden" name="page" />'."\n".
 4564:         '<input type="hidden" name="title" />'."\n";
 4565: 
 4566:     $result.=&build_section_inputs();
 4567:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4568:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 4569: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 4570: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 4571: 
 4572:     # Show grading options
 4573:     $result.=&Apache::lonhtmlcommon::start_pick_box();
 4574:     my $select = '<select name="selectpage">'."\n";
 4575:     $ctr=0;
 4576:     foreach (@$titles) {
 4577: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4578: 	$select.='<option value="'.$ctr.'"'.
 4579: 	    ($$symbx{$_} =~ /$curpage$/ ? ' selected="selected"' : '').
 4580: 	    '>'.$showtitle.'</option>'."\n";
 4581: 	$ctr++;
 4582:     }
 4583:     $select.= '</select>';
 4584: 
 4585:     $result.=
 4586:         &Apache::lonhtmlcommon::row_title(&mt('Problems from'))
 4587:        .$select
 4588:        .&Apache::lonhtmlcommon::row_closure();
 4589: 
 4590:     $result.=
 4591:         &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
 4592:        .'<label><input type="radio" name="vProb" value="no"'
 4593:            .' checked="checked" /> '.&mt('no').' </label>'."\n"
 4594:        .'<label><input type="radio" name="vProb" value="yes" />'
 4595:            .&mt('yes').'</label>'."\n"
 4596:        .&Apache::lonhtmlcommon::row_closure();
 4597: 
 4598:     $result.=
 4599:         &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
 4600:        .'<label><input type="radio" name="lastSub" value="none" /> '
 4601:            .&mt('none').' </label>'."\n"
 4602:        .'<label><input type="radio" name="lastSub" value="datesub"'
 4603:            .' checked="checked" /> '.&mt('all submissions').'</label>'."\n"
 4604:        .'<label><input type="radio" name="lastSub" value="all" /> '
 4605:            .&mt('all submissions with details').' </label>'
 4606:        .&Apache::lonhtmlcommon::row_closure();
 4607:     
 4608:     $result.=
 4609:         &Apache::lonhtmlcommon::row_title(&mt('Use CODE'))
 4610:        .'<input type="text" name="CODE" value="" />'
 4611:        .&Apache::lonhtmlcommon::row_closure(1)
 4612:        .&Apache::lonhtmlcommon::end_pick_box();
 4613: 
 4614:     # Show list of students to select for grading
 4615:     $result.='<br /><input type="button" '.
 4616:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 4617: 
 4618:     $request->print($result);
 4619: 
 4620:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 4621: 	&Apache::loncommon::start_data_table().
 4622: 	&Apache::loncommon::start_data_table_header_row().
 4623: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4624: 	'<th>'.&nameUserString('header').'</th>'.
 4625: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4626: 	'<th>'.&nameUserString('header').'</th>'.
 4627: 	&Apache::loncommon::end_data_table_header_row();
 4628:  
 4629:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 4630:     my $ptr = 1;
 4631:     foreach my $student (sort 
 4632: 			 {
 4633: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4634: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4635: 			     }
 4636: 			     return $a cmp $b;
 4637: 			 } (keys(%$fullname))) {
 4638: 	my ($uname,$udom) = split(/:/,$student);
 4639: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 4640:                                   : '</td>');
 4641: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 4642: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 4643: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 4644: 	$studentTable.=
 4645: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 4646:                          : '');
 4647: 	$ptr++;
 4648:     }
 4649:     if ($ptr%2 == 0) {
 4650: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 4651: 	    &Apache::loncommon::end_data_table_row();
 4652:     }
 4653:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 4654:     $studentTable.='<input type="button" '.
 4655:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 4656: 
 4657:     $request->print($studentTable);
 4658: 
 4659:     return '';
 4660: }
 4661: 
 4662: sub getSymbMap {
 4663:     my ($map_error) = @_;
 4664:     my $navmap = Apache::lonnavmaps::navmap->new();
 4665:     unless (ref($navmap)) {
 4666:         if (ref($map_error)) {
 4667:             $$map_error = 'navmap';
 4668:         }
 4669:         return;
 4670:     }
 4671:     my %symbx = ();
 4672:     my @titles = ();
 4673:     my $minder = 0;
 4674: 
 4675:     # Gather every sequence that has problems.
 4676:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 4677: 					       1,0,1);
 4678:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 4679: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 4680: 	    my $title = $minder.'.'.
 4681: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 4682: 	    push(@titles, $title); # minder in case two titles are identical
 4683: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 4684: 	    $minder++;
 4685: 	}
 4686:     }
 4687:     return \@titles,\%symbx;
 4688: }
 4689: 
 4690: #
 4691: #--- Displays a page/sequence w/wo problems, w/wo submissions
 4692: sub displayPage {
 4693:     my ($request,$symb) = @_;
 4694:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4695:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4696:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4697:     my $pageTitle = $env{'form.page'};
 4698:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4699:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4700:     my $usec=$classlist->{$env{'form.student'}}[5];
 4701: 
 4702:     #need to make sure we have the correct data for later EXT calls, 
 4703:     #thus invalidate the cache
 4704:     &Apache::lonnet::devalidatecourseresdata(
 4705:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 4706:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 4707:     &Apache::lonnet::clear_EXT_cache_status();
 4708: 
 4709:     if (!&canview($usec)) {
 4710:         $request->print(
 4711:             '<span class="LC_warning">'.
 4712:             &mt('Unable to view requested student. ([_1])',
 4713:                     $env{'form.student'}).
 4714:             '</span>');
 4715:         return;
 4716:     }
 4717:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4718:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 4719: 	'</h3>'."\n";
 4720:     $env{'form.CODE'} = uc($env{'form.CODE'});
 4721:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 4722: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 4723:     } else {
 4724: 	delete($env{'form.CODE'});
 4725:     }
 4726:     &sub_page_js($request);
 4727:     $request->print($result);
 4728: 
 4729:     my $navmap = Apache::lonnavmaps::navmap->new();
 4730:     unless (ref($navmap)) {
 4731:         $request->print(&navmap_errormsg());
 4732:         return;
 4733:     }
 4734:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 4735:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4736:     if (!$map) {
 4737: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 4738: 	return; 
 4739:     }
 4740:     my $iterator = $navmap->getIterator($map->map_start(),
 4741: 					$map->map_finish());
 4742: 
 4743:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 4744: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 4745: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 4746: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 4747: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 4748: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 4749: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4750: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
 4751: 
 4752:     if (defined($env{'form.CODE'})) {
 4753: 	$studentTable.=
 4754: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 4755:     }
 4756:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 4757: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 4758: 
 4759:     $studentTable.='&nbsp;<span class="LC_info">'.
 4760:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
 4761:         '</span>'."\n".
 4762: 	&Apache::loncommon::start_data_table().
 4763: 	&Apache::loncommon::start_data_table_header_row().
 4764: 	'<th>'.&mt('Prob.').'</th>'.
 4765: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 4766: 	&Apache::loncommon::end_data_table_header_row();
 4767: 
 4768:     &Apache::lonxml::clear_problem_counter();
 4769:     my ($depth,$question,$prob) = (1,1,1);
 4770:     $iterator->next(); # skip the first BEGIN_MAP
 4771:     my $curRes = $iterator->next(); # for "current resource"
 4772:     while ($depth > 0) {
 4773:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4774:         if($curRes == $iterator->END_MAP) { $depth--; }
 4775: 
 4776:         if (ref($curRes) && $curRes->is_problem()) {
 4777: 	    my $parts = $curRes->parts();
 4778:             my $title = $curRes->compTitle();
 4779: 	    my $symbx = $curRes->symb();
 4780: 	    $studentTable.=
 4781: 		&Apache::loncommon::start_data_table_row().
 4782: 		'<td align="center" valign="top" >'.$prob.
 4783: 		(scalar(@{$parts}) == 1 ? '' 
 4784: 		                        : '<br />('.&mt('[_1]parts',
 4785: 							scalar(@{$parts}).'&nbsp;').')'
 4786: 		 ).
 4787: 		 '</td>';
 4788: 	    $studentTable.='<td valign="top">';
 4789: 	    my %form = ('CODE' => $env{'form.CODE'},);
 4790: 	    if ($env{'form.vProb'} eq 'yes' ) {
 4791: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 4792: 					     undef,'both',\%form);
 4793: 	    } else {
 4794: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 4795: 		$companswer =~ s|<form(.*?)>||g;
 4796: 		$companswer =~ s|</form>||g;
 4797: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 4798: #		    $companswer =~ s/$1/ /ms;
 4799: #		    $request->print('match='.$1."<br />\n");
 4800: #		}
 4801: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 4802: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 4803: 	    }
 4804: 
 4805: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 4806: 
 4807: 	    if ($env{'form.lastSub'} eq 'datesub') {
 4808: 		if ($record{'version'} eq '') {
 4809: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
 4810: 		} else {
 4811: 		    my %responseType = ();
 4812: 		    foreach my $partid (@{$parts}) {
 4813: 			my @responseIds =$curRes->responseIds($partid);
 4814: 			my @responseType =$curRes->responseType($partid);
 4815: 			my %responseIds;
 4816: 			for (my $i=0;$i<=$#responseIds;$i++) {
 4817: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 4818: 			}
 4819: 			$responseType{$partid} = \%responseIds;
 4820: 		    }
 4821: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 4822: 
 4823: 		}
 4824: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 4825: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 4826:                 my $identifier = (&canmodify($usec)? $prob : ''); 
 4827: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 4828: 									$env{'request.course.id'},
 4829: 									'','.submission',undef,
 4830:                                                                         $usec,$identifier);
 4831:  
 4832: 	    }
 4833: 	    if (&canmodify($usec)) {
 4834:             $studentTable.=&gradeBox_start();
 4835: 		foreach my $partid (@{$parts}) {
 4836: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 4837: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 4838: 		    $question++;
 4839: 		}
 4840:             $studentTable.=&gradeBox_end();
 4841: 		$prob++;
 4842: 	    }
 4843: 	    $studentTable.='</td></tr>';
 4844: 
 4845: 	}
 4846:         $curRes = $iterator->next();
 4847:     }
 4848: 
 4849:     $studentTable.=
 4850:         '</table>'."\n".
 4851:         '<input type="button" value="'.&mt('Save').'" '.
 4852:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 4853:         '</form>'."\n";
 4854:     $request->print($studentTable);
 4855: 
 4856:     return '';
 4857: }
 4858: 
 4859: sub displaySubByDates {
 4860:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 4861:     my $isCODE=0;
 4862:     my $isTask = ($symb =~/\.task$/);
 4863:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 4864:     my $studentTable=&Apache::loncommon::start_data_table().
 4865: 	&Apache::loncommon::start_data_table_header_row().
 4866: 	'<th>'.&mt('Date/Time').'</th>'.
 4867: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 4868:         ($isTask?'<th>'.&mt('Version').'</th>':'').
 4869: 	'<th>'.&mt('Submission').'</th>'.
 4870: 	'<th>'.&mt('Status').'</th>'.
 4871: 	&Apache::loncommon::end_data_table_header_row();
 4872:     my ($version);
 4873:     my %mark;
 4874:     my %orders;
 4875:     $mark{'correct_by_student'} = $checkIcon;
 4876:     if (!exists($$record{'1:timestamp'})) {
 4877: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 4878:     }
 4879: 
 4880:     my $interaction;
 4881:     my $no_increment = 1;
 4882:     my %lastrndseed;
 4883:     for ($version=1;$version<=$$record{'version'};$version++) {
 4884: 	my $timestamp = 
 4885: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 4886: 	if (exists($$record{$version.':resource.0.version'})) {
 4887: 	    $interaction = $$record{$version.':resource.0.version'};
 4888: 	}
 4889:         if ($isTask && $env{'form.previousversion'}) {
 4890:             next unless ($interaction == $env{'form.previousversion'});
 4891:         }
 4892: 	my $where = ($isTask ? "$version:resource.$interaction"
 4893: 		             : "$version:resource");
 4894: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 4895: 	    '<td>'.$timestamp.'</td>';
 4896: 	if ($isCODE) {
 4897: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 4898: 	}
 4899:         if ($isTask) {
 4900:             $studentTable.='<td>'.$interaction.'</td>';
 4901:         }
 4902: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 4903: 	my @displaySub = ();
 4904: 	foreach my $partid (@{$parts}) {
 4905:             my ($hidden,$type);
 4906:             $type = $$record{$version.':resource.'.$partid.'.type'};
 4907:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
 4908:                 $hidden = 1;
 4909:             }
 4910: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
 4911: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 4912: 	    
 4913: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 4914: 	    my $display_part=&get_display_part($partid,$symb);
 4915: 	    foreach my $matchKey (@matchKey) {
 4916: 		if (exists($$record{$version.':'.$matchKey}) &&
 4917: 		    $$record{$version.':'.$matchKey} ne '') {
 4918:                     
 4919: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 4920: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 4921:                     $displaySub[0].='<span class="LC_nobreak">';
 4922:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
 4923:                                    .' <span class="LC_internal_info">'
 4924:                                    .'('.&mt('Response ID: [_1]',$responseId).')'
 4925:                                    .'</span>'
 4926:                                    .' <b>';
 4927:                     if ($hidden) {
 4928:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
 4929:                     } else {
 4930:                         my ($trial,$rndseed,$newvariation);
 4931:                         if ($type eq 'randomizetry') {
 4932:                             $trial = $$record{"$where.$partid.tries"};
 4933:                             $rndseed = $$record{"$where.$partid.rndseed"};
 4934:                         }
 4935: 		        if ($$record{"$where.$partid.tries"} eq '') {
 4936: 			    $displaySub[0].=&mt('Trial not counted');
 4937: 		        } else {
 4938: 			    $displaySub[0].=&mt('Trial: [_1]',
 4939: 					    $$record{"$where.$partid.tries"});
 4940:                             if ($rndseed || $lastrndseed{$partid}) {
 4941:                                 if ($rndseed ne $lastrndseed{$partid}) {
 4942:                                     $newvariation = '&nbsp;('.&mt('New variation this try').')';
 4943:                                 }
 4944:                             }
 4945:                             $lastrndseed{$partid} = $rndseed;
 4946: 		        }
 4947: 		        my $responseType=($isTask ? 'Task'
 4948:                                               : $responseType->{$partid}->{$responseId});
 4949: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
 4950: 		        if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
 4951: 			    $orders{$partid}->{$responseId}=
 4952: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
 4953:                                            $no_increment,$type,$trial,$rndseed);
 4954: 		        }
 4955: 		        $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
 4956: 		        $displaySub[0].='&nbsp; '.
 4957: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
 4958:                     }
 4959: 		}
 4960: 	    }
 4961: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 4962: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 4963: 				    $$record{"$where.$partid.checkedin"},
 4964: 				    $$record{"$where.$partid.checkedin.slot"}).
 4965: 					'<br />';
 4966: 	    }
 4967: 	    if (exists $$record{"$where.$partid.award"}) {
 4968: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 4969: 		    lc($$record{"$where.$partid.award"}).' '.
 4970: 		    $mark{$$record{"$where.$partid.solved"}}.
 4971: 		    '<br />';
 4972: 	    }
 4973: 	    if (exists $$record{"$where.$partid.regrader"}) {
 4974: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 4975: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4976: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 4977: 		$displaySub[2].=
 4978: 		    $$record{"$version:resource.$partid.regrader"}.
 4979: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4980: 	    }
 4981: 	}
 4982: 	# needed because old essay regrader has not parts info
 4983: 	if (exists $$record{"$version:resource.regrader"}) {
 4984: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 4985: 	}
 4986: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 4987: 	if ($displaySub[2]) {
 4988: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 4989: 	}
 4990: 	$studentTable.='&nbsp;</td>'.
 4991: 	    &Apache::loncommon::end_data_table_row();
 4992:     }
 4993:     $studentTable.=&Apache::loncommon::end_data_table();
 4994:     return $studentTable;
 4995: }
 4996: 
 4997: sub updateGradeByPage {
 4998:     my ($request,$symb) = @_;
 4999: 
 5000:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 5001:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 5002:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 5003:     my $pageTitle = $env{'form.page'};
 5004:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 5005:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 5006:     my $usec=$classlist->{$env{'form.student'}}[5];
 5007:     if (!&canmodify($usec)) {
 5008: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 5009: 	return;
 5010:     }
 5011:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 5012:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 5013: 	'</h3>'."\n";
 5014: 
 5015:     $request->print($result);
 5016: 
 5017: 
 5018:     my $navmap = Apache::lonnavmaps::navmap->new();
 5019:     unless (ref($navmap)) {
 5020:         $request->print(&navmap_errormsg());
 5021:         return;
 5022:     }
 5023:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 5024:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 5025:     if (!$map) {
 5026: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 5027: 	return; 
 5028:     }
 5029:     my $iterator = $navmap->getIterator($map->map_start(),
 5030: 					$map->map_finish());
 5031: 
 5032:     my $studentTable=
 5033: 	&Apache::loncommon::start_data_table().
 5034: 	&Apache::loncommon::start_data_table_header_row().
 5035: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 5036: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 5037: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 5038: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 5039: 	&Apache::loncommon::end_data_table_header_row();
 5040: 
 5041:     $iterator->next(); # skip the first BEGIN_MAP
 5042:     my $curRes = $iterator->next(); # for "current resource"
 5043:     my ($depth,$question,$prob,$changeflag,$hideflag)= (1,1,1,0,0);
 5044:     while ($depth > 0) {
 5045:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 5046:         if($curRes == $iterator->END_MAP) { $depth--; }
 5047: 
 5048:         if (ref($curRes) && $curRes->is_problem()) {
 5049: 	    my $parts = $curRes->parts();
 5050:             my $title = $curRes->compTitle();
 5051: 	    my $symbx = $curRes->symb();
 5052: 	    $studentTable.=
 5053: 		&Apache::loncommon::start_data_table_row().
 5054: 		'<td align="center" valign="top" >'.$prob.
 5055: 		(scalar(@{$parts}) == 1 ? '' 
 5056:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
 5057: 		.')').'</td>';
 5058: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 5059: 
 5060: 	    my %newrecord=();
 5061: 	    my @displayPts=();
 5062:             my %aggregate = ();
 5063:             my $aggregateflag = 0;
 5064:             if ($env{'form.HIDE'.$prob}) {
 5065:                 my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 5066:                 my $numchgs = &makehidden($prob,\%record,$symbx,$udom,$uname);
 5067:                 $hideflag += $numchgs;
 5068:             }
 5069: 	    foreach my $partid (@{$parts}) {
 5070: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 5071: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 5072: 
 5073: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 5074: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 5075: 		my $partial = $newpts/$wgt;
 5076: 		my $score;
 5077: 		if ($partial > 0) {
 5078: 		    $score = 'correct_by_override';
 5079: 		} elsif ($newpts ne '') { #empty is taken as 0
 5080: 		    $score = 'incorrect_by_override';
 5081: 		}
 5082: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 5083: 		if ($dropMenu eq 'excused') {
 5084: 		    $partial = '';
 5085: 		    $score = 'excused';
 5086: 		} elsif ($dropMenu eq 'reset status'
 5087: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 5088: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 5089: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 5090: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 5091: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 5092: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 5093: 		    $changeflag++;
 5094: 		    $newpts = '';
 5095:                     
 5096:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 5097:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 5098:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 5099:                     if ($aggtries > 0) {
 5100:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 5101:                         $aggregateflag = 1;
 5102:                     }
 5103: 		}
 5104: 		my $display_part=&get_display_part($partid,$curRes->symb());
 5105: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 5106: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5107: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 5108: 		    '&nbsp;<br />';
 5109: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5110: 		     (($score eq 'excused') ? 'excused' : $newpts).
 5111: 		    '&nbsp;<br />';
 5112: 		$question++;
 5113: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 5114: 
 5115: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 5116: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 5117: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 5118: 		    if (scalar(keys(%newrecord)) > 0);
 5119: 
 5120: 		$changeflag++;
 5121: 	    }
 5122: 	    if (scalar(keys(%newrecord)) > 0) {
 5123: 		my %record = 
 5124: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 5125: 					     $udom,$uname);
 5126: 
 5127: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 5128: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 5129: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 5130: 		    $newrecord{'resource.CODE'} = '';
 5131: 		}
 5132: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 5133: 					$udom,$uname);
 5134: 		%record = &Apache::lonnet::restore($symbx,
 5135: 						   $env{'request.course.id'},
 5136: 						   $udom,$uname);
 5137: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 5138: 					     $cdom,$cnum,$udom,$uname);
 5139: 	    }
 5140: 	    
 5141:             if ($aggregateflag) {
 5142:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 5143:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 5144:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 5145:             }
 5146: 
 5147: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 5148: 		'<td valign="top">'.$displayPts[1].'</td>'.
 5149: 		&Apache::loncommon::end_data_table_row();
 5150: 
 5151: 	    $prob++;
 5152: 	}
 5153:         $curRes = $iterator->next();
 5154:     }
 5155: 
 5156:     $studentTable.=&Apache::loncommon::end_data_table();
 5157:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 5158: 		  &mt('The scores were changed for [quant,_1,problem].',
 5159: 		  $changeflag).'<br />');
 5160:     my $hidemsg=($hideflag == 0 ? '' :
 5161:                  &mt('Submissions were marked "hidden" for [quant,_1,transaction].',
 5162:                      $hideflag).'<br />');
 5163:     $request->print($hidemsg.$grademsg.$studentTable);
 5164: 
 5165:     return '';
 5166: }
 5167: 
 5168: #-------- end of section for handling grading by page/sequence ---------
 5169: #
 5170: #-------------------------------------------------------------------
 5171: 
 5172: #-------------------- Bubblesheet (Scantron) Grading -------------------
 5173: #
 5174: #------ start of section for handling grading by page/sequence ---------
 5175: 
 5176: =pod
 5177: 
 5178: =head1 Bubble sheet grading routines
 5179: 
 5180:   For this documentation:
 5181: 
 5182:    'scanline' refers to the full line of characters
 5183:    from the file that we are parsing that represents one entire sheet
 5184: 
 5185:    'bubble line' refers to the data
 5186:    representing the line of bubbles that are on the physical bubblesheet
 5187: 
 5188: 
 5189: The overall process is that a scanned in bubblesheet data is uploaded
 5190: into a course. When a user wants to grade, they select a
 5191: sequence/folder of resources, a file of bubblesheet info, and pick
 5192: one of the predefined configurations for what each scanline looks
 5193: like.
 5194: 
 5195: Next each scanline is checked for any errors of either 'missing
 5196: bubbles' (it's an error because it may have been mis-scanned
 5197: because too light bubbling), 'double bubble' (each bubble line should
 5198: have no more than one letter picked), invalid or duplicated CODE,
 5199: invalid student/employee ID
 5200: 
 5201: If the CODE option is used that determines the randomization of the
 5202: homework problems, either way the student/employee ID is looked up into a
 5203: username:domain.
 5204: 
 5205: During the validation phase the instructor can choose to skip scanlines. 
 5206: 
 5207: After the validation phase, there are now 3 bubblesheet files
 5208: 
 5209:   scantron_original_filename (unmodified original file)
 5210:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 5211:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 5212: 
 5213: Also there is a separate hash nohist_scantrondata that contains extra
 5214: correction information that isn't representable in the bubblesheet
 5215: file (see &scantron_getfile() for more information)
 5216: 
 5217: After all scanlines are either valid, marked as valid or skipped, then
 5218: foreach line foreach problem in the picked sequence, an ssi request is
 5219: made that simulates a user submitting their selected letter(s) against
 5220: the homework problem.
 5221: 
 5222: =over 4
 5223: 
 5224: 
 5225: 
 5226: =item defaultFormData
 5227: 
 5228:   Returns html hidden inputs used to hold context/default values.
 5229: 
 5230:  Arguments:
 5231:   $symb - $symb of the current resource 
 5232: 
 5233: =cut
 5234: 
 5235: sub defaultFormData {
 5236:     my ($symb)=@_;
 5237:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />';
 5238: }
 5239: 
 5240: 
 5241: =pod 
 5242: 
 5243: =item getSequenceDropDown
 5244: 
 5245:    Return html dropdown of possible sequences to grade
 5246:  
 5247:  Arguments:
 5248:    $symb - $symb of the current resource
 5249:    $map_error - ref to scalar which will container error if
 5250:                 $navmap object is unavailable in &getSymbMap().
 5251: 
 5252: =cut
 5253: 
 5254: sub getSequenceDropDown {
 5255:     my ($symb,$map_error)=@_;
 5256:     my $result='<select name="selectpage">'."\n";
 5257:     my ($titles,$symbx) = &getSymbMap($map_error);
 5258:     if (ref($map_error)) {
 5259:         return if ($$map_error);
 5260:     }
 5261:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 5262:     my $ctr=0;
 5263:     foreach (@$titles) {
 5264: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 5265: 	$result.='<option value="'.$$symbx{$_}.'" '.
 5266: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 5267: 	    '>'.$showtitle.'</option>'."\n";
 5268: 	$ctr++;
 5269:     }
 5270:     $result.= '</select>';
 5271:     return $result;
 5272: }
 5273: 
 5274: my %bubble_lines_per_response;     # no. bubble lines for each response.
 5275:                                    # key is zero-based index - 0, 1, 2 ...
 5276: 
 5277: my %first_bubble_line;             # First bubble line no. for each bubble.
 5278: 
 5279: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 5280:                                    # matchresponse or rankresponse, where 
 5281:                                    # an individual response can have multiple 
 5282:                                    # lines
 5283: 
 5284: my %responsetype_per_response;     # responsetype for each response
 5285: 
 5286: my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
 5287:                                    # numbered response. Needed when randomorder
 5288:                                    # or randompick are in use. Key is ID, value 
 5289:                                    # is response number.
 5290: 
 5291: # Save and restore the bubble lines array to the form env.
 5292: 
 5293: 
 5294: sub save_bubble_lines {
 5295:     foreach my $line (keys(%bubble_lines_per_response)) {
 5296: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 5297: 	$env{"form.scantron.first_bubble_line.$line"} =
 5298: 	    $first_bubble_line{$line};
 5299:         $env{"form.scantron.sub_bubblelines.$line"} = 
 5300:             $subdivided_bubble_lines{$line};
 5301:         $env{"form.scantron.responsetype.$line"} =
 5302:             $responsetype_per_response{$line};
 5303:     }
 5304:     foreach my $resid (keys(%masterseq_id_responsenum)) {
 5305:         my $line = $masterseq_id_responsenum{$resid};
 5306:         $env{"form.scantron.residpart.$line"} = $resid;
 5307:     }
 5308: }
 5309: 
 5310: 
 5311: sub restore_bubble_lines {
 5312:     my $line = 0;
 5313:     %bubble_lines_per_response = ();
 5314:     %masterseq_id_responsenum = ();
 5315:     while ($env{"form.scantron.bubblelines.$line"}) {
 5316: 	my $value = $env{"form.scantron.bubblelines.$line"};
 5317: 	$bubble_lines_per_response{$line} = $value;
 5318: 	$first_bubble_line{$line}  =
 5319: 	    $env{"form.scantron.first_bubble_line.$line"};
 5320:         $subdivided_bubble_lines{$line} =
 5321:             $env{"form.scantron.sub_bubblelines.$line"};
 5322:         $responsetype_per_response{$line} =
 5323:             $env{"form.scantron.responsetype.$line"};
 5324:         my $id = $env{"form.scantron.residpart.$line"};
 5325:         $masterseq_id_responsenum{$id} = $line;
 5326: 	$line++;
 5327:     }
 5328: }
 5329: 
 5330: =pod 
 5331: 
 5332: =item scantron_filenames
 5333: 
 5334:    Returns a list of the scantron files in the current course 
 5335: 
 5336: =cut
 5337: 
 5338: sub scantron_filenames {
 5339:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5340:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5341:     my $getpropath = 1;
 5342:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
 5343:                                                         $cname,$getpropath);
 5344:     my @possiblenames;
 5345:     if (ref($dirlist) eq 'ARRAY') {
 5346:         foreach my $filename (sort(@{$dirlist})) {
 5347: 	    ($filename)=split(/&/,$filename);
 5348: 	    if ($filename!~/^scantron_orig_/) { next ; }
 5349: 	    $filename=~s/^scantron_orig_//;
 5350: 	    push(@possiblenames,$filename);
 5351:         }
 5352:     }
 5353:     return @possiblenames;
 5354: }
 5355: 
 5356: =pod 
 5357: 
 5358: =item scantron_uploads
 5359: 
 5360:    Returns  html drop-down list of scantron files in current course.
 5361: 
 5362:  Arguments:
 5363:    $file2grade - filename to set as selected in the dropdown
 5364: 
 5365: =cut
 5366: 
 5367: sub scantron_uploads {
 5368:     my ($file2grade) = @_;
 5369:     my $result=	'<select name="scantron_selectfile">';
 5370:     $result.="<option></option>";
 5371:     foreach my $filename (sort(&scantron_filenames())) {
 5372: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 5373:     }
 5374:     $result.="</select>";
 5375:     return $result;
 5376: }
 5377: 
 5378: =pod 
 5379: 
 5380: =item scantron_scantab
 5381: 
 5382:   Returns html drop down of the scantron formats in the scantronformat.tab
 5383:   file.
 5384: 
 5385: =cut
 5386: 
 5387: sub scantron_scantab {
 5388:     my $result='<select name="scantron_format">'."\n";
 5389:     $result.='<option></option>'."\n";
 5390:     my @lines = &get_scantronformat_file();
 5391:     if (@lines > 0) {
 5392:         foreach my $line (@lines) {
 5393:             next if (($line =~ /^\#/) || ($line eq ''));
 5394: 	    my ($name,$descrip)=split(/:/,$line);
 5395: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 5396:         }
 5397:     }
 5398:     $result.='</select>'."\n";
 5399:     return $result;
 5400: }
 5401: 
 5402: =pod
 5403: 
 5404: =item get_scantronformat_file
 5405: 
 5406:   Returns an array containing lines from the scantron format file for
 5407:   the domain of the course.
 5408: 
 5409:   If a url for a custom.tab file is listed in domain's configuration.db, 
 5410:   lines are from this file.
 5411: 
 5412:   Otherwise, if a default.tab has been published in RES space by the 
 5413:   domainconfig user, lines are from this file.
 5414: 
 5415:   Otherwise, fall back to getting lines from the legacy file on the
 5416:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
 5417: 
 5418: =cut
 5419: 
 5420: sub get_scantronformat_file {
 5421:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5422:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
 5423:     my $gottab = 0;
 5424:     my @lines;
 5425:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 5426:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 5427:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 5428:             if ($formatfile ne '-1') {
 5429:                 @lines = split("\n",$formatfile,-1);
 5430:                 $gottab = 1;
 5431:             }
 5432:         }
 5433:     }
 5434:     if (!$gottab) {
 5435:         my $confname = $cdom.'-domainconfig';
 5436:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 5437:         my $formatfile =  &Apache::lonnet::getfile($default);
 5438:         if ($formatfile ne '-1') {
 5439:             @lines = split("\n",$formatfile,-1);
 5440:             $gottab = 1;
 5441:         }
 5442:     }
 5443:     if (!$gottab) {
 5444:         my @domains = &Apache::lonnet::current_machine_domains();
 5445:         if (grep(/^\Q$cdom\E$/,@domains)) {
 5446:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 5447:             @lines = <$fh>;
 5448:             close($fh);
 5449:         } else {
 5450:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
 5451:             @lines = <$fh>;
 5452:             close($fh);
 5453:         }
 5454:     }
 5455:     return @lines;
 5456: }
 5457: 
 5458: =pod 
 5459: 
 5460: =item scantron_CODElist
 5461: 
 5462:   Returns html drop down of the saved CODE lists from current course,
 5463:   generated from earlier printings.
 5464: 
 5465: =cut
 5466: 
 5467: sub scantron_CODElist {
 5468:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5469:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5470:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 5471:     my $namechoice='<option></option>';
 5472:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 5473: 	if ($name =~ /^error: 2 /) { next; }
 5474: 	if ($name =~ /^type\0/) { next; }
 5475: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 5476:     }
 5477:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 5478:     return $namechoice;
 5479: }
 5480: 
 5481: =pod 
 5482: 
 5483: =item scantron_CODEunique
 5484: 
 5485:   Returns the html for "Each CODE to be used once" radio.
 5486: 
 5487: =cut
 5488: 
 5489: sub scantron_CODEunique {
 5490:     my $result='<span class="LC_nobreak">
 5491:                  <label><input type="radio" name="scantron_CODEunique"
 5492:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 5493:                 </span>
 5494:                 <span class="LC_nobreak">
 5495:                  <label><input type="radio" name="scantron_CODEunique"
 5496:                         value="no" />'.&mt('No').' </label>
 5497:                 </span>';
 5498:     return $result;
 5499: }
 5500: 
 5501: =pod 
 5502: 
 5503: =item scantron_selectphase
 5504: 
 5505:   Generates the initial screen to start the bubblesheet process.
 5506:   Allows for - starting a grading run.
 5507:              - downloading existing scan data (original, corrected
 5508:                                                 or skipped info)
 5509: 
 5510:              - uploading new scan data
 5511: 
 5512:  Arguments:
 5513:   $r          - The Apache request object
 5514:   $file2grade - name of the file that contain the scanned data to score
 5515: 
 5516: =cut
 5517: 
 5518: sub scantron_selectphase {
 5519:     my ($r,$file2grade,$symb) = @_;
 5520:     if (!$symb) {return '';}
 5521:     my $map_error;
 5522:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
 5523:     if ($map_error) {
 5524:         $r->print('<br />'.&navmap_errormsg().'<br />');
 5525:         return;
 5526:     }
 5527:     my $default_form_data=&defaultFormData($symb);
 5528:     my $file_selector=&scantron_uploads($file2grade);
 5529:     my $format_selector=&scantron_scantab();
 5530:     my $CODE_selector=&scantron_CODElist();
 5531:     my $CODE_unique=&scantron_CODEunique();
 5532:     my $result;
 5533: 
 5534:     $ssi_error = 0;
 5535: 
 5536:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 5537:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 5538: 
 5539: 	# Chunk of form to prompt for a scantron file upload.
 5540: 
 5541:         $r->print('
 5542:     <br />
 5543:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5544:        '.&Apache::loncommon::start_data_table_header_row().'
 5545:             <th>
 5546:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
 5547:             </th>
 5548:        '.&Apache::loncommon::end_data_table_header_row().'
 5549:        '.&Apache::loncommon::start_data_table_row().'
 5550:             <td>
 5551: ');
 5552:     my $default_form_data=&defaultFormData($symb);
 5553:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5554:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 5555:     $r->print(&Apache::lonhtmlcommon::scripttag('
 5556:     function checkUpload(formname) {
 5557: 	if (formname.upfile.value == "") {
 5558: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
 5559: 	    return false;
 5560: 	}
 5561: 	formname.submit();
 5562:     }'));
 5563:     $r->print('
 5564:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 5565:                 '.$default_form_data.'
 5566:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 5567:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 5568:                 <input name="command" value="scantronupload_save" type="hidden" />
 5569:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
 5570:                 <br />
 5571:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 5572:               </form>
 5573: ');
 5574: 
 5575:         $r->print('
 5576:             </td>
 5577:        '.&Apache::loncommon::end_data_table_row().'
 5578:        '.&Apache::loncommon::end_data_table().'
 5579: ');
 5580:     }
 5581: 
 5582:     # Chunk of form to prompt for a file to grade and how:
 5583: 
 5584:     $result.= '
 5585:     <br />
 5586:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 5587:     <input type="hidden" name="command" value="scantron_warning" />
 5588:     '.$default_form_data.'
 5589:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5590:        '.&Apache::loncommon::start_data_table_header_row().'
 5591:             <th colspan="2">
 5592:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 5593:             </th>
 5594:        '.&Apache::loncommon::end_data_table_header_row().'
 5595:        '.&Apache::loncommon::start_data_table_row().'
 5596:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 5597:        '.&Apache::loncommon::end_data_table_row().'
 5598:        '.&Apache::loncommon::start_data_table_row().'
 5599:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
 5600:        '.&Apache::loncommon::end_data_table_row().'
 5601:        '.&Apache::loncommon::start_data_table_row().'
 5602:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
 5603:        '.&Apache::loncommon::end_data_table_row().'
 5604:        '.&Apache::loncommon::start_data_table_row().'
 5605:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 5606:        '.&Apache::loncommon::end_data_table_row().'
 5607:        '.&Apache::loncommon::start_data_table_row().'
 5608:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 5609:        '.&Apache::loncommon::end_data_table_row().'
 5610:        '.&Apache::loncommon::start_data_table_row().'
 5611: 	    <td> '.&mt('Options:').' </td>
 5612:             <td>
 5613: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 5614:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 5615:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 5616: 	    </td>
 5617:        '.&Apache::loncommon::end_data_table_row().'
 5618:        '.&Apache::loncommon::start_data_table_row().'
 5619:             <td colspan="2">
 5620:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
 5621:             </td>
 5622:        '.&Apache::loncommon::end_data_table_row().'
 5623:     '.&Apache::loncommon::end_data_table().'
 5624:     </form>
 5625: ';
 5626:    
 5627:     $r->print($result);
 5628: 
 5629: 
 5630: 
 5631:     # Chunk of the form that prompts to view a scoring office file,
 5632:     # corrected file, skipped records in a file.
 5633: 
 5634:     $r->print('
 5635:    <br />
 5636:    <form action="/adm/grades" name="scantron_download">
 5637:      '.$default_form_data.'
 5638:      <input type="hidden" name="command" value="scantron_download" />
 5639:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5640:        '.&Apache::loncommon::start_data_table_header_row().'
 5641:               <th>
 5642:                 &nbsp;'.&mt('Download a scoring office file').'
 5643:               </th>
 5644:        '.&Apache::loncommon::end_data_table_header_row().'
 5645:        '.&Apache::loncommon::start_data_table_row().'
 5646:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 5647:                 <br />
 5648:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 5649:        '.&Apache::loncommon::end_data_table_row().'
 5650:      '.&Apache::loncommon::end_data_table().'
 5651:    </form>
 5652:    <br />
 5653: ');
 5654: 
 5655:     &Apache::lonpickcode::code_list($r,2);
 5656: 
 5657:     $r->print('<br /><form method="post" name="checkscantron" action="">'.
 5658:              $default_form_data."\n".
 5659:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 5660:              &Apache::loncommon::start_data_table_header_row()."\n".
 5661:              '<th colspan="2">
 5662:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
 5663:              '</th>'."\n".
 5664:               &Apache::loncommon::end_data_table_header_row()."\n".
 5665:               &Apache::loncommon::start_data_table_row()."\n".
 5666:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 5667:               '<td> '.$sequence_selector.' </td>'.
 5668:               &Apache::loncommon::end_data_table_row()."\n".
 5669:               &Apache::loncommon::start_data_table_row()."\n".
 5670:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 5671:               '<td> '.$file_selector.' </td>'."\n".
 5672:               &Apache::loncommon::end_data_table_row()."\n".
 5673:               &Apache::loncommon::start_data_table_row()."\n".
 5674:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 5675:               '<td> '.$format_selector.' </td>'."\n".
 5676:               &Apache::loncommon::end_data_table_row()."\n".
 5677:               &Apache::loncommon::start_data_table_row()."\n".
 5678:               '<td> '.&mt('Options').' </td>'."\n".
 5679:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
 5680:               &Apache::loncommon::end_data_table_row()."\n".
 5681:               &Apache::loncommon::start_data_table_row()."\n".
 5682:               '<td colspan="2">'."\n".
 5683:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 5684:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
 5685:               '</td>'."\n".
 5686:               &Apache::loncommon::end_data_table_row()."\n".
 5687:               &Apache::loncommon::end_data_table()."\n".
 5688:               '</form><br />');
 5689:     return;
 5690: }
 5691: 
 5692: =pod
 5693: 
 5694: =item get_scantron_config
 5695: 
 5696:    Parse and return the bubblesheet configuration line selected as a
 5697:    hash of configuration file fields.
 5698: 
 5699:  Arguments:
 5700:     which - the name of the configuration to parse from the file.
 5701: 
 5702: 
 5703:  Returns:
 5704:             If the named configuration is not in the file, an empty
 5705:             hash is returned.
 5706:     a hash with the fields
 5707:       name         - internal name for the this configuration setup
 5708:       description  - text to display to operator that describes this config
 5709:       CODElocation - if 0 or the string 'none'
 5710:                           - no CODE exists for this config
 5711:                      if -1 || the string 'letter'
 5712:                           - a CODE exists for this config and is
 5713:                             a string of letters
 5714:                      Unsupported value (but planned for future support)
 5715:                           if a positive integer
 5716:                                - The CODE exists as the first n items from
 5717:                                  the question section of the form
 5718:                           if the string 'number'
 5719:                                - The CODE exists for this config and is
 5720:                                  a string of numbers
 5721:       CODEstart   - (only matter if a CODE exists) column in the line where
 5722:                      the CODE starts
 5723:       CODElength  - length of the CODE
 5724:       IDstart     - column where the student/employee ID starts
 5725:       IDlength    - length of the student/employee ID info
 5726:       Qstart      - column where the information from the bubbled
 5727:                     'questions' start
 5728:       Qlength     - number of columns comprising a single bubble line from
 5729:                     the sheet. (usually either 1 or 10)
 5730:       Qon         - either a single character representing the character used
 5731:                     to signal a bubble was chosen in the positional setup, or
 5732:                     the string 'letter' if the letter of the chosen bubble is
 5733:                     in the final, or 'number' if a number representing the
 5734:                     chosen bubble is in the file (1->A 0->J)
 5735:       Qoff        - the character used to represent that a bubble was
 5736:                     left blank
 5737:       PaperID     - if the scanning process generates a unique number for each
 5738:                     sheet scanned the column that this ID number starts in
 5739:       PaperIDlength - number of columns that comprise the unique ID number
 5740:                       for the sheet of paper
 5741:       FirstName   - column that the first name starts in
 5742:       FirstNameLength - number of columns that the first name spans
 5743:  
 5744:       LastName    - column that the last name starts in
 5745:       LastNameLength - number of columns that the last name spans
 5746:       BubblesPerRow - number of bubbles available in each row used to 
 5747:                       bubble an answer. (If not specified, 10 assumed).
 5748: 
 5749: =cut
 5750: 
 5751: sub get_scantron_config {
 5752:     my ($which) = @_;
 5753:     my @lines = &get_scantronformat_file();
 5754:     my %config;
 5755:     #FIXME probably should move to XML it has already gotten a bit much now
 5756:     foreach my $line (@lines) {
 5757: 	my ($name,$descrip)=split(/:/,$line);
 5758: 	if ($name ne $which ) { next; }
 5759: 	chomp($line);
 5760: 	my @config=split(/:/,$line);
 5761: 	$config{'name'}=$config[0];
 5762: 	$config{'description'}=$config[1];
 5763: 	$config{'CODElocation'}=$config[2];
 5764: 	$config{'CODEstart'}=$config[3];
 5765: 	$config{'CODElength'}=$config[4];
 5766: 	$config{'IDstart'}=$config[5];
 5767: 	$config{'IDlength'}=$config[6];
 5768: 	$config{'Qstart'}=$config[7];
 5769:  	$config{'Qlength'}=$config[8];
 5770: 	$config{'Qoff'}=$config[9];
 5771: 	$config{'Qon'}=$config[10];
 5772: 	$config{'PaperID'}=$config[11];
 5773: 	$config{'PaperIDlength'}=$config[12];
 5774: 	$config{'FirstName'}=$config[13];
 5775: 	$config{'FirstNamelength'}=$config[14];
 5776: 	$config{'LastName'}=$config[15];
 5777: 	$config{'LastNamelength'}=$config[16];
 5778:         $config{'BubblesPerRow'}=$config[17];
 5779: 	last;
 5780:     }
 5781:     return %config;
 5782: }
 5783: 
 5784: =pod 
 5785: 
 5786: =item username_to_idmap
 5787: 
 5788:     creates a hash keyed by student/employee ID with values of the corresponding
 5789:     student username:domain.
 5790: 
 5791:   Arguments:
 5792: 
 5793:     $classlist - reference to the class list hash. This is a hash
 5794:                  keyed by student name:domain  whose elements are references
 5795:                  to arrays containing various chunks of information
 5796:                  about the student. (See loncoursedata for more info).
 5797: 
 5798:   Returns
 5799:     %idmap - the constructed hash
 5800: 
 5801: =cut
 5802: 
 5803: sub username_to_idmap {
 5804:     my ($classlist)= @_;
 5805:     my %idmap;
 5806:     foreach my $student (keys(%$classlist)) {
 5807: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
 5808: 	    $student;
 5809:     }
 5810:     return %idmap;
 5811: }
 5812: 
 5813: =pod
 5814: 
 5815: =item scantron_fixup_scanline
 5816: 
 5817:    Process a requested correction to a scanline.
 5818: 
 5819:   Arguments:
 5820:     $scantron_config   - hash from &get_scantron_config()
 5821:     $scan_data         - hash of correction information 
 5822:                           (see &scantron_getfile())
 5823:     $line              - existing scanline
 5824:     $whichline         - line number of the passed in scanline
 5825:     $field             - type of change to process 
 5826:                          (either 
 5827:                           'ID'     -> correct the student/employee ID
 5828:                           'CODE'   -> correct the CODE
 5829:                           'answer' -> fixup the submitted answers)
 5830:     
 5831:    $args               - hash of additional info,
 5832:                           - 'ID' 
 5833:                                'newid' -> studentID to use in replacement
 5834:                                           of existing one
 5835:                           - 'CODE' 
 5836:                                'CODE_ignore_dup' - set to true if duplicates
 5837:                                                    should be ignored.
 5838: 	                       'CODE' - is new code or 'use_unfound'
 5839:                                         if the existing unfound code should
 5840:                                         be used as is
 5841:                           - 'answer'
 5842:                                'response' - new answer or 'none' if blank
 5843:                                'question' - the bubble line to change
 5844:                                'questionnum' - the question identifier,
 5845:                                                may include subquestion. 
 5846: 
 5847:   Returns:
 5848:     $line - the modified scanline
 5849: 
 5850:   Side effects: 
 5851:     $scan_data - may be updated
 5852: 
 5853: =cut
 5854: 
 5855: 
 5856: sub scantron_fixup_scanline {
 5857:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 5858:     if ($field eq 'ID') {
 5859: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 5860: 	    return ($line,1,'New value too large');
 5861: 	}
 5862: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 5863: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 5864: 				     $args->{'newid'});
 5865: 	}
 5866: 	substr($line,$$scantron_config{'IDstart'}-1,
 5867: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 5868: 	if ($args->{'newid'}=~/^\s*$/) {
 5869: 	    &scan_data($scan_data,"$whichline.user",
 5870: 		       $args->{'username'}.':'.$args->{'domain'});
 5871: 	}
 5872:     } elsif ($field eq 'CODE') {
 5873: 	if ($args->{'CODE_ignore_dup'}) {
 5874: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 5875: 	}
 5876: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 5877: 	if ($args->{'CODE'} ne 'use_unfound') {
 5878: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 5879: 		return ($line,1,'New CODE value too large');
 5880: 	    }
 5881: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 5882: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 5883: 	    }
 5884: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 5885: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 5886: 	}
 5887:     } elsif ($field eq 'answer') {
 5888: 	my $length=$scantron_config->{'Qlength'};
 5889: 	my $off=$scantron_config->{'Qoff'};
 5890: 	my $on=$scantron_config->{'Qon'};
 5891: 	my $answer=${off}x$length;
 5892: 	if ($args->{'response'} eq 'none') {
 5893: 	    &scan_data($scan_data,
 5894: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 5895: 	} else {
 5896: 	    if ($on eq 'letter') {
 5897: 		my @alphabet=('A'..'Z');
 5898: 		$answer=$alphabet[$args->{'response'}];
 5899: 	    } elsif ($on eq 'number') {
 5900: 		$answer=$args->{'response'}+1;
 5901: 		if ($answer == 10) { $answer = '0'; }
 5902: 	    } else {
 5903: 		substr($answer,$args->{'response'},1)=$on;
 5904: 	    }
 5905: 	    &scan_data($scan_data,
 5906: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 5907: 	}
 5908: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 5909: 	substr($line,$where-1,$length)=$answer;
 5910:     }
 5911:     return $line;
 5912: }
 5913: 
 5914: =pod
 5915: 
 5916: =item scan_data
 5917: 
 5918:     Edit or look up  an item in the scan_data hash.
 5919: 
 5920:   Arguments:
 5921:     $scan_data  - The hash (see scantron_getfile)
 5922:     $key        - shorthand of the key to edit (actual key is
 5923:                   scantronfilename_key).
 5924:     $data        - New value of the hash entry.
 5925:     $delete      - If true, the entry is removed from the hash.
 5926: 
 5927:   Returns:
 5928:     The new value of the hash table field (undefined if deleted).
 5929: 
 5930: =cut
 5931: 
 5932: 
 5933: sub scan_data {
 5934:     my ($scan_data,$key,$value,$delete)=@_;
 5935:     my $filename=$env{'form.scantron_selectfile'};
 5936:     if (defined($value)) {
 5937: 	$scan_data->{$filename.'_'.$key} = $value;
 5938:     }
 5939:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 5940:     return $scan_data->{$filename.'_'.$key};
 5941: }
 5942: 
 5943: # ----- These first few routines are general use routines.----
 5944: 
 5945: # Return the number of occurences of a pattern in a string.
 5946: 
 5947: sub occurence_count {
 5948:     my ($string, $pattern) = @_;
 5949: 
 5950:     my @matches = ($string =~ /$pattern/g);
 5951: 
 5952:     return scalar(@matches);
 5953: }
 5954: 
 5955: 
 5956: # Take a string known to have digits and convert all the
 5957: # digits into letters in the range J,A..I.
 5958: 
 5959: sub digits_to_letters {
 5960:     my ($input) = @_;
 5961: 
 5962:     my @alphabet = ('J', 'A'..'I');
 5963: 
 5964:     my @input    = split(//, $input);
 5965:     my $output ='';
 5966:     for (my $i = 0; $i < scalar(@input); $i++) {
 5967: 	if ($input[$i] =~ /\d/) {
 5968: 	    $output .= $alphabet[$input[$i]];
 5969: 	} else {
 5970: 	    $output .= $input[$i];
 5971: 	}
 5972:     }
 5973:     return $output;
 5974: }
 5975: 
 5976: =pod 
 5977: 
 5978: =item scantron_parse_scanline
 5979: 
 5980:   Decodes a scanline from the selected bubblesheet file
 5981: 
 5982:  Arguments:
 5983:     line             - The text of the bubblesheet file line to process
 5984:     whichline        - Line number
 5985:     scantron_config  - Hash describing the format of the bubblesheet lines.
 5986:     scan_data        - Hash of extra information about the scanline
 5987:                        (see scantron_getfile for more information)
 5988:     just_header      - True if should not process question answers but only
 5989:                        the stuff to the left of the answers.
 5990:     randomorder      - True if randomorder in use
 5991:     randompick       - True if randompick in use
 5992:     sequence         - Exam folder URL
 5993:     master_seq       - Ref to array containing symbs in exam folder
 5994:     symb_to_resource - Ref to hash of symbs for resources in exam folder
 5995:                        (corresponding values are resource objects)
 5996:     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
 5997:     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
 5998:                        are refs to an array of resource objects, ordered
 5999:                        according to order used for CODE, when randomorder
 6000:                        and or randompick are in use.
 6001:     respnumlookup    - Ref to hash mapping question numbers in bubble lines
 6002:                        for current line to question number used for same question
 6003:                         in "Master Sequence" (as seen by Course Coordinator).
 6004:     startline        - Ref to hash where key is question number (0 is first)
 6005:                        and value is number of first bubble line for current 
 6006:                        student or code-based randompick and/or randomorder.
 6007:     totalref         - Ref of scalar used to score total number of bubble
 6008:                        lines needed for responses in a scan line (used when
 6009:                        randompick in use. 
 6010:     
 6011:  Returns:
 6012:    Hash containing the result of parsing the scanline
 6013: 
 6014:    Keys are all proceeded by the string 'scantron.'
 6015: 
 6016:        CODE    - the CODE in use for this scanline
 6017:        useCODE - 1 if the CODE is invalid but it usage has been forced
 6018:                  by the operator
 6019:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 6020:                             CODEs were selected, but the usage has been
 6021:                             forced by the operator
 6022:        ID  - student/employee ID
 6023:        PaperID - if used, the ID number printed on the sheet when the 
 6024:                  paper was scanned
 6025:        FirstName - first name from the sheet
 6026:        LastName  - last name from the sheet
 6027: 
 6028:      if just_header was not true these key may also exist
 6029: 
 6030:        missingerror - a list of bubble ranges that are considered to be answers
 6031:                       to a single question that don't have any bubbles filled in.
 6032:                       Of the form questionnumber:firstbubblenumber:count.
 6033:        doubleerror  - a list of bubble ranges that are considered to be answers
 6034:                       to a single question that have more than one bubble filled in.
 6035:                       Of the form questionnumber::firstbubblenumber:count
 6036:    
 6037:                 In the above, count is the number of bubble responses in the
 6038:                 input line needed to represent the possible answers to the question.
 6039:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 6040:                 per line would have count = 2.
 6041: 
 6042:        maxquest     - the number of the last bubble line that was parsed
 6043: 
 6044:        (<number> starts at 1)
 6045:        <number>.answer - zero or more letters representing the selected
 6046:                          letters from the scanline for the bubble line 
 6047:                          <number>.
 6048:                          if blank there was either no bubble or there where
 6049:                          multiple bubbles, (consult the keys missingerror and
 6050:                          doubleerror if this is an error condition)
 6051: 
 6052: =cut
 6053: 
 6054: sub scantron_parse_scanline {
 6055:     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
 6056:         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
 6057:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
 6058: 
 6059:     my %record;
 6060:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
 6061:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 6062: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 6063: 	if ($$scantron_config{'CODElocation'} < 0 ||
 6064: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 6065: 	    $$scantron_config{'CODElocation'} eq 'number') {
 6066: 	    $record{'scantron.CODE'}=substr($data,
 6067: 					    $$scantron_config{'CODEstart'}-1,
 6068: 					    $$scantron_config{'CODElength'});
 6069: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 6070: 		$record{'scantron.useCODE'}=1;
 6071: 	    }
 6072: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 6073: 		$record{'scantron.CODE_ignore_dup'}=1;
 6074: 	    }
 6075: 	} else {
 6076: 	    #FIXME interpret first N questions
 6077: 	}
 6078:     }
 6079:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 6080: 				  $$scantron_config{'IDlength'});
 6081:     $record{'scantron.PaperID'}=
 6082: 	substr($data,$$scantron_config{'PaperID'}-1,
 6083: 	       $$scantron_config{'PaperIDlength'});
 6084:     $record{'scantron.FirstName'}=
 6085: 	substr($data,$$scantron_config{'FirstName'}-1,
 6086: 	       $$scantron_config{'FirstNamelength'});
 6087:     $record{'scantron.LastName'}=
 6088: 	substr($data,$$scantron_config{'LastName'}-1,
 6089: 	       $$scantron_config{'LastNamelength'});
 6090:     if ($just_header) { return \%record; }
 6091: 
 6092:     my @alphabet=('A'..'Z');
 6093:     my $questnum=0;
 6094:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 6095: 
 6096:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 6097:     if ($randompick || $randomorder) {
 6098:         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
 6099:                                          $master_seq,$symb_to_resource,
 6100:                                          $partids_by_symb,$orderedforcode,
 6101:                                          $respnumlookup,$startline);
 6102:         if ($total) {
 6103:             $lastpos = $total*$$scantron_config{'Qlength'}; 
 6104:         }
 6105:         if (ref($totalref)) {
 6106:             $$totalref = $total;
 6107:         }
 6108:     }
 6109:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 6110:     chomp($questions);		# Get rid of any trailing \n.
 6111:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 6112:     while (length($questions)) {
 6113:         my $answers_needed;
 6114:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6115:             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
 6116:         } else {
 6117: 	    $answers_needed = $bubble_lines_per_response{$questnum};
 6118:         }
 6119:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 6120:                              || 1;
 6121:         $questnum++;
 6122:         my $quest_id = $questnum;
 6123:         my $currentquest = substr($questions,0,$answer_length);
 6124:         $questions       = substr($questions,$answer_length);
 6125:         if (length($currentquest) < $answer_length) { next; }
 6126: 
 6127:         my $subdivided;
 6128:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6129:             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
 6130:         } else {
 6131:             $subdivided = $subdivided_bubble_lines{$questnum-1};
 6132:         }
 6133:         if ($subdivided =~ /,/) {
 6134:             my $subquestnum = 1;
 6135:             my $subquestions = $currentquest;
 6136:             my @subanswers_needed = split(/,/,$subdivided);
 6137:             foreach my $subans (@subanswers_needed) {
 6138:                 my $subans_length =
 6139:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 6140:                 my $currsubquest = substr($subquestions,0,$subans_length);
 6141:                 $subquestions   = substr($subquestions,$subans_length);
 6142:                 $quest_id = "$questnum.$subquestnum";
 6143:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 6144:                     ($$scantron_config{'Qon'} eq 'number')) {
 6145:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 6146:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6147:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6148:                         $randomorder,$randompick,$respnumlookup);
 6149:                 } else {
 6150:                     $ansnum = &scantron_validator_positional($ansnum,
 6151:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6152:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6153:                         $randomorder,$randompick,$respnumlookup);
 6154:                 }
 6155:                 $subquestnum ++;
 6156:             }
 6157:         } else {
 6158:             if (($$scantron_config{'Qon'} eq 'letter') ||
 6159:                 ($$scantron_config{'Qon'} eq 'number')) {
 6160:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 6161:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6162:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6163:                     $randomorder,$randompick,$respnumlookup);
 6164:             } else {
 6165:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 6166:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6167:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6168:                     $randomorder,$randompick,$respnumlookup);
 6169:             }
 6170:         }
 6171:     }
 6172:     $record{'scantron.maxquest'}=$questnum;
 6173:     return \%record;
 6174: }
 6175: 
 6176: sub get_master_seq {
 6177:     my ($resources,$master_seq,$symb_to_resource) = @_;
 6178:     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') && 
 6179:                    (ref($symb_to_resource) eq 'HASH'));
 6180:     my $resource_error;
 6181:     foreach my $resource (@{$resources}) {
 6182:         my $ressymb;
 6183:         if (ref($resource)) {
 6184:             $ressymb = $resource->symb();
 6185:             push(@{$master_seq},$ressymb);
 6186:             $symb_to_resource->{$ressymb} = $resource;
 6187:         } else {
 6188:             $resource_error = 1;
 6189:             last;
 6190:         }
 6191:     }
 6192:     return $resource_error;
 6193: }
 6194: 
 6195: sub get_respnum_lookups {
 6196:     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
 6197:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
 6198:     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
 6199:                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
 6200:                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
 6201:                    (ref($startline) eq 'HASH'));
 6202:     my ($user,$scancode);
 6203:     if ((exists($record->{'scantron.CODE'})) &&
 6204:         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
 6205:         $scancode = $record->{'scantron.CODE'};
 6206:     } else {
 6207:         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
 6208:     }
 6209:     my @mapresources =
 6210:         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
 6211:                      $orderedforcode);
 6212:     my $total = 0;
 6213:     my $count = 0;
 6214:     foreach my $resource (@mapresources) {
 6215:         my $id = $resource->id();
 6216:         my $symb = $resource->symb();
 6217:         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
 6218:             foreach my $partid (@{$partids_by_symb->{$symb}}) {
 6219:                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
 6220:                 if ($respnum ne '') {
 6221:                     $respnumlookup->{$count} = $respnum;
 6222:                     $startline->{$count} = $total;
 6223:                     $total += $bubble_lines_per_response{$respnum};
 6224:                     $count ++;
 6225:                 }
 6226:             }
 6227:         }
 6228:     }
 6229:     return $total;
 6230: }
 6231: 
 6232: sub scantron_validator_lettnum {
 6233:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 6234:         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
 6235:         $randompick,$respnumlookup) = @_;
 6236: 
 6237:     # Qon 'letter' implies for each slot in currquest we have:
 6238:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 6239:     #    about anything else (esp. a value of Qoff) for missing
 6240:     #    bubbles.
 6241:     #
 6242:     # Qon 'number' implies each slot gives a digit that indexes the
 6243:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 6244:     #    and * or ? for double bubbles on a single line.
 6245:     #
 6246: 
 6247:     my $matchon;
 6248:     if ($$scantron_config{'Qon'} eq 'letter') {
 6249:         $matchon = '[A-Z]';
 6250:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 6251:         $matchon = '\d';
 6252:     }
 6253:     my $occurrences = 0;
 6254:     my $responsenum = $questnum-1;
 6255:     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6256:        $responsenum = $respnumlookup->{$questnum-1} 
 6257:     }
 6258:     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6259:         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6260:         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6261:         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6262:         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6263:         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6264:         my @singlelines = split('',$currquest);
 6265:         foreach my $entry (@singlelines) {
 6266:             $occurrences = &occurence_count($entry,$matchon);
 6267:             if ($occurrences > 1) {
 6268:                 last;
 6269:             }
 6270:         }
 6271:     } else {
 6272:         $occurrences = &occurence_count($currquest,$matchon); 
 6273:     }
 6274:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 6275:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6276:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6277:             my $bubble = substr($currquest,$ans,1);
 6278:             if ($bubble =~ /$matchon/ ) {
 6279:                 if ($$scantron_config{'Qon'} eq 'number') {
 6280:                     if ($bubble == 0) {
 6281:                         $bubble = 10; 
 6282:                     }
 6283:                     $record->{"scantron.$ansnum.answer"} = 
 6284:                         $alphabet->[$bubble-1];
 6285:                 } else {
 6286:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 6287:                 }
 6288:             } else {
 6289:                 $record->{"scantron.$ansnum.answer"}='';
 6290:             }
 6291:             $ansnum++;
 6292:         }
 6293:     } elsif (!defined($currquest)
 6294:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 6295:             || (&occurence_count($currquest,$matchon) == 0)) {
 6296:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6297:             $record->{"scantron.$ansnum.answer"}='';
 6298:             $ansnum++;
 6299:         }
 6300:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6301:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 6302:         }
 6303:     } else {
 6304:         if ($$scantron_config{'Qon'} eq 'number') {
 6305:             $currquest = &digits_to_letters($currquest);            
 6306:         }
 6307:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6308:             my $bubble = substr($currquest,$ans,1);
 6309:             $record->{"scantron.$ansnum.answer"} = $bubble;
 6310:             $ansnum++;
 6311:         }
 6312:     }
 6313:     return $ansnum;
 6314: }
 6315: 
 6316: sub scantron_validator_positional {
 6317:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 6318:         $whichline,$alphabet,$record,$scantron_config,$scan_data,
 6319:         $randomorder,$randompick,$respnumlookup) = @_;
 6320: 
 6321:     # Otherwise there's a positional notation;
 6322:     # each bubble line requires Qlength items, and there are filled in
 6323:     # bubbles for each case where there 'Qon' characters.
 6324:     #
 6325: 
 6326:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 6327: 
 6328:     # If the split only gives us one element.. the full length of the
 6329:     # answer string, no bubbles are filled in:
 6330: 
 6331:     if ($answers_needed eq '') {
 6332:         return;
 6333:     }
 6334: 
 6335:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 6336:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6337:             $record->{"scantron.$ansnum.answer"}='';
 6338:             $ansnum++;
 6339:         }
 6340:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6341:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 6342:         }
 6343:     } elsif (scalar(@array) == 2) {
 6344:         my $location = length($array[0]);
 6345:         my $line_num = int($location / $$scantron_config{'Qlength'});
 6346:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 6347:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6348:             if ($ans eq $line_num) {
 6349:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 6350:             } else {
 6351:                 $record->{"scantron.$ansnum.answer"} = ' ';
 6352:             }
 6353:             $ansnum++;
 6354:          }
 6355:     } else {
 6356:         #  If there's more than one instance of a bubble character
 6357:         #  That's a double bubble; with positional notation we can
 6358:         #  record all the bubbles filled in as well as the
 6359:         #  fact this response consists of multiple bubbles.
 6360:         #
 6361:         my $responsenum = $questnum-1;
 6362:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6363:             $responsenum = $respnumlookup->{$questnum-1}
 6364:         }
 6365:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6366:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6367:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6368:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6369:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6370:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6371:             my $doubleerror = 0;
 6372:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 6373:                    (!$doubleerror)) {
 6374:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 6375:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 6376:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 6377:                if (length(@currarray) > 2) {
 6378:                    $doubleerror = 1;
 6379:                } 
 6380:             }
 6381:             if ($doubleerror) {
 6382:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6383:             }
 6384:         } else {
 6385:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6386:         }
 6387:         my $item = $ansnum;
 6388:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6389:             $record->{"scantron.$item.answer"} = '';
 6390:             $item ++;
 6391:         }
 6392: 
 6393:         my @ans=@array;
 6394:         my $i=0;
 6395:         my $increment = 0;
 6396:         while ($#ans) {
 6397:             $i+=length($ans[0]) + $increment;
 6398:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 6399:             my $bubble = $i%$$scantron_config{'Qlength'};
 6400:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 6401:             shift(@ans);
 6402:             $increment = 1;
 6403:         }
 6404:         $ansnum += $answers_needed;
 6405:     }
 6406:     return $ansnum;
 6407: }
 6408: 
 6409: =pod
 6410: 
 6411: =item scantron_add_delay
 6412: 
 6413:    Adds an error message that occurred during the grading phase to a
 6414:    queue of messages to be shown after grading pass is complete
 6415: 
 6416:  Arguments:
 6417:    $delayqueue  - arrary ref of hash ref of error messages
 6418:    $scanline    - the scanline that caused the error
 6419:    $errormesage - the error message
 6420:    $errorcode   - a numeric code for the error
 6421: 
 6422:  Side Effects:
 6423:    updates the $delayqueue to have a new hash ref of the error
 6424: 
 6425: =cut
 6426: 
 6427: sub scantron_add_delay {
 6428:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 6429:     push(@$delayqueue,
 6430: 	 {'line' => $scanline, 'emsg' => $errormessage,
 6431: 	  'ecode' => $errorcode }
 6432: 	 );
 6433: }
 6434: 
 6435: =pod
 6436: 
 6437: =item scantron_find_student
 6438: 
 6439:    Finds the username for the current scanline
 6440: 
 6441:   Arguments:
 6442:    $scantron_record - hash result from scantron_parse_scanline
 6443:    $scan_data       - hash of correction information 
 6444:                       (see &scantron_getfile() form more information)
 6445:    $idmap           - hash from &username_to_idmap()
 6446:    $line            - number of current scanline
 6447:  
 6448:   Returns:
 6449:    Either 'username:domain' or undef if unknown
 6450: 
 6451: =cut
 6452: 
 6453: sub scantron_find_student {
 6454:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 6455:     my $scanID=$$scantron_record{'scantron.ID'};
 6456:     if ($scanID =~ /^\s*$/) {
 6457:  	return &scan_data($scan_data,"$line.user");
 6458:     }
 6459:     foreach my $id (keys(%$idmap)) {
 6460:  	if (lc($id) eq lc($scanID)) {
 6461:  	    return $$idmap{$id};
 6462:  	}
 6463:     }
 6464:     return undef;
 6465: }
 6466: 
 6467: =pod
 6468: 
 6469: =item scantron_filter
 6470: 
 6471:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 6472:    hidden resources was selected
 6473: 
 6474: =cut
 6475: 
 6476: sub scantron_filter {
 6477:     my ($curres)=@_;
 6478: 
 6479:     if (ref($curres) && $curres->is_problem()) {
 6480: 	# if the user has asked to not have either hidden
 6481: 	# or 'randomout' controlled resources to be graded
 6482: 	# don't include them
 6483: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6484: 	    && $curres->randomout) {
 6485: 	    return 0;
 6486: 	}
 6487: 	return 1;
 6488:     }
 6489:     return 0;
 6490: }
 6491: 
 6492: =pod
 6493: 
 6494: =item scantron_process_corrections
 6495: 
 6496:    Gets correction information out of submitted form data and corrects
 6497:    the scanline
 6498: 
 6499: =cut
 6500: 
 6501: sub scantron_process_corrections {
 6502:     my ($r) = @_;
 6503:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6504:     my ($scanlines,$scan_data)=&scantron_getfile();
 6505:     my $classlist=&Apache::loncoursedata::get_classlist();
 6506:     my $which=$env{'form.scantron_line'};
 6507:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 6508:     my ($skip,$err,$errmsg);
 6509:     if ($env{'form.scantron_skip_record'}) {
 6510: 	$skip=1;
 6511:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 6512: 	my $newstudent=$env{'form.scantron_username'}.':'.
 6513: 	    $env{'form.scantron_domain'};
 6514: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 6515: 	($line,$err,$errmsg)=
 6516: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6517: 				     'ID',{'newid'=>$newid,
 6518: 				    'username'=>$env{'form.scantron_username'},
 6519: 				    'domain'=>$env{'form.scantron_domain'}});
 6520:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 6521: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 6522: 	my $newCODE;
 6523: 	my %args;
 6524: 	if      ($resolution eq 'use_unfound') {
 6525: 	    $newCODE='use_unfound';
 6526: 	} elsif ($resolution eq 'use_found') {
 6527: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 6528: 	} elsif ($resolution eq 'use_typed') {
 6529: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 6530: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 6531: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 6532: 	}
 6533: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 6534: 	    $args{'CODE_ignore_dup'}=1;
 6535: 	}
 6536: 	$args{'CODE'}=$newCODE;
 6537: 	($line,$err,$errmsg)=
 6538: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6539: 				     'CODE',\%args);
 6540:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 6541: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 6542: 	    ($line,$err,$errmsg)=
 6543: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 6544: 					 $which,'answer',
 6545: 					 { 'question'=>$question,
 6546: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 6547:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 6548: 	    if ($err) { last; }
 6549: 	}
 6550:     }
 6551:     if ($err) {
 6552:         $r->print(
 6553:             '<p class="LC_error">'
 6554:            .&mt('Unable to accept last correction, an error occurred: [_1]',
 6555:                 $errmsg)
 6556:            .'</p>');
 6557:     } else {
 6558: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 6559: 	&scantron_putfile($scanlines,$scan_data);
 6560:     }
 6561: }
 6562: 
 6563: =pod
 6564: 
 6565: =item reset_skipping_status
 6566: 
 6567:    Forgets the current set of remember skipped scanlines (and thus
 6568:    reverts back to considering all lines in the
 6569:    scantron_skipped_<filename> file)
 6570: 
 6571: =cut
 6572: 
 6573: sub reset_skipping_status {
 6574:     my ($scanlines,$scan_data)=&scantron_getfile();
 6575:     &scan_data($scan_data,'remember_skipping',undef,1);
 6576:     &scantron_putfile(undef,$scan_data);
 6577: }
 6578: 
 6579: =pod
 6580: 
 6581: =item start_skipping
 6582: 
 6583:    Marks a scanline to be skipped. 
 6584: 
 6585: =cut
 6586: 
 6587: sub start_skipping {
 6588:     my ($scan_data,$i)=@_;
 6589:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6590:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 6591: 	$remembered{$i}=2;
 6592:     } else {
 6593: 	$remembered{$i}=1;
 6594:     }
 6595:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 6596: }
 6597: 
 6598: =pod
 6599: 
 6600: =item should_be_skipped
 6601: 
 6602:    Checks whether a scanline should be skipped.
 6603: 
 6604: =cut
 6605: 
 6606: sub should_be_skipped {
 6607:     my ($scanlines,$scan_data,$i)=@_;
 6608:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 6609: 	# not redoing old skips
 6610: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 6611: 	return 0;
 6612:     }
 6613:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6614: 
 6615:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 6616: 	return 0;
 6617:     }
 6618:     return 1;
 6619: }
 6620: 
 6621: =pod
 6622: 
 6623: =item remember_current_skipped
 6624: 
 6625:    Discovers what scanlines are in the scantron_skipped_<filename>
 6626:    file and remembers them into scan_data for later use.
 6627: 
 6628: =cut
 6629: 
 6630: sub remember_current_skipped {
 6631:     my ($scanlines,$scan_data)=&scantron_getfile();
 6632:     my %to_remember;
 6633:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6634: 	if ($scanlines->{'skipped'}[$i]) {
 6635: 	    $to_remember{$i}=1;
 6636: 	}
 6637:     }
 6638: 
 6639:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 6640:     &scantron_putfile(undef,$scan_data);
 6641: }
 6642: 
 6643: =pod
 6644: 
 6645: =item check_for_error
 6646: 
 6647:     Checks if there was an error when attempting to remove a specific
 6648:     scantron_.. bubblesheet data file. Prints out an error if
 6649:     something went wrong.
 6650: 
 6651: =cut
 6652: 
 6653: sub check_for_error {
 6654:     my ($r,$result)=@_;
 6655:     if ($result ne 'ok' && $result ne 'not_found' ) {
 6656: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 6657:     }
 6658: }
 6659: 
 6660: =pod
 6661: 
 6662: =item scantron_warning_screen
 6663: 
 6664:    Interstitial screen to make sure the operator has selected the
 6665:    correct options before we start the validation phase.
 6666: 
 6667: =cut
 6668: 
 6669: sub scantron_warning_screen {
 6670:     my ($button_text,$symb)=@_;
 6671:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 6672:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6673:     my $CODElist;
 6674:     if ($scantron_config{'CODElocation'} &&
 6675: 	$scantron_config{'CODEstart'} &&
 6676: 	$scantron_config{'CODElength'}) {
 6677: 	$CODElist=$env{'form.scantron_CODElist'};
 6678: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
 6679: 	$CODElist=
 6680: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 6681: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 6682:     }
 6683:     my $lastbubblepoints;
 6684:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 6685:         $lastbubblepoints =
 6686:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
 6687:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
 6688:     }
 6689:     return ('
 6690: <p>
 6691: <span class="LC_warning">
 6692: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
 6693: </p>
 6694: <table>
 6695: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 6696: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 6697: '.$CODElist.$lastbubblepoints.'
 6698: </table>
 6699: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
 6700: '.&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>
 6701: 
 6702: <br />
 6703: ');
 6704: }
 6705: 
 6706: =pod
 6707: 
 6708: =item scantron_do_warning
 6709: 
 6710:    Check if the operator has picked something for all required
 6711:    fields. Error out if something is missing.
 6712: 
 6713: =cut
 6714: 
 6715: sub scantron_do_warning {
 6716:     my ($r,$symb)=@_;
 6717:     if (!$symb) {return '';}
 6718:     my $default_form_data=&defaultFormData($symb);
 6719:     $r->print(&scantron_form_start().$default_form_data);
 6720:     if ( $env{'form.selectpage'} eq '' ||
 6721: 	 $env{'form.scantron_selectfile'} eq '' ||
 6722: 	 $env{'form.scantron_format'} eq '' ) {
 6723: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
 6724: 	if ( $env{'form.selectpage'} eq '') {
 6725: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 6726: 	} 
 6727: 	if ( $env{'form.scantron_selectfile'} eq '') {
 6728: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected a file that contains the student's response data.").'</span></p>');
 6729: 	} 
 6730: 	if ( $env{'form.scantron_format'} eq '') {
 6731: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected the format of the student's response data.").'</span></p>');
 6732: 	} 
 6733:     } else {
 6734: 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
 6735:         my $bubbledbyhand=&hand_bubble_option();
 6736: 	$r->print('
 6737: '.$warning.$bubbledbyhand.'
 6738: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 6739: <input type="hidden" name="command" value="scantron_validate" />
 6740: ');
 6741:     }
 6742:     $r->print("</form><br />");
 6743:     return '';
 6744: }
 6745: 
 6746: =pod
 6747: 
 6748: =item scantron_form_start
 6749: 
 6750:     html hidden input for remembering all selected grading options
 6751: 
 6752: =cut
 6753: 
 6754: sub scantron_form_start {
 6755:     my ($max_bubble)=@_;
 6756:     my $result= <<SCANTRONFORM;
 6757: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 6758:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 6759:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 6760:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 6761:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 6762:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 6763:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 6764:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 6765:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 6766:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 6767: SCANTRONFORM
 6768: 
 6769:   my $line = 0;
 6770:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 6771:        my $chunk =
 6772: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 6773:        $chunk .=
 6774: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 6775:        $chunk .= 
 6776:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 6777:        $chunk .=
 6778:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 6779:        $chunk .=
 6780:            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
 6781:        $result .= $chunk;
 6782:        $line++;
 6783:     }
 6784:     return $result;
 6785: }
 6786: 
 6787: =pod
 6788: 
 6789: =item scantron_validate_file
 6790: 
 6791:     Dispatch routine for doing validation of a bubblesheet data file.
 6792: 
 6793:     Also processes any necessary information resets that need to
 6794:     occur before validation begins (ignore previous corrections,
 6795:     restarting the skipped records processing)
 6796: 
 6797: =cut
 6798: 
 6799: sub scantron_validate_file {
 6800:     my ($r,$symb) = @_;
 6801:     if (!$symb) {return '';}
 6802:     my $default_form_data=&defaultFormData($symb);
 6803:     
 6804:     # do the detection of only doing skipped records first before we delete
 6805:     # them when doing the corrections reset
 6806:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 6807: 	&reset_skipping_status();
 6808:     }
 6809:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 6810: 	&remember_current_skipped();
 6811: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 6812:     }
 6813: 
 6814:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 6815: 	&check_for_error($r,&scantron_remove_file('corrected'));
 6816: 	&check_for_error($r,&scantron_remove_file('skipped'));
 6817: 	&check_for_error($r,&scantron_remove_scan_data());
 6818: 	$env{'form.scantron_options_ignore'}='done';
 6819:     }
 6820: 
 6821:     if ($env{'form.scantron_corrections'}) {
 6822: 	&scantron_process_corrections($r);
 6823:     }
 6824:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 6825:     #get the student pick code ready
 6826:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 6827:     my $nav_error;
 6828:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6829:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 6830:     if ($nav_error) {
 6831:         $r->print(&navmap_errormsg());
 6832:         return '';
 6833:     }
 6834:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 6835:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 6836:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
 6837:     }
 6838:     $r->print($result);
 6839:     
 6840:     my @validate_phases=( 'sequence',
 6841: 			  'ID',
 6842: 			  'CODE',
 6843: 			  'doublebubble',
 6844: 			  'missingbubbles');
 6845:     if (!$env{'form.validatepass'}) {
 6846: 	$env{'form.validatepass'} = 0;
 6847:     }
 6848:     my $currentphase=$env{'form.validatepass'};
 6849: 
 6850: 
 6851:     my $stop=0;
 6852:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 6853: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 6854: 	$r->rflush();
 6855:      
 6856: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 6857: 	{
 6858: 	    no strict 'refs';
 6859: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 6860: 	}
 6861:     }
 6862:     if (!$stop) {
 6863: 	my $warning=&scantron_warning_screen('Start Grading',$symb);
 6864: 	$r->print(&mt('Validation process complete.').'<br />'.
 6865:                   $warning.
 6866:                   &mt('Perform verification for each student after storage of submissions?').
 6867:                   '&nbsp;<span class="LC_nobreak"><label>'.
 6868:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 6869:                   ('&nbsp;'x3).'<label>'.
 6870:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 6871:                   '</label></span><br />'.
 6872:                   &mt('Grading will take longer if you use verification.').'<br />'.
 6873:                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
 6874:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 6875:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 6876:     } else {
 6877: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 6878: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 6879:     }
 6880:     if ($stop) {
 6881: 	if ($validate_phases[$currentphase] eq 'sequence') {
 6882: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 6883: 	    $r->print(' '.&mt('this error').' <br />');
 6884: 
 6885: 	    $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>');
 6886: 	} else {
 6887:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 6888: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 6889:             } else {
 6890:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 6891:             }
 6892: 	    $r->print(' '.&mt('using corrected info').' <br />');
 6893: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 6894: 	    $r->print(" ".&mt("this scanline saving it for later."));
 6895: 	}
 6896:     }
 6897:     $r->print(" </form><br />");
 6898:     return '';
 6899: }
 6900: 
 6901: 
 6902: =pod
 6903: 
 6904: =item scantron_remove_file
 6905: 
 6906:    Removes the requested bubblesheet data file, makes sure that
 6907:    scantron_original_<filename> is never removed
 6908: 
 6909: 
 6910: =cut
 6911: 
 6912: sub scantron_remove_file {
 6913:     my ($which)=@_;
 6914:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6915:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6916:     my $file='scantron_';
 6917:     if ($which eq 'corrected' || $which eq 'skipped') {
 6918: 	$file.=$which.'_';
 6919:     } else {
 6920: 	return 'refused';
 6921:     }
 6922:     $file.=$env{'form.scantron_selectfile'};
 6923:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 6924: }
 6925: 
 6926: 
 6927: =pod
 6928: 
 6929: =item scantron_remove_scan_data
 6930: 
 6931:    Removes all scan_data correction for the requested bubblesheet
 6932:    data file.  (In the case that both the are doing skipped records we need
 6933:    to remember the old skipped lines for the time being so that element
 6934:    persists for a while.)
 6935: 
 6936: =cut
 6937: 
 6938: sub scantron_remove_scan_data {
 6939:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6940:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6941:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 6942:     my @todelete;
 6943:     my $filename=$env{'form.scantron_selectfile'};
 6944:     foreach my $key (@keys) {
 6945: 	if ($key=~/^\Q$filename\E_/) {
 6946: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 6947: 		$key=~/remember_skipping/) {
 6948: 		next;
 6949: 	    }
 6950: 	    push(@todelete,$key);
 6951: 	}
 6952:     }
 6953:     my $result;
 6954:     if (@todelete) {
 6955: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 6956: 				       \@todelete,$cdom,$cname);
 6957:     } else {
 6958: 	$result = 'ok';
 6959:     }
 6960:     return $result;
 6961: }
 6962: 
 6963: 
 6964: =pod
 6965: 
 6966: =item scantron_getfile
 6967: 
 6968:     Fetches the requested bubblesheet data file (all 3 versions), and
 6969:     the scan_data hash
 6970:   
 6971:   Arguments:
 6972:     None
 6973: 
 6974:   Returns:
 6975:     2 hash references
 6976: 
 6977:      - first one has 
 6978:          orig      -
 6979:          corrected -
 6980:          skipped   -  each of which points to an array ref of the specified
 6981:                       file broken up into individual lines
 6982:          count     - number of scanlines
 6983:  
 6984:      - second is the scan_data hash possible keys are
 6985:        ($number refers to scanline numbered $number and thus the key affects
 6986:         only that scanline
 6987:         $bubline refers to the specific bubble line element and the aspects
 6988:         refers to that specific bubble line element)
 6989: 
 6990:        $number.user - username:domain to use
 6991:        $number.CODE_ignore_dup 
 6992:                     - ignore the duplicate CODE error 
 6993:        $number.useCODE
 6994:                     - use the CODE in the scanline as is
 6995:        $number.no_bubble.$bubline
 6996:                     - it is valid that there is no bubbled in bubble
 6997:                       at $number $bubline
 6998:        remember_skipping
 6999:                     - a frozen hash containing keys of $number and values
 7000:                       of either 
 7001:                         1 - we are on a 'do skipped records pass' and plan
 7002:                             on processing this line
 7003:                         2 - we are on a 'do skipped records pass' and this
 7004:                             scanline has been marked to skip yet again
 7005: 
 7006: =cut
 7007: 
 7008: sub scantron_getfile {
 7009:     #FIXME really would prefer a scantron directory
 7010:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7011:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7012:     my $lines;
 7013:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7014: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 7015:     my %scanlines;
 7016:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 7017:     my $temp=$scanlines{'orig'};
 7018:     $scanlines{'count'}=$#$temp;
 7019: 
 7020:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7021: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 7022:     if ($lines eq '-1') {
 7023: 	$scanlines{'corrected'}=[];
 7024:     } else {
 7025: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 7026:     }
 7027:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7028: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 7029:     if ($lines eq '-1') {
 7030: 	$scanlines{'skipped'}=[];
 7031:     } else {
 7032: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 7033:     }
 7034:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 7035:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 7036:     my %scan_data = @tmp;
 7037:     return (\%scanlines,\%scan_data);
 7038: }
 7039: 
 7040: =pod
 7041: 
 7042: =item lonnet_putfile
 7043: 
 7044:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 7045: 
 7046:  Arguments:
 7047:    $contents - data to store
 7048:    $filename - filename to store $contents into
 7049: 
 7050:  Returns:
 7051:    result value from &Apache::lonnet::finishuserfileupload
 7052: 
 7053: =cut
 7054: 
 7055: sub lonnet_putfile {
 7056:     my ($contents,$filename)=@_;
 7057:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7058:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7059:     $env{'form.sillywaytopassafilearound'}=$contents;
 7060:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 7061: 
 7062: }
 7063: 
 7064: =pod
 7065: 
 7066: =item scantron_putfile
 7067: 
 7068:     Stores the current version of the bubblesheet data files, and the
 7069:     scan_data hash. (Does not modify the original version only the
 7070:     corrected and skipped versions.
 7071: 
 7072:  Arguments:
 7073:     $scanlines - hash ref that looks like the first return value from
 7074:                  &scantron_getfile()
 7075:     $scan_data - hash ref that looks like the second return value from
 7076:                  &scantron_getfile()
 7077: 
 7078: =cut
 7079: 
 7080: sub scantron_putfile {
 7081:     my ($scanlines,$scan_data) = @_;
 7082:     #FIXME really would prefer a scantron directory
 7083:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7084:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7085:     if ($scanlines) {
 7086: 	my $prefix='scantron_';
 7087: # no need to update orig, shouldn't change
 7088: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 7089: #		    $env{'form.scantron_selectfile'});
 7090: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 7091: 			$prefix.'corrected_'.
 7092: 			$env{'form.scantron_selectfile'});
 7093: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 7094: 			$prefix.'skipped_'.
 7095: 			$env{'form.scantron_selectfile'});
 7096:     }
 7097:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 7098: }
 7099: 
 7100: =pod
 7101: 
 7102: =item scantron_get_line
 7103: 
 7104:    Returns the correct version of the scanline
 7105: 
 7106:  Arguments:
 7107:     $scanlines - hash ref that looks like the first return value from
 7108:                  &scantron_getfile()
 7109:     $scan_data - hash ref that looks like the second return value from
 7110:                  &scantron_getfile()
 7111:     $i         - number of the requested line (starts at 0)
 7112: 
 7113:  Returns:
 7114:    A scanline, (either the original or the corrected one if it
 7115:    exists), or undef if the requested scanline should be
 7116:    skipped. (Either because it's an skipped scanline, or it's an
 7117:    unskipped scanline and we are not doing a 'do skipped scanlines'
 7118:    pass.
 7119: 
 7120: =cut
 7121: 
 7122: sub scantron_get_line {
 7123:     my ($scanlines,$scan_data,$i)=@_;
 7124:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 7125:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 7126:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 7127:     return $scanlines->{'orig'}[$i]; 
 7128: }
 7129: 
 7130: =pod
 7131: 
 7132: =item scantron_todo_count
 7133: 
 7134:     Counts the number of scanlines that need processing.
 7135: 
 7136:  Arguments:
 7137:     $scanlines - hash ref that looks like the first return value from
 7138:                  &scantron_getfile()
 7139:     $scan_data - hash ref that looks like the second return value from
 7140:                  &scantron_getfile()
 7141: 
 7142:  Returns:
 7143:     $count - number of scanlines to process
 7144: 
 7145: =cut
 7146: 
 7147: sub get_todo_count {
 7148:     my ($scanlines,$scan_data)=@_;
 7149:     my $count=0;
 7150:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7151: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7152: 	if ($line=~/^[\s\cz]*$/) { next; }
 7153: 	$count++;
 7154:     }
 7155:     return $count;
 7156: }
 7157: 
 7158: =pod
 7159: 
 7160: =item scantron_put_line
 7161: 
 7162:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
 7163:     data file.
 7164: 
 7165:  Arguments:
 7166:     $scanlines - hash ref that looks like the first return value from
 7167:                  &scantron_getfile()
 7168:     $scan_data - hash ref that looks like the second return value from
 7169:                  &scantron_getfile()
 7170:     $i         - line number to update
 7171:     $newline   - contents of the updated scanline
 7172:     $skip      - if true make the line for skipping and update the
 7173:                  'skipped' file
 7174: 
 7175: =cut
 7176: 
 7177: sub scantron_put_line {
 7178:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 7179:     if ($skip) {
 7180: 	$scanlines->{'skipped'}[$i]=$newline;
 7181: 	&start_skipping($scan_data,$i);
 7182: 	return;
 7183:     }
 7184:     $scanlines->{'corrected'}[$i]=$newline;
 7185: }
 7186: 
 7187: =pod
 7188: 
 7189: =item scantron_clear_skip
 7190: 
 7191:    Remove a line from the 'skipped' file
 7192: 
 7193:  Arguments:
 7194:     $scanlines - hash ref that looks like the first return value from
 7195:                  &scantron_getfile()
 7196:     $scan_data - hash ref that looks like the second return value from
 7197:                  &scantron_getfile()
 7198:     $i         - line number to update
 7199: 
 7200: =cut
 7201: 
 7202: sub scantron_clear_skip {
 7203:     my ($scanlines,$scan_data,$i)=@_;
 7204:     if (exists($scanlines->{'skipped'}[$i])) {
 7205: 	undef($scanlines->{'skipped'}[$i]);
 7206: 	return 1;
 7207:     }
 7208:     return 0;
 7209: }
 7210: 
 7211: =pod
 7212: 
 7213: =item scantron_filter_not_exam
 7214: 
 7215:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 7216:    filter out resources that are not marked as 'exam' mode
 7217: 
 7218: =cut
 7219: 
 7220: sub scantron_filter_not_exam {
 7221:     my ($curres)=@_;
 7222:     
 7223:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 7224: 	# if the user has asked to not have either hidden
 7225: 	# or 'randomout' controlled resources to be graded
 7226: 	# don't include them
 7227: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 7228: 	    && $curres->randomout) {
 7229: 	    return 0;
 7230: 	}
 7231: 	return 1;
 7232:     }
 7233:     return 0;
 7234: }
 7235: 
 7236: =pod
 7237: 
 7238: =item scantron_validate_sequence
 7239: 
 7240:     Validates the selected sequence, checking for resource that are
 7241:     not set to exam mode.
 7242: 
 7243: =cut
 7244: 
 7245: sub scantron_validate_sequence {
 7246:     my ($r,$currentphase) = @_;
 7247: 
 7248:     my $navmap=Apache::lonnavmaps::navmap->new();
 7249:     unless (ref($navmap)) {
 7250:         $r->print(&navmap_errormsg());
 7251:         return (1,$currentphase);
 7252:     }
 7253:     my (undef,undef,$sequence)=
 7254: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7255: 
 7256:     my $map=$navmap->getResourceByUrl($sequence);
 7257: 
 7258:     $r->print('<input type="hidden" name="validate_sequence_exam"
 7259:                                     value="ignore" />');
 7260:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 7261: 	my @resources=
 7262: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 7263: 	if (@resources) {
 7264: 	    $r->print(
 7265:                 '<p class="LC_warning">'
 7266:                .&mt('Some resources in the sequence currently are not set to'
 7267:                    .' bubblesheet exam mode. Grading these resources currently may not'
 7268:                    .' work correctly.')
 7269:                .'</p>'
 7270:             );
 7271: 	    return (1,$currentphase);
 7272: 	}
 7273:     }
 7274: 
 7275:     return (0,$currentphase+1);
 7276: }
 7277: 
 7278: 
 7279: 
 7280: sub scantron_validate_ID {
 7281:     my ($r,$currentphase) = @_;
 7282:     
 7283:     #get student info
 7284:     my $classlist=&Apache::loncoursedata::get_classlist();
 7285:     my %idmap=&username_to_idmap($classlist);
 7286: 
 7287:     #get scantron line setup
 7288:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7289:     my ($scanlines,$scan_data)=&scantron_getfile();
 7290: 
 7291:     my $nav_error;
 7292:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
 7293:     if ($nav_error) {
 7294:         $r->print(&navmap_errormsg());
 7295:         return(1,$currentphase);
 7296:     }
 7297: 
 7298:     my %found=('ids'=>{},'usernames'=>{});
 7299:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7300: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7301: 	if ($line=~/^[\s\cz]*$/) { next; }
 7302: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7303: 						 $scan_data);
 7304: 	my $id=$$scan_record{'scantron.ID'};
 7305: 	my $found;
 7306: 	foreach my $checkid (keys(%idmap)) {
 7307: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 7308: 	}
 7309: 	if ($found) {
 7310: 	    my $username=$idmap{$found};
 7311: 	    if ($found{'ids'}{$found}) {
 7312: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7313: 					 $line,'duplicateID',$found);
 7314: 		return(1,$currentphase);
 7315: 	    } elsif ($found{'usernames'}{$username}) {
 7316: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7317: 					 $line,'duplicateID',$username);
 7318: 		return(1,$currentphase);
 7319: 	    }
 7320: 	    #FIXME store away line we previously saw the ID on to use above
 7321: 	    $found{'ids'}{$found}++;
 7322: 	    $found{'usernames'}{$username}++;
 7323: 	} else {
 7324: 	    if ($id =~ /^\s*$/) {
 7325: 		my $username=&scan_data($scan_data,"$i.user");
 7326: 		if (defined($username) && $found{'usernames'}{$username}) {
 7327: 		    &scantron_get_correction($r,$i,$scan_record,
 7328: 					     \%scantron_config,
 7329: 					     $line,'duplicateID',$username);
 7330: 		    return(1,$currentphase);
 7331: 		} elsif (!defined($username)) {
 7332: 		    &scantron_get_correction($r,$i,$scan_record,
 7333: 					     \%scantron_config,
 7334: 					     $line,'incorrectID');
 7335: 		    return(1,$currentphase);
 7336: 		}
 7337: 		$found{'usernames'}{$username}++;
 7338: 	    } else {
 7339: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7340: 					 $line,'incorrectID');
 7341: 		return(1,$currentphase);
 7342: 	    }
 7343: 	}
 7344:     }
 7345: 
 7346:     return (0,$currentphase+1);
 7347: }
 7348: 
 7349: 
 7350: sub scantron_get_correction {
 7351:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
 7352:         $randomorder,$randompick,$respnumlookup,$startline)=@_;
 7353: #FIXME in the case of a duplicated ID the previous line, probably need
 7354: #to show both the current line and the previous one and allow skipping
 7355: #the previous one or the current one
 7356: 
 7357:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 7358:         $r->print(
 7359:             '<p class="LC_warning">'
 7360:            .&mt('An error was detected ([_1]) for PaperID [_2]',
 7361:                 "<b>$error</b>",
 7362:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
 7363:            ."</p> \n");
 7364:     } else {
 7365:         $r->print(
 7366:             '<p class="LC_warning">'
 7367:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
 7368:                 "<b>$error</b>", $i, "<pre>$line</pre>")
 7369:            ."</p> \n");
 7370:     }
 7371:     my $message =
 7372:         '<p>'
 7373:        .&mt('The ID on the form is [_1]',
 7374:             "<tt>$$scan_record{'scantron.ID'}</tt>")
 7375:        .'<br />'
 7376:        .&mt('The name on the paper is [_1], [_2]',
 7377:             $$scan_record{'scantron.LastName'},
 7378:             $$scan_record{'scantron.FirstName'})
 7379:        .'</p>';
 7380: 
 7381:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 7382:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 7383:                            # Array populated for doublebubble or
 7384:     my @lines_to_correct;  # missingbubble errors to build javascript
 7385:                            # to validate radio button checking   
 7386: 
 7387:     if ($error =~ /ID$/) {
 7388: 	if ($error eq 'incorrectID') {
 7389:             $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
 7390: 		      "</p>\n");
 7391: 	} elsif ($error eq 'duplicateID') {
 7392:             $r->print('<p class="LC_warning">'.&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 7393: 	}
 7394: 	$r->print($message);
 7395: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 7396: 	$r->print("\n<ul><li> ");
 7397: 	#FIXME it would be nice if this sent back the user ID and
 7398: 	#could do partial userID matches
 7399: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 7400: 				       'scantron_username','scantron_domain'));
 7401: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 7402: 	$r->print("\n:\n".
 7403: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 7404: 
 7405: 	$r->print('</li>');
 7406:     } elsif ($error =~ /CODE$/) {
 7407: 	if ($error eq 'incorrectCODE') {
 7408: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 7409: 	} elsif ($error eq 'duplicateCODE') {
 7410: 	    $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");
 7411: 	}
 7412: 	$r->print("<p>".&mt('The CODE on the form is [_1]',
 7413: 			    "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
 7414:                  ."</p>\n");
 7415: 	$r->print($message);
 7416: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
 7417: 	$r->print("\n<br /> ");
 7418: 	my $i=0;
 7419: 	if ($error eq 'incorrectCODE' 
 7420: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 7421: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 7422: 	    if ($closest > 0) {
 7423: 		foreach my $testcode (@{$closest}) {
 7424: 		    my $checked='';
 7425: 		    if (!$i) { $checked=' checked="checked"'; }
 7426: 		    $r->print("
 7427:    <label>
 7428:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
 7429:        ".&mt("Use the similar CODE [_1] instead.",
 7430: 	    "<b><tt>".$testcode."</tt></b>")."
 7431:     </label>
 7432:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 7433: 		    $r->print("\n<br />");
 7434: 		    $i++;
 7435: 		}
 7436: 	    }
 7437: 	}
 7438: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 7439: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
 7440: 	    $r->print("
 7441:     <label>
 7442:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
 7443:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
 7444: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 7445:     </label>");
 7446: 	    $r->print("\n<br />");
 7447: 	}
 7448: 
 7449: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
 7450: function change_radio(field) {
 7451:     var slct=document.scantronupload.scantron_CODE_resolution;
 7452:     var i;
 7453:     for (i=0;i<slct.length;i++) {
 7454:         if (slct[i].value==field) { slct[i].checked=true; }
 7455:     }
 7456: }
 7457: ENDSCRIPT
 7458: 	my $href="/adm/pickcode?".
 7459: 	   "form=".&escape("scantronupload").
 7460: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 7461: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 7462: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 7463: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 7464: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 7465: 	    $r->print("
 7466:     <label>
 7467:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 7468:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 7469: 	     "<a target='_blank' href='$href'>","</a>")."
 7470:     </label> 
 7471:     ".&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\')" />'));
 7472: 	    $r->print("\n<br />");
 7473: 	}
 7474: 	$r->print("
 7475:     <label>
 7476:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 7477:        ".&mt("Use [_1] as the CODE.",
 7478: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 7479: 	$r->print("\n<br /><br />");
 7480:     } elsif ($error eq 'doublebubble') {
 7481: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 7482: 
 7483: 	# The form field scantron_questions is acutally a list of line numbers.
 7484: 	# represented by this form so:
 7485: 
 7486: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 7487:                                                 $respnumlookup,$startline);
 7488: 
 7489: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7490: 		  $line_list.'" />');
 7491: 	$r->print($message);
 7492: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 7493: 	foreach my $question (@{$arg}) {
 7494: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7495:                                                    $scan_record, $error,
 7496:                                                    $randomorder,$randompick,
 7497:                                                    $respnumlookup,$startline);
 7498:             push(@lines_to_correct,@linenums);
 7499: 	}
 7500:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7501:     } elsif ($error eq 'missingbubble') {
 7502: 	$r->print('<p class="LC_warning">'.&mt("There have been [_1]no[_2] bubbles scanned for some question(s)",'<b>','</b>')."</p>\n");
 7503: 	$r->print($message);
 7504: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 7505: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 7506: 
 7507: 	# The form field scantron_questions is actually a list of line numbers not
 7508: 	# a list of question numbers. Therefore:
 7509: 	#
 7510: 
 7511: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 7512:                                                 $respnumlookup,$startline);
 7513: 
 7514: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7515: 		  $line_list.'" />');
 7516: 	foreach my $question (@{$arg}) {
 7517: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7518:                                                    $scan_record, $error,
 7519:                                                    $randomorder,$randompick,
 7520:                                                    $respnumlookup,$startline);
 7521:             push(@lines_to_correct,@linenums);
 7522: 	}
 7523:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7524:     } else {
 7525: 	$r->print("\n<ul>");
 7526:     }
 7527:     $r->print("\n</li></ul>");
 7528: }
 7529: 
 7530: sub verify_bubbles_checked {
 7531:     my (@ansnums) = @_;
 7532:     my $ansnumstr = join('","',@ansnums);
 7533:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 7534:     my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
 7535: function verify_bubble_radio(form) {
 7536:     var ansnumArray = new Array ("$ansnumstr");
 7537:     var need_bubble_count = 0;
 7538:     for (var i=0; i<ansnumArray.length; i++) {
 7539:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 7540:             var bubble_picked = 0; 
 7541:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 7542:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 7543:                     bubble_picked = 1;
 7544:                 }
 7545:             }
 7546:             if (bubble_picked == 0) {
 7547:                 need_bubble_count ++;
 7548:             }
 7549:         }
 7550:     }
 7551:     if (need_bubble_count) {
 7552:         alert("$warning");
 7553:         return;
 7554:     }
 7555:     form.submit(); 
 7556: }
 7557: ENDSCRIPT
 7558:     return $output;
 7559: }
 7560: 
 7561: =pod
 7562: 
 7563: =item  questions_to_line_list
 7564: 
 7565: Converts a list of questions into a string of comma separated
 7566: line numbers in the answer sheet used by the questions.  This is
 7567: used to fill in the scantron_questions form field.
 7568: 
 7569:   Arguments:
 7570:      questions    - Reference to an array of questions.
 7571:      randomorder  - True if randomorder in use.
 7572:      randompick   - True if randompick in use.
 7573:      respnumlookup - Reference to HASH mapping question numbers in bubble lines
 7574:                      for current line to question number used for same question
 7575:                      in "Master Seqence" (as seen by Course Coordinator).
 7576:      startline    - Reference to hash where key is question number (0 is first)
 7577:                     and key is number of first bubble line for current student
 7578:                     or code-based randompick and/or randomorder.
 7579: 
 7580: =cut
 7581: 
 7582: 
 7583: sub questions_to_line_list {
 7584:     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
 7585:     my @lines;
 7586: 
 7587:     foreach my $item (@{$questions}) {
 7588:         my $question = $item;
 7589:         my ($first,$count,$last);
 7590:         if ($item =~ /^(\d+)\.(\d+)$/) {
 7591:             $question = $1;
 7592:             my $subquestion = $2;
 7593:             my $responsenum = $question-1;
 7594:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7595:                 $responsenum = $respnumlookup->{$question-1};
 7596:                 if (ref($startline) eq 'HASH') {
 7597:                     $first = $startline->{$question-1} + 1;
 7598:                 }
 7599:             } else {
 7600:                 $first = $first_bubble_line{$responsenum} + 1;
 7601:             }
 7602:             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 7603:             my $subcount = 1;
 7604:             while ($subcount<$subquestion) {
 7605:                 $first += $subans[$subcount-1];
 7606:                 $subcount ++;
 7607:             }
 7608:             $count = $subans[$subquestion-1];
 7609:         } else {
 7610:             my $responsenum = $question-1;
 7611:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7612:                 $responsenum = $respnumlookup->{$question-1};
 7613:                 if (ref($startline) eq 'HASH') {
 7614:                     $first = $startline->{$question-1} + 1;
 7615:                 }
 7616:             } else {
 7617:                 $first = $first_bubble_line{$responsenum} + 1;
 7618:             }
 7619: 	    $count   = $bubble_lines_per_response{$responsenum};
 7620:         }
 7621:         $last = $first+$count-1;
 7622:         push(@lines, ($first..$last));
 7623:     }
 7624:     return join(',', @lines);
 7625: }
 7626: 
 7627: =pod 
 7628: 
 7629: =item prompt_for_corrections
 7630: 
 7631: Prompts for a potentially multiline correction to the
 7632: user's bubbling (factors out common code from scantron_get_correction
 7633: for multi and missing bubble cases).
 7634: 
 7635:  Arguments:
 7636:    $r           - Apache request object.
 7637:    $question    - The question number to prompt for.
 7638:    $scan_config - The scantron file configuration hash.
 7639:    $scan_record - Reference to the hash that has the the parsed scanlines.
 7640:    $error       - Type of error
 7641:    $randomorder - True if randomorder in use.
 7642:    $randompick  - True if randompick in use.
 7643:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
 7644:                     for current line to question number used for same question
 7645:                     in "Master Seqence" (as seen by Course Coordinator).
 7646:    $startline   - Reference to hash where key is question number (0 is first)
 7647:                   and value is number of first bubble line for current student
 7648:                   or code-based randompick and/or randomorder.
 7649: 
 7650: 
 7651:  Implicit inputs:
 7652:    %bubble_lines_per_response   - Starting line numbers for each question.
 7653:                                   Numbered from 0 (but question numbers are from
 7654:                                   1.
 7655:    %first_bubble_line           - Starting bubble line for each question.
 7656:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 7657:                                   type problems render as separate sub-questions, 
 7658:                                   in exam mode. This hash contains a 
 7659:                                   comma-separated list of the lines per 
 7660:                                   sub-question.
 7661:    %responsetype_per_response   - essayresponse, formularesponse,
 7662:                                   stringresponse, imageresponse, reactionresponse,
 7663:                                   and organicresponse type problem parts can have
 7664:                                   multiple lines per response if the weight
 7665:                                   assigned exceeds 10.  In this case, only
 7666:                                   one bubble per line is permitted, but more 
 7667:                                   than one line might contain bubbles, e.g.
 7668:                                   bubbling of: line 1 - J, line 2 - J, 
 7669:                                   line 3 - B would assign 22 points.  
 7670: 
 7671: =cut
 7672: 
 7673: sub prompt_for_corrections {
 7674:     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
 7675:         $randompick, $respnumlookup, $startline) = @_;
 7676:     my ($current_line,$lines);
 7677:     my @linenums;
 7678:     my $questionnum = $question;
 7679:     my ($first,$responsenum);
 7680:     if ($question =~ /^(\d+)\.(\d+)$/) {
 7681:         $question = $1;
 7682:         my $subquestion = $2;
 7683:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7684:             $responsenum = $respnumlookup->{$question-1};
 7685:             if (ref($startline) eq 'HASH') {
 7686:                 $first = $startline->{$question-1};
 7687:             }
 7688:         } else {
 7689:             $responsenum = $question-1;
 7690:             $first = $first_bubble_line{$responsenum};
 7691:         }
 7692:         $current_line = $first + 1 ;
 7693:         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 7694:         my $subcount = 1;
 7695:         while ($subcount<$subquestion) {
 7696:             $current_line += $subans[$subcount-1];
 7697:             $subcount ++;
 7698:         }
 7699:         $lines = $subans[$subquestion-1];
 7700:     } else {
 7701:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7702:             $responsenum = $respnumlookup->{$question-1};
 7703:             if (ref($startline) eq 'HASH') { 
 7704:                 $first = $startline->{$question-1};
 7705:             }
 7706:         } else {
 7707:             $responsenum = $question-1;
 7708:             $first = $first_bubble_line{$responsenum};
 7709:         }
 7710:         $current_line = $first + 1;
 7711:         $lines        = $bubble_lines_per_response{$responsenum};
 7712:     }
 7713:     if ($lines > 1) {
 7714:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 7715:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 7716:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 7717:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 7718:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 7719:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 7720:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 7721:             $r->print(
 7722:                 &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)
 7723:                .'<br /><br />'
 7724:                .&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.')
 7725:                .'<br />'
 7726:                .&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.')
 7727:                .'<br />'
 7728:                .&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.")
 7729:                .'<br /><br />'
 7730:             );
 7731:         } else {
 7732:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 7733:         }
 7734:     }
 7735:     for (my $i =0; $i < $lines; $i++) {
 7736:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 7737: 	&scantron_bubble_selector($r,$scan_config,$current_line,
 7738: 	        		  $questionnum,$error,split('', $selected));
 7739:         push(@linenums,$current_line);
 7740: 	$current_line++;
 7741:     }
 7742:     if ($lines > 1) {
 7743: 	$r->print("<hr /><br />");
 7744:     }
 7745:     return @linenums;
 7746: }
 7747: 
 7748: =pod
 7749: 
 7750: =item scantron_bubble_selector
 7751:   
 7752:    Generates the html radiobuttons to correct a single bubble line
 7753:    possibly showing the existing the selected bubbles if known
 7754: 
 7755:  Arguments:
 7756:     $r           - Apache request object
 7757:     $scan_config - hash from &get_scantron_config()
 7758:     $line        - Number of the line being displayed.
 7759:     $questionnum - Question number (may include subquestion)
 7760:     $error       - Type of error.
 7761:     @selected    - Array of bubbles picked on this line.
 7762: 
 7763: =cut
 7764: 
 7765: sub scantron_bubble_selector {
 7766:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 7767:     my $max=$$scan_config{'Qlength'};
 7768: 
 7769:     my $scmode=$$scan_config{'Qon'};
 7770:     if ($scmode eq 'number' || $scmode eq 'letter') { 
 7771:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
 7772:             ($$scan_config{'BubblesPerRow'} > 0)) {
 7773:             $max=$$scan_config{'BubblesPerRow'};
 7774:             if (($scmode eq 'number') && ($max > 10)) {
 7775:                 $max = 10;
 7776:             } elsif (($scmode eq 'letter') && $max > 26) {
 7777:                 $max = 26;
 7778:             }
 7779:         } else {
 7780:             $max = 10;
 7781:         }
 7782:     }
 7783: 
 7784:     my @alphabet=('A'..'Z');
 7785:     $r->print(&Apache::loncommon::start_data_table().
 7786:               &Apache::loncommon::start_data_table_row());
 7787:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 7788:     for (my $i=0;$i<$max+1;$i++) {
 7789: 	$r->print("\n".'<td align="center">');
 7790: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 7791: 	else { $r->print('&nbsp;'); }
 7792: 	$r->print('</td>');
 7793:     }
 7794:     $r->print(&Apache::loncommon::end_data_table_row().
 7795:               &Apache::loncommon::start_data_table_row());
 7796:     for (my $i=0;$i<$max;$i++) {
 7797: 	$r->print("\n".
 7798: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 7799: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 7800:     }
 7801:     my $nobub_checked = ' ';
 7802:     if ($error eq 'missingbubble') {
 7803:         $nobub_checked = ' checked = "checked" ';
 7804:     }
 7805:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 7806: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 7807:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 7808:               $line.'" value="'.$questionnum.'" /></td>');
 7809:     $r->print(&Apache::loncommon::end_data_table_row().
 7810:               &Apache::loncommon::end_data_table());
 7811: }
 7812: 
 7813: =pod
 7814: 
 7815: =item num_matches
 7816: 
 7817:    Counts the number of characters that are the same between the two arguments.
 7818: 
 7819:  Arguments:
 7820:    $orig - CODE from the scanline
 7821:    $code - CODE to match against
 7822: 
 7823:  Returns:
 7824:    $count - integer count of the number of same characters between the
 7825:             two arguments
 7826: 
 7827: =cut
 7828: 
 7829: sub num_matches {
 7830:     my ($orig,$code) = @_;
 7831:     my @code=split(//,$code);
 7832:     my @orig=split(//,$orig);
 7833:     my $same=0;
 7834:     for (my $i=0;$i<scalar(@code);$i++) {
 7835: 	if ($code[$i] eq $orig[$i]) { $same++; }
 7836:     }
 7837:     return $same;
 7838: }
 7839: 
 7840: =pod
 7841: 
 7842: =item scantron_get_closely_matching_CODEs
 7843: 
 7844:    Cycles through all CODEs and finds the set that has the greatest
 7845:    number of same characters as the provided CODE
 7846: 
 7847:  Arguments:
 7848:    $allcodes - hash ref returned by &get_codes()
 7849:    $CODE     - CODE from the current scanline
 7850: 
 7851:  Returns:
 7852:    2 element list
 7853:     - first elements is number of how closely matching the best fit is 
 7854:       (5 means best set has 5 matching characters)
 7855:     - second element is an arrary ref containing the set of valid CODEs
 7856:       that best fit the passed in CODE
 7857: 
 7858: =cut
 7859: 
 7860: sub scantron_get_closely_matching_CODEs {
 7861:     my ($allcodes,$CODE)=@_;
 7862:     my @CODEs;
 7863:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 7864: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 7865:     }
 7866: 
 7867:     return ($#CODEs,$CODEs[-1]);
 7868: }
 7869: 
 7870: =pod
 7871: 
 7872: =item get_codes
 7873: 
 7874:    Builds a hash which has keys of all of the valid CODEs from the selected
 7875:    set of remembered CODEs.
 7876: 
 7877:  Arguments:
 7878:   $old_name - name of the set of remembered CODEs
 7879:   $cdom     - domain of the course
 7880:   $cnum     - internal course name
 7881: 
 7882:  Returns:
 7883:   %allcodes - keys are the valid CODEs, values are all 1
 7884: 
 7885: =cut
 7886: 
 7887: sub get_codes {
 7888:     my ($old_name, $cdom, $cnum) = @_;
 7889:     if (!$old_name) {
 7890: 	$old_name=$env{'form.scantron_CODElist'};
 7891:     }
 7892:     if (!$cdom) {
 7893: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 7894:     }
 7895:     if (!$cnum) {
 7896: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 7897:     }
 7898:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 7899: 				    $cdom,$cnum);
 7900:     my %allcodes;
 7901:     if ($result{"type\0$old_name"} eq 'number') {
 7902: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 7903:     } else {
 7904: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 7905:     }
 7906:     return %allcodes;
 7907: }
 7908: 
 7909: =pod
 7910: 
 7911: =item scantron_validate_CODE
 7912: 
 7913:    Validates all scanlines in the selected file to not have any
 7914:    invalid or underspecified CODEs and that none of the codes are
 7915:    duplicated if this was requested.
 7916: 
 7917: =cut
 7918: 
 7919: sub scantron_validate_CODE {
 7920:     my ($r,$currentphase) = @_;
 7921:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7922:     if ($scantron_config{'CODElocation'} &&
 7923: 	$scantron_config{'CODEstart'} &&
 7924: 	$scantron_config{'CODElength'}) {
 7925: 	if (!defined($env{'form.scantron_CODElist'})) {
 7926: 	    &FIXME_blow_up()
 7927: 	}
 7928:     } else {
 7929: 	return (0,$currentphase+1);
 7930:     }
 7931:     
 7932:     my %usedCODEs;
 7933: 
 7934:     my %allcodes=&get_codes();
 7935: 
 7936:     my $nav_error;
 7937:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
 7938:     if ($nav_error) {
 7939:         $r->print(&navmap_errormsg());
 7940:         return(1,$currentphase);
 7941:     }
 7942: 
 7943:     my ($scanlines,$scan_data)=&scantron_getfile();
 7944:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7945: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7946: 	if ($line=~/^[\s\cz]*$/) { next; }
 7947: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7948: 						 $scan_data);
 7949: 	my $CODE=$$scan_record{'scantron.CODE'};
 7950: 	my $error=0;
 7951: 	if (!&Apache::lonnet::validCODE($CODE)) {
 7952: 	    &scantron_get_correction($r,$i,$scan_record,
 7953: 				     \%scantron_config,
 7954: 				     $line,'incorrectCODE',\%allcodes);
 7955: 	    return(1,$currentphase);
 7956: 	}
 7957: 	if (%allcodes && !exists($allcodes{$CODE}) 
 7958: 	    && !$$scan_record{'scantron.useCODE'}) {
 7959: 	    &scantron_get_correction($r,$i,$scan_record,
 7960: 				     \%scantron_config,
 7961: 				     $line,'incorrectCODE',\%allcodes);
 7962: 	    return(1,$currentphase);
 7963: 	}
 7964: 	if (exists($usedCODEs{$CODE}) 
 7965: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 7966: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 7967: 	    &scantron_get_correction($r,$i,$scan_record,
 7968: 				     \%scantron_config,
 7969: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 7970: 	    return(1,$currentphase);
 7971: 	}
 7972: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 7973:     }
 7974:     return (0,$currentphase+1);
 7975: }
 7976: 
 7977: =pod
 7978: 
 7979: =item scantron_validate_doublebubble
 7980: 
 7981:    Validates all scanlines in the selected file to not have any
 7982:    bubble lines with multiple bubbles marked.
 7983: 
 7984: =cut
 7985: 
 7986: sub scantron_validate_doublebubble {
 7987:     my ($r,$currentphase) = @_;
 7988:     #get student info
 7989:     my $classlist=&Apache::loncoursedata::get_classlist();
 7990:     my %idmap=&username_to_idmap($classlist);
 7991:     my (undef,undef,$sequence)=
 7992:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 7993: 
 7994:     #get scantron line setup
 7995:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7996:     my ($scanlines,$scan_data)=&scantron_getfile();
 7997: 
 7998:     my $navmap = Apache::lonnavmaps::navmap->new();
 7999:     unless (ref($navmap)) {
 8000:         $r->print(&navmap_errormsg());
 8001:         return(1,$currentphase);
 8002:     }
 8003:     my $map=$navmap->getResourceByUrl($sequence);
 8004:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8005:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8006:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 8007:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8008: 
 8009:     my $nav_error;
 8010:     if (ref($map)) {
 8011:         $randomorder = $map->randomorder();
 8012:         $randompick = $map->randompick();
 8013:         if ($randomorder || $randompick) {
 8014:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8015:             if ($nav_error) {
 8016:                 $r->print(&navmap_errormsg());
 8017:                 return(1,$currentphase);
 8018:             }
 8019:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8020:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 8021:         }
 8022:     } else {
 8023:         $r->print(&navmap_errormsg());
 8024:         return(1,$currentphase);
 8025:     }
 8026: 
 8027:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
 8028:     if ($nav_error) {
 8029:         $r->print(&navmap_errormsg());
 8030:         return(1,$currentphase);
 8031:     }
 8032: 
 8033:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8034: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8035: 	if ($line=~/^[\s\cz]*$/) { next; }
 8036: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8037: 						 $scan_data,undef,\%idmap,$randomorder,
 8038:                                                  $randompick,$sequence,\@master_seq,
 8039:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 8040:                                                  \%orderedforcode,\%respnumlookup,\%startline);
 8041: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 8042: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 8043: 				 'doublebubble',
 8044: 				 $$scan_record{'scantron.doubleerror'},
 8045:                                  $randomorder,$randompick,\%respnumlookup,\%startline);
 8046:     	return (1,$currentphase);
 8047:     }
 8048:     return (0,$currentphase+1);
 8049: }
 8050: 
 8051: 
 8052: sub scantron_get_maxbubble {
 8053:     my ($nav_error,$scantron_config) = @_;
 8054:     if (defined($env{'form.scantron_maxbubble'}) &&
 8055: 	$env{'form.scantron_maxbubble'}) {
 8056: 	&restore_bubble_lines();
 8057: 	return $env{'form.scantron_maxbubble'};
 8058:     }
 8059: 
 8060:     my (undef, undef, $sequence) =
 8061: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8062: 
 8063:     my $navmap=Apache::lonnavmaps::navmap->new();
 8064:     unless (ref($navmap)) {
 8065:         if (ref($nav_error)) {
 8066:             $$nav_error = 1;
 8067:         }
 8068:         return;
 8069:     }
 8070:     my $map=$navmap->getResourceByUrl($sequence);
 8071:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8072:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
 8073: 
 8074:     &Apache::lonxml::clear_problem_counter();
 8075: 
 8076:     my $uname       = $env{'user.name'};
 8077:     my $udom        = $env{'user.domain'};
 8078:     my $cid         = $env{'request.course.id'};
 8079:     my $total_lines = 0;
 8080:     %bubble_lines_per_response = ();
 8081:     %first_bubble_line         = ();
 8082:     %subdivided_bubble_lines   = ();
 8083:     %responsetype_per_response = ();
 8084:     %masterseq_id_responsenum  = ();
 8085: 
 8086:     my $response_number = 0;
 8087:     my $bubble_line     = 0;
 8088:     foreach my $resource (@resources) {
 8089:         my $resid = $resource->id(); 
 8090:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
 8091:                                                           $udom,undef,$bubbles_per_row);
 8092:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 8093: 	    foreach my $part_id (@{$parts}) {
 8094:                 my $lines;
 8095: 
 8096: 	        # TODO - make this a persistent hash not an array.
 8097: 
 8098:                 # optionresponse, matchresponse and rankresponse type items 
 8099:                 # render as separate sub-questions in exam mode.
 8100:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 8101:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 8102:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 8103:                     my ($numbub,$numshown);
 8104:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 8105:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 8106:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 8107:                         }
 8108:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 8109:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 8110:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 8111:                         }
 8112:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 8113:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 8114:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 8115:                         }
 8116:                     }
 8117:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 8118:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 8119:                     }
 8120:                     my $bubbles_per_row =
 8121:                         &bubblesheet_bubbles_per_row($scantron_config);
 8122:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
 8123:                     if (($numbub % $bubbles_per_row) != 0) {
 8124:                         $inner_bubble_lines++;
 8125:                     }
 8126:                     for (my $i=0; $i<$numshown; $i++) {
 8127:                         $subdivided_bubble_lines{$response_number} .= 
 8128:                             $inner_bubble_lines.',';
 8129:                     }
 8130:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 8131:                     $lines = $numshown * $inner_bubble_lines;
 8132:                 } else {
 8133:                     $lines = $analysis->{"$part_id.bubble_lines"};
 8134:                 }
 8135: 
 8136:                 $first_bubble_line{$response_number} = $bubble_line;
 8137: 	        $bubble_lines_per_response{$response_number} = $lines;
 8138:                 $responsetype_per_response{$response_number} = 
 8139:                     $analysis->{$part_id.'.type'};
 8140:                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;  
 8141: 	        $response_number++;
 8142: 
 8143: 	        $bubble_line +=  $lines;
 8144: 	        $total_lines +=  $lines;
 8145: 	    }
 8146:         }
 8147:     }
 8148:     &Apache::lonnet::delenv('scantron.');
 8149: 
 8150:     &save_bubble_lines();
 8151:     $env{'form.scantron_maxbubble'} =
 8152: 	$total_lines;
 8153:     return $env{'form.scantron_maxbubble'};
 8154: }
 8155: 
 8156: sub bubblesheet_bubbles_per_row {
 8157:     my ($scantron_config) = @_;
 8158:     my $bubbles_per_row;
 8159:     if (ref($scantron_config) eq 'HASH') {
 8160:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
 8161:     }
 8162:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
 8163:         $bubbles_per_row = 10;
 8164:     }
 8165:     return $bubbles_per_row;
 8166: }
 8167: 
 8168: sub scantron_validate_missingbubbles {
 8169:     my ($r,$currentphase) = @_;
 8170:     #get student info
 8171:     my $classlist=&Apache::loncoursedata::get_classlist();
 8172:     my %idmap=&username_to_idmap($classlist);
 8173:     my (undef,undef,$sequence)=
 8174:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8175: 
 8176:     #get scantron line setup
 8177:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8178:     my ($scanlines,$scan_data)=&scantron_getfile();
 8179: 
 8180:     my $navmap = Apache::lonnavmaps::navmap->new();
 8181:     unless (ref($navmap)) {
 8182:         $r->print(&navmap_errormsg());
 8183:         return(1,$currentphase);
 8184:     }
 8185: 
 8186:     my $map=$navmap->getResourceByUrl($sequence);
 8187:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8188:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8189:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 8190:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8191: 
 8192:     my $nav_error;
 8193:     if (ref($map)) {
 8194:         $randomorder = $map->randomorder();
 8195:         $randompick = $map->randompick();
 8196:         if ($randomorder || $randompick) {
 8197:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8198:             if ($nav_error) {
 8199:                 $r->print(&navmap_errormsg());
 8200:                 return(1,$currentphase);
 8201:             }
 8202:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8203:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 8204:         }
 8205:     } else {
 8206:         $r->print(&navmap_errormsg());
 8207:         return(1,$currentphase);
 8208:     }
 8209: 
 8210: 
 8211:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 8212:     if ($nav_error) {
 8213:         $r->print(&navmap_errormsg());
 8214:         return(1,$currentphase);
 8215:     }
 8216: 
 8217:     if (!$max_bubble) { $max_bubble=2**31; }
 8218:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8219: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8220: 	if ($line=~/^[\s\cz]*$/) { next; }
 8221: 	my $scan_record =
 8222:             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
 8223: 				     $randomorder,$randompick,$sequence,\@master_seq,
 8224:                                      \%symb_to_resource,\%grader_partids_by_symb,
 8225:                                      \%orderedforcode,\%respnumlookup,\%startline);
 8226: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 8227: 	my @to_correct;
 8228: 	
 8229: 	# Probably here's where the error is...
 8230: 
 8231: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 8232:             my $lastbubble;
 8233:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 8234:                my $question = $1;
 8235:                my $subquestion = $2;
 8236:                my ($first,$responsenum);
 8237:                if ($randomorder || $randompick) {
 8238:                    $responsenum = $respnumlookup{$question-1};
 8239:                    $first = $startline{$question-1};
 8240:                } else {
 8241:                    $responsenum = $question-1; 
 8242:                    $first = $first_bubble_line{$responsenum};
 8243:                }
 8244:                if (!defined($first)) { next; }
 8245:                my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8246:                my $subcount = 1;
 8247:                while ($subcount<$subquestion) {
 8248:                    $first += $subans[$subcount-1];
 8249:                    $subcount ++;
 8250:                }
 8251:                my $count = $subans[$subquestion-1];
 8252:                $lastbubble = $first + $count;
 8253:             } else {
 8254:                my ($first,$responsenum);
 8255:                if ($randomorder || $randompick) {
 8256:                    $responsenum = $respnumlookup{$missing-1};
 8257:                    $first = $startline{$missing-1};
 8258:                } else {
 8259:                    $responsenum = $missing-1;
 8260:                    $first = $first_bubble_line{$responsenum};
 8261:                }
 8262:                if (!defined($first)) { next; }
 8263:                $lastbubble = $first + $bubble_lines_per_response{$responsenum};
 8264:             }
 8265:             if ($lastbubble > $max_bubble) { next; }
 8266: 	    push(@to_correct,$missing);
 8267: 	}
 8268: 	if (@to_correct) {
 8269: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 8270: 				     $line,'missingbubble',\@to_correct,
 8271:                                      $randomorder,$randompick,\%respnumlookup,
 8272:                                      \%startline);
 8273: 	    return (1,$currentphase);
 8274: 	}
 8275: 
 8276:     }
 8277:     return (0,$currentphase+1);
 8278: }
 8279: 
 8280: sub hand_bubble_option {
 8281:     my (undef, undef, $sequence) =
 8282:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8283:     return if ($sequence eq '');
 8284:     my $navmap = Apache::lonnavmaps::navmap->new();
 8285:     unless (ref($navmap)) {
 8286:         return;
 8287:     }
 8288:     my $needs_hand_bubbles;
 8289:     my $map=$navmap->getResourceByUrl($sequence);
 8290:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8291:     foreach my $res (@resources) {
 8292:         if (ref($res)) {
 8293:             if ($res->is_problem()) {
 8294:                 my $partlist = $res->parts();
 8295:                 foreach my $part (@{ $partlist }) {
 8296:                     my @types = $res->responseType($part);
 8297:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
 8298:                         $needs_hand_bubbles = 1;
 8299:                         last;
 8300:                     }
 8301:                 }
 8302:             }
 8303:         }
 8304:     }
 8305:     if ($needs_hand_bubbles) {
 8306:         my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8307:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8308:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
 8309:                &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 />').
 8310:                '<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;'.
 8311:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
 8312:     }
 8313:     return;
 8314: }
 8315: 
 8316: sub scantron_process_students {
 8317:     my ($r,$symb) = @_;
 8318: 
 8319:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8320:     if (!$symb) {
 8321: 	return '';
 8322:     }
 8323:     my $default_form_data=&defaultFormData($symb);
 8324: 
 8325:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8326:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config); 
 8327:     my ($scanlines,$scan_data)=&scantron_getfile();
 8328:     my $classlist=&Apache::loncoursedata::get_classlist();
 8329:     my %idmap=&username_to_idmap($classlist);
 8330:     my $navmap=Apache::lonnavmaps::navmap->new();
 8331:     unless (ref($navmap)) {
 8332:         $r->print(&navmap_errormsg());
 8333:         return '';
 8334:     }
 8335:     my $map=$navmap->getResourceByUrl($sequence);
 8336:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8337:         %grader_randomlists_by_symb);
 8338:     if (ref($map)) {
 8339:         $randomorder = $map->randomorder();
 8340:         $randompick = $map->randompick();
 8341:     } else {
 8342:         $r->print(&navmap_errormsg());
 8343:         return '';
 8344:     }
 8345:     my $nav_error;
 8346:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8347:     if ($randomorder || $randompick) {
 8348:         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8349:         if ($nav_error) {
 8350:             $r->print(&navmap_errormsg());
 8351:             return '';
 8352:         }
 8353:     }
 8354:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8355:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 8356: 
 8357:     my ($uname,$udom);
 8358:     my $result= <<SCANTRONFORM;
 8359: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 8360:   <input type="hidden" name="command" value="scantron_configphase" />
 8361:   $default_form_data
 8362: SCANTRONFORM
 8363:     $r->print($result);
 8364: 
 8365:     my @delayqueue;
 8366:     my (%completedstudents,%scandata);
 8367:     
 8368:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 8369:     my $count=&get_todo_count($scanlines,$scan_data);
 8370:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 8371:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
 8372:     $r->print('<br />');
 8373:     my $start=&Time::HiRes::time();
 8374:     my $i=-1;
 8375:     my $started;
 8376: 
 8377:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 8378:     if ($nav_error) {
 8379:         $r->print(&navmap_errormsg());
 8380:         return '';
 8381:     }
 8382: 
 8383:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 8384:     # the user and return.
 8385: 
 8386:     if ($ssi_error) {
 8387: 	$r->print("</form>");
 8388: 	&ssi_print_error($r);
 8389:         &Apache::lonnet::remove_lock($lock);
 8390: 	return '';		# Dunno why the other returns return '' rather than just returning.
 8391:     }
 8392: 
 8393:     my %lettdig = &letter_to_digits();
 8394:     my $numletts = scalar(keys(%lettdig));
 8395:     my %orderedforcode;
 8396: 
 8397:     while ($i<$scanlines->{'count'}) {
 8398:  	($uname,$udom)=('','');
 8399:  	$i++;
 8400:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8401:  	if ($line=~/^[\s\cz]*$/) { next; }
 8402: 	if ($started) {
 8403: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
 8404: 	}
 8405: 	$started=1;
 8406:         my %respnumlookup = ();
 8407:         my %startline = ();
 8408:         my $total;
 8409:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8410:                                                  $scan_data,undef,\%idmap,$randomorder,
 8411:                                                  $randompick,$sequence,\@master_seq,
 8412:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 8413:                                                  \%orderedforcode,\%respnumlookup,\%startline,
 8414:                                                  \$total);
 8415:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 8416:  					      \%idmap,$i)) {
 8417:   	    &scantron_add_delay(\@delayqueue,$line,
 8418:  				'Unable to find a student that matches',1);
 8419:  	    next;
 8420:   	}
 8421:  	if (exists $completedstudents{$uname}) {
 8422:  	    &scantron_add_delay(\@delayqueue,$line,
 8423:  				'Student '.$uname.' has multiple sheets',2);
 8424:  	    next;
 8425:  	}
 8426:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 8427:         my $user = $uname.':'.$usec;
 8428:   	($uname,$udom)=split(/:/,$uname);
 8429: 
 8430:         my $scancode;
 8431:         if ((exists($scan_record->{'scantron.CODE'})) &&
 8432:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 8433:             $scancode = $scan_record->{'scantron.CODE'};
 8434:         } else {
 8435:             $scancode = '';
 8436:         }
 8437: 
 8438:         my @mapresources = @resources;
 8439:         if ($randomorder || $randompick) {
 8440:             @mapresources = 
 8441:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
 8442:                              \%orderedforcode);
 8443:         }
 8444:         my (%partids_by_symb,$res_error);
 8445:         foreach my $resource (@mapresources) {
 8446:             my $ressymb;
 8447:             if (ref($resource)) {
 8448:                 $ressymb = $resource->symb();
 8449:             } else {
 8450:                 $res_error = 1;
 8451:                 last;
 8452:             }
 8453:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 8454:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 8455:                 my ($analysis,$parts) =
 8456:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 8457:                                               $uname,$udom,undef,$bubbles_per_row);
 8458:                 $partids_by_symb{$ressymb} = $parts;
 8459:             } else {
 8460:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
 8461:             }
 8462:         }
 8463: 
 8464:         if ($res_error) {
 8465:             &scantron_add_delay(\@delayqueue,$line,
 8466:                                 'An error occurred while grading student '.$uname,2);
 8467:             next;
 8468:         }
 8469: 
 8470: 	&Apache::lonxml::clear_problem_counter();
 8471:   	&Apache::lonnet::appenv($scan_record);
 8472: 
 8473: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 8474: 	    &scantron_putfile($scanlines,$scan_data);
 8475: 	}
 8476: 	
 8477:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 8478:                                    \@mapresources,\%partids_by_symb,
 8479:                                    $bubbles_per_row,$randomorder,$randompick,
 8480:                                    \%respnumlookup,\%startline) 
 8481:             eq 'ssi_error') {
 8482:             $ssi_error = 0; # So end of handler error message does not trigger.
 8483:             $r->print("</form>");
 8484:             &ssi_print_error($r);
 8485:             &Apache::lonnet::remove_lock($lock);
 8486:             return '';      # Why return ''?  Beats me.
 8487:         }
 8488: 
 8489:         if (($scancode) && ($randomorder || $randompick)) {
 8490:             my $parmresult =
 8491:                 &Apache::lonparmset::storeparm_by_symb($symb,
 8492:                                                        '0_examcode',2,$scancode,
 8493:                                                        'string_examcode',$uname,
 8494:                                                        $udom);
 8495:         }
 8496: 	$completedstudents{$uname}={'line'=>$line};
 8497:         if ($env{'form.verifyrecord'}) {
 8498:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 8499:             if ($randompick) {
 8500:                 if ($total) {
 8501:                     $lastpos = $total*$scantron_config{'Qlength'};
 8502:                 }
 8503:             }
 8504: 
 8505:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 8506:             chomp($studentdata);
 8507:             $studentdata =~ s/\r$//;
 8508:             my $studentrecord = '';
 8509:             my $counter = -1;
 8510:             foreach my $resource (@mapresources) {
 8511:                 my $ressymb = $resource->symb();
 8512:                 ($counter,my $recording) =
 8513:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 8514:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
 8515:                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
 8516:                                              $randompick,\%respnumlookup,\%startline);
 8517:                 $studentrecord .= $recording;
 8518:             }
 8519:             if ($studentrecord ne $studentdata) {
 8520:                 &Apache::lonxml::clear_problem_counter();
 8521:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 8522:                                            \@mapresources,\%partids_by_symb,
 8523:                                            $bubbles_per_row,$randomorder,$randompick,
 8524:                                            \%respnumlookup,\%startline) 
 8525:                     eq 'ssi_error') {
 8526:                     $ssi_error = 0; # So end of handler error message does not trigger.
 8527:                     $r->print("</form>");
 8528:                     &ssi_print_error($r);
 8529:                     &Apache::lonnet::remove_lock($lock);
 8530:                     delete($completedstudents{$uname});
 8531:                     return '';
 8532:                 }
 8533:                 $counter = -1;
 8534:                 $studentrecord = '';
 8535:                 foreach my $resource (@mapresources) {
 8536:                     my $ressymb = $resource->symb();
 8537:                     ($counter,my $recording) =
 8538:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 8539:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 8540:                                                  \%scantron_config,\%lettdig,$numletts,
 8541:                                                  $randomorder,$randompick,\%respnumlookup,
 8542:                                                  \%startline);
 8543:                     $studentrecord .= $recording;
 8544:                 }
 8545:                 if ($studentrecord ne $studentdata) {
 8546:                     $r->print('<p><span class="LC_warning">');
 8547:                     if ($scancode eq '') {
 8548:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
 8549:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 8550:                     } else {
 8551:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
 8552:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 8553:                     }
 8554:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 8555:                               &Apache::loncommon::start_data_table_header_row()."\n".
 8556:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 8557:                               &Apache::loncommon::end_data_table_header_row()."\n".
 8558:                               &Apache::loncommon::start_data_table_row().
 8559:                               '<td>'.&mt('Bubblesheet').'</td>'.
 8560:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
 8561:                               &Apache::loncommon::end_data_table_row().
 8562:                               &Apache::loncommon::start_data_table_row().
 8563:                               '<td>'.&mt('Stored submissions').'</td>'.
 8564:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
 8565:                               &Apache::loncommon::end_data_table_row().
 8566:                               &Apache::loncommon::end_data_table().'</p>');
 8567:                 } else {
 8568:                     $r->print('<br /><span class="LC_warning">'.
 8569:                              &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 />'.
 8570:                              &mt("As a consequence, this user's submission history records two tries.").
 8571:                                  '</span><br />');
 8572:                 }
 8573:             }
 8574:         }
 8575:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 8576:     } continue {
 8577: 	&Apache::lonxml::clear_problem_counter();
 8578: 	&Apache::lonnet::delenv('scantron.');
 8579:     }
 8580:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 8581:     &Apache::lonnet::remove_lock($lock);
 8582: #    my $lasttime = &Time::HiRes::time()-$start;
 8583: #    $r->print("<p>took $lasttime</p>");
 8584: 
 8585:     $r->print("</form>");
 8586:     return '';
 8587: }
 8588: 
 8589: sub graders_resources_pass {
 8590:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
 8591:         $bubbles_per_row) = @_;
 8592:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
 8593:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
 8594:         foreach my $resource (@{$resources}) {
 8595:             my $ressymb = $resource->symb();
 8596:             my ($analysis,$parts) =
 8597:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
 8598:                                           $env{'user.name'},$env{'user.domain'},
 8599:                                           1,$bubbles_per_row);
 8600:             $grader_partids_by_symb->{$ressymb} = $parts;
 8601:             if (ref($analysis) eq 'HASH') {
 8602:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 8603:                     $grader_randomlists_by_symb->{$ressymb} =
 8604:                         $analysis->{'parts_withrandomlist'};
 8605:                 }
 8606:             }
 8607:         }
 8608:     }
 8609:     return;
 8610: }
 8611: 
 8612: =pod
 8613: 
 8614: =item users_order
 8615: 
 8616:   Returns array of resources in current map, ordered based on either CODE,
 8617:   if this is a CODEd exam, or based on student's identity if this is a 
 8618:   "NAMEd" exam.
 8619: 
 8620:   Should be used when randomorder and/or randompick applied when the 
 8621:   corresponding exam was printed, prior to students completing bubblesheets 
 8622:   for the version of the exam the student received.
 8623: 
 8624: =cut
 8625: 
 8626: sub users_order  {
 8627:     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
 8628:     my @mapresources;
 8629:     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
 8630:         return @mapresources;
 8631:     }
 8632:     if ($scancode) {
 8633:         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
 8634:             @mapresources = @{$orderedforcode->{$scancode}};
 8635:         } else {
 8636:             $env{'form.CODE'} = $scancode;
 8637:             my $actual_seq =
 8638:                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 8639:                                                                $master_seq,
 8640:                                                                $user,$scancode,1);
 8641:             if (ref($actual_seq) eq 'ARRAY') {
 8642:                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
 8643:                 if (ref($orderedforcode) eq 'HASH') {
 8644:                     if (@mapresources > 0) { 
 8645:                         $orderedforcode->{$scancode} = \@mapresources;
 8646:                     }
 8647:                 }
 8648:             }
 8649:             delete($env{'form.CODE'});
 8650:         }
 8651:     } else {
 8652:         my $actual_seq =
 8653:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 8654:                                                            $master_seq,
 8655:                                                            $user,undef,1);
 8656:         if (ref($actual_seq) eq 'ARRAY') {
 8657:             @mapresources = 
 8658:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
 8659:         }
 8660:     }
 8661:     return @mapresources;
 8662: }
 8663: 
 8664: sub grade_student_bubbles {
 8665:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
 8666:         $randomorder,$randompick,$respnumlookup,$startline) = @_;
 8667:     my $uselookup = 0;
 8668:     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
 8669:         (ref($startline) eq 'HASH')) {
 8670:         $uselookup = 1;
 8671:     }
 8672: 
 8673:     if (ref($resources) eq 'ARRAY') {
 8674:         my $count = 0;
 8675:         foreach my $resource (@{$resources}) {
 8676:             my $ressymb = $resource->symb();
 8677:             my %form = ('submitted'      => 'scantron',
 8678:                         'grade_target'   => 'grade',
 8679:                         'grade_username' => $uname,
 8680:                         'grade_domain'   => $udom,
 8681:                         'grade_courseid' => $env{'request.course.id'},
 8682:                         'grade_symb'     => $ressymb,
 8683:                         'CODE'           => $scancode
 8684:                        );
 8685:             if ($bubbles_per_row ne '') {
 8686:                 $form{'bubbles_per_row'} = $bubbles_per_row;
 8687:             }
 8688:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
 8689:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
 8690:             }
 8691:             if (ref($parts) eq 'HASH') {
 8692:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 8693:                     foreach my $part (@{$parts->{$ressymb}}) {
 8694:                         if ($uselookup) {
 8695:                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
 8696:                         } else {
 8697:                             $form{'scantron_questnum_start.'.$part} =
 8698:                                 1+$env{'form.scantron.first_bubble_line.'.$count};
 8699:                         }
 8700:                         $count++;
 8701:                     }
 8702:                 }
 8703:             }
 8704:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 8705:             return 'ssi_error' if ($ssi_error);
 8706:             last if (&Apache::loncommon::connection_aborted($r));
 8707:         }
 8708:     }
 8709:     return;
 8710: }
 8711: 
 8712: sub scantron_upload_scantron_data {
 8713:     my ($r,$symb)=@_;
 8714:     my $dom = $env{'request.role.domain'};
 8715:     my $domdesc = &Apache::lonnet::domain($dom,'description');
 8716:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
 8717:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 8718: 							  'domainid',
 8719: 							  'coursename',$dom);
 8720:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
 8721:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
 8722:     my $default_form_data=&defaultFormData($symb);
 8723:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
 8724:     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.");
 8725:     $r->print(&Apache::lonhtmlcommon::scripttag('
 8726:     function checkUpload(formname) {
 8727: 	if (formname.upfile.value == "") {
 8728: 	    alert("'.$nofile_alert.'");
 8729: 	    return false;
 8730: 	}
 8731:         if (formname.courseid.value == "") {
 8732:             alert("'.$nocourseid_alert.'");
 8733:             return false;
 8734:         }
 8735: 	formname.submit();
 8736:     }
 8737: 
 8738:     function ToSyllabus() {
 8739:         var cdom = '."'$dom'".';
 8740:         var cnum = document.rules.courseid.value;
 8741:         if (cdom == "" || cdom == null) {
 8742:             return;
 8743:         }
 8744:         if (cnum == "" || cnum == null) {
 8745:            return;
 8746:         }
 8747:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
 8748:                             "height=350,width=350,scrollbars=yes,menubar=no");
 8749:         return;
 8750:     }
 8751: 
 8752: '));
 8753:     $r->print('
 8754: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
 8755: 
 8756: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 8757: '.$default_form_data.
 8758:   &Apache::lonhtmlcommon::start_pick_box().
 8759:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
 8760:   '<input name="courseid" type="text" size="30" />'.$select_link.
 8761:   &Apache::lonhtmlcommon::row_closure().
 8762:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
 8763:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
 8764:   &Apache::lonhtmlcommon::row_closure().
 8765:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
 8766:   '<input name="domainid" type="hidden" />'.$domdesc.
 8767:   &Apache::lonhtmlcommon::row_closure().
 8768:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
 8769:   '<input type="file" name="upfile" size="50" />'.
 8770:   &Apache::lonhtmlcommon::row_closure(1).
 8771:   &Apache::lonhtmlcommon::end_pick_box().'<br />
 8772: 
 8773: <input name="command" value="scantronupload_save" type="hidden" />
 8774: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 8775: </form>
 8776: ');
 8777:     return '';
 8778: }
 8779: 
 8780: 
 8781: sub scantron_upload_scantron_data_save {
 8782:     my($r,$symb)=@_;
 8783:     my $doanotherupload=
 8784: 	'<br /><form action="/adm/grades" method="post">'."\n".
 8785: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 8786: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 8787: 	'</form>'."\n";
 8788:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 8789: 	!&Apache::lonnet::allowed('usc',
 8790: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 8791: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
 8792: 	unless ($symb) {
 8793: 	    $r->print($doanotherupload);
 8794: 	}
 8795: 	return '';
 8796:     }
 8797:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 8798:     my $uploadedfile;
 8799:     $r->print('<p>'.&mt('Uploading file to [_1]','"'.$coursedata{'description'}.'"').'</p>');
 8800:     if (length($env{'form.upfile'}) < 2) {
 8801:         $r->print(
 8802:             &Apache::lonhtmlcommon::confirm_success(
 8803:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
 8804:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
 8805:     } else {
 8806:         my $result = 
 8807:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
 8808:                                             $env{'form.courseid'},$env{'form.domainid'});
 8809:         if ($result =~ m{^/uploaded/}) {
 8810:             $r->print(
 8811:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
 8812:                 &mt('Uploaded [_1] bytes of data into location: [_2]',
 8813:                         (length($env{'form.upfile'})-1),
 8814:                         '<span class="LC_filename">'.$result.'</span>'));
 8815:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
 8816:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
 8817:                                                        $env{'form.courseid'},$uploadedfile));
 8818:         } else {
 8819:             $r->print(
 8820:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
 8821:                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
 8822:                           $result,
 8823: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 8824: 	}
 8825:     }
 8826:     if ($symb) {
 8827: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
 8828:     } else {
 8829: 	$r->print($doanotherupload);
 8830:     }
 8831:     return '';
 8832: }
 8833: 
 8834: sub validate_uploaded_scantron_file {
 8835:     my ($cdom,$cname,$fname) = @_;
 8836:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
 8837:     my @lines;
 8838:     if ($scanlines ne '-1') {
 8839:         @lines=split("\n",$scanlines,-1);
 8840:     }
 8841:     my $output;
 8842:     if (@lines) {
 8843:         my (%counts,$max_match_format);
 8844:         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
 8845:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
 8846:         my %idmap = &username_to_idmap($classlist);
 8847:         foreach my $key (keys(%idmap)) {
 8848:             my $lckey = lc($key);
 8849:             $idmap{$lckey} = $idmap{$key};
 8850:         }
 8851:         my %unique_formats;
 8852:         my @formatlines = &get_scantronformat_file();
 8853:         foreach my $line (@formatlines) {
 8854:             chomp($line);
 8855:             my @config = split(/:/,$line);
 8856:             my $idstart = $config[5];
 8857:             my $idlength = $config[6];
 8858:             if (($idstart ne '') && ($idlength > 0)) {
 8859:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
 8860:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
 8861:                 } else {
 8862:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
 8863:                 }
 8864:             }
 8865:         }
 8866:         foreach my $key (keys(%unique_formats)) {
 8867:             my ($idstart,$idlength) = split(':',$key);
 8868:             %{$counts{$key}} = (
 8869:                                'found'   => 0,
 8870:                                'total'   => 0,
 8871:                               );
 8872:             foreach my $line (@lines) {
 8873:                 next if ($line =~ /^#/);
 8874:                 next if ($line =~ /^[\s\cz]*$/);
 8875:                 my $id = substr($line,$idstart-1,$idlength);
 8876:                 $id = lc($id);
 8877:                 if (exists($idmap{$id})) {
 8878:                     $counts{$key}{'found'} ++;
 8879:                 }
 8880:                 $counts{$key}{'total'} ++;
 8881:             }
 8882:             if ($counts{$key}{'total'}) {
 8883:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
 8884:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
 8885:                     $max_match_pct = $percent_match;
 8886:                     $max_match_format = $key;
 8887:                     $found_match_count = $counts{$key}{'found'};
 8888:                     $max_match_count = $counts{$key}{'total'};
 8889:                 }
 8890:             }
 8891:         }
 8892:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
 8893:             my $format_descs;
 8894:             my $numwithformat = @{$unique_formats{$max_match_format}};
 8895:             for (my $i=0; $i<$numwithformat; $i++) {
 8896:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
 8897:                 if ($i<$numwithformat-2) {
 8898:                     $format_descs .= '"<i>'.$desc.'</i>", ';
 8899:                 } elsif ($i==$numwithformat-2) {
 8900:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
 8901:                 } elsif ($i==$numwithformat-1) {
 8902:                     $format_descs .= '"<i>'.$desc.'</i>"';
 8903:                 }
 8904:             }
 8905:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
 8906:             $output .= '<br />';
 8907:             if ($found_match_count == $max_match_count) {
 8908:                 # 100% matching entries
 8909:                 $output .= &Apache::lonhtmlcommon::confirm_success(
 8910:                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
 8911:                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
 8912:                 &mt('Comparison of student IDs in the uploaded file with'.
 8913:                     ' the course roster found matches for [_1] of the [_2] entries'.
 8914:                     ' in the file (for the format defined for [_3]).',
 8915:                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
 8916:             } else {
 8917:                 # Not all entries matching? -> Show warning and additional info
 8918:                 $output .=
 8919:                     &Apache::lonhtmlcommon::confirm_success(
 8920:                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
 8921:                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
 8922:                         &mt('Not all entries could be matched!'),1).'<br />'.
 8923:                     &mt('Comparison of student IDs in the uploaded file with'.
 8924:                         ' the course roster found matches for [_1] of the [_2] entries'.
 8925:                         ' in the file (for the format defined for [_3]).',
 8926:                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
 8927:                     '<p class="LC_info">'.
 8928:                     &mt('A low percentage of matches results from one of the following:').
 8929:                     '</p><ul>'.
 8930:                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
 8931:                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
 8932:                                '<i>'.$cdom.'</i>').'</li>'.
 8933:                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
 8934:                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
 8935:                     '</ul>';
 8936:             }
 8937:         }
 8938:     } else {
 8939:         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
 8940:     }
 8941:     return $output;
 8942: }
 8943: 
 8944: sub valid_file {
 8945:     my ($requested_file)=@_;
 8946:     foreach my $filename (sort(&scantron_filenames())) {
 8947: 	if ($requested_file eq $filename) { return 1; }
 8948:     }
 8949:     return 0;
 8950: }
 8951: 
 8952: sub scantron_download_scantron_data {
 8953:     my ($r,$symb)=@_;
 8954:     my $default_form_data=&defaultFormData($symb);
 8955:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 8956:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8957:     my $file=$env{'form.scantron_selectfile'};
 8958:     if (! &valid_file($file)) {
 8959: 	$r->print('
 8960: 	<p>
 8961: 	    '.&mt('The requested filename was invalid.').'
 8962:         </p>
 8963: ');
 8964: 	return;
 8965:     }
 8966:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 8967:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 8968:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 8969:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 8970:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 8971:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 8972:     $r->print('
 8973:     <p>
 8974: 	'.&mt('[_1]Original[_2] file as uploaded by the bubblesheet scanning office.',
 8975: 	      '<a href="'.$orig.'">','</a>').'
 8976:     </p>
 8977:     <p>
 8978: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 8979: 	      '<a href="'.$corrected.'">','</a>').'
 8980:     </p>
 8981:     <p>
 8982: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 8983: 	      '<a href="'.$skipped.'">','</a>').'
 8984:     </p>
 8985: ');
 8986:     return '';
 8987: }
 8988: 
 8989: sub checkscantron_results {
 8990:     my ($r,$symb) = @_;
 8991:     if (!$symb) {return '';}
 8992:     my $cid = $env{'request.course.id'};
 8993:     my %lettdig = &letter_to_digits();
 8994:     my $numletts = scalar(keys(%lettdig));
 8995:     my $cnum = $env{'course.'.$cid.'.num'};
 8996:     my $cdom = $env{'course.'.$cid.'.domain'};
 8997:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8998:     my %record;
 8999:     my %scantron_config =
 9000:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
 9001:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 9002:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
 9003:     my $classlist=&Apache::loncoursedata::get_classlist();
 9004:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 9005:     my $navmap=Apache::lonnavmaps::navmap->new();
 9006:     unless (ref($navmap)) {
 9007:         $r->print(&navmap_errormsg());
 9008:         return '';
 9009:     }
 9010:     my $map=$navmap->getResourceByUrl($sequence);
 9011:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 9012:         %grader_randomlists_by_symb,%orderedforcode);
 9013:     if (ref($map)) { 
 9014:         $randomorder=$map->randomorder();
 9015:         $randompick=$map->randompick();
 9016:     }
 9017:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 9018:     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 9019:     if ($nav_error) {
 9020:         $r->print(&navmap_errormsg());
 9021:         return '';
 9022:     }
 9023:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 9024:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 9025:     my ($uname,$udom);
 9026:     my (%scandata,%lastname,%bylast);
 9027:     $r->print('
 9028: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 9029: 
 9030:     my @delayqueue;
 9031:     my %completedstudents;
 9032: 
 9033:     my $count=&get_todo_count($scanlines,$scan_data);
 9034:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 9035:     my ($username,$domain,$started);
 9036:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 9037:     if ($nav_error) {
 9038:         $r->print(&navmap_errormsg());
 9039:         return '';
 9040:     }
 9041: 
 9042:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
 9043:     my $start=&Time::HiRes::time();
 9044:     my $i=-1;
 9045: 
 9046:     while ($i<$scanlines->{'count'}) {
 9047:         ($username,$domain,$uname)=('','','');
 9048:         $i++;
 9049:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 9050:         if ($line=~/^[\s\cz]*$/) { next; }
 9051:         if ($started) {
 9052:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
 9053:         }
 9054:         $started=1;
 9055:         my $scan_record=
 9056:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 9057:                                                      $scan_data);
 9058:         unless ($uname=&scantron_find_student($scan_record,$scan_data,
 9059:                                               \%idmap,$i)) {
 9060:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 9061:                                 'Unable to find a student that matches',1);
 9062:             next;
 9063:         }
 9064:         if (exists $completedstudents{$uname}) {
 9065:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 9066:                                 'Student '.$uname.' has multiple sheets',2);
 9067:             next;
 9068:         }
 9069:         my $pid = $scan_record->{'scantron.ID'};
 9070:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 9071:         push(@{$bylast{$lastname{$pid}}},$pid);
 9072:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 9073:         my $user = $uname.':'.$usec;
 9074:         ($username,$domain)=split(/:/,$uname);
 9075: 
 9076:         my $scancode;
 9077:         if ((exists($scan_record->{'scantron.CODE'})) &&
 9078:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 9079:             $scancode = $scan_record->{'scantron.CODE'};
 9080:         } else {
 9081:             $scancode = '';
 9082:         }
 9083: 
 9084:         my @mapresources = @resources;
 9085:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 9086:         my %respnumlookup=();
 9087:         my %startline=();
 9088:         if ($randomorder || $randompick) {
 9089:             @mapresources =
 9090:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
 9091:                              \%orderedforcode);
 9092:             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
 9093:                                              $scan_record,\@master_seq,\%symb_to_resource,
 9094:                                              \%grader_partids_by_symb,\%orderedforcode,
 9095:                                              \%respnumlookup,\%startline);
 9096:             if ($randompick && $total) {
 9097:                 $lastpos = $total*$scantron_config{'Qlength'};
 9098:             }
 9099:         }
 9100:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 9101:         chomp($scandata{$pid});
 9102:         $scandata{$pid} =~ s/\r$//;
 9103: 
 9104:         my $counter = -1;
 9105:         foreach my $resource (@mapresources) {
 9106:             my $parts;
 9107:             my $ressymb = $resource->symb();
 9108:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 9109:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 9110:                 (my $analysis,$parts) =
 9111:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 9112:                                               $username,$domain,undef,
 9113:                                               $bubbles_per_row);
 9114:             } else {
 9115:                 $parts = $grader_partids_by_symb{$ressymb};
 9116:             }
 9117:             ($counter,my $recording) =
 9118:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
 9119:                                          $scandata{$pid},$parts,
 9120:                                          \%scantron_config,\%lettdig,$numletts,
 9121:                                          $randomorder,$randompick,
 9122:                                          \%respnumlookup,\%startline);
 9123:             $record{$pid} .= $recording;
 9124:         }
 9125:     }
 9126:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 9127:     $r->print('<br />');
 9128:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 9129:     $passed = 0;
 9130:     $failed = 0;
 9131:     $numstudents = 0;
 9132:     foreach my $last (sort(keys(%bylast))) {
 9133:         if (ref($bylast{$last}) eq 'ARRAY') {
 9134:             foreach my $pid (sort(@{$bylast{$last}})) {
 9135:                 my $showscandata = $scandata{$pid};
 9136:                 my $showrecord = $record{$pid};
 9137:                 $showscandata =~ s/\s/&nbsp;/g;
 9138:                 $showrecord =~ s/\s/&nbsp;/g;
 9139:                 if ($scandata{$pid} eq $record{$pid}) {
 9140:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 9141:                     $okstudents .= '<tr class="'.$css_class.'">'.
 9142: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 9143: '</tr>'."\n".
 9144: '<tr class="'.$css_class.'">'."\n".
 9145: '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
 9146:                     $passed ++;
 9147:                 } else {
 9148:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
 9149:                     $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".
 9150: '</tr>'."\n".
 9151: '<tr class="'.$css_class.'">'."\n".
 9152: '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
 9153: '</tr>'."\n";
 9154:                     $failed ++;
 9155:                 }
 9156:                 $numstudents ++;
 9157:             }
 9158:         }
 9159:     }
 9160:     $r->print(
 9161:         '<p>'
 9162:        .&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).',
 9163:             '<b>',
 9164:             $numstudents,
 9165:             '</b>',
 9166:             $env{'form.scantron_maxbubble'})
 9167:        .'</p>'
 9168:     );
 9169:     $r->print('<p>'
 9170:              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
 9171:              .'<br />'
 9172:              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
 9173:              .'</p>'
 9174:     );
 9175:     if ($passed) {
 9176:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
 9177:         $r->print(&Apache::loncommon::start_data_table()."\n".
 9178:                  &Apache::loncommon::start_data_table_header_row()."\n".
 9179:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 9180:                  &Apache::loncommon::end_data_table_header_row()."\n".
 9181:                  $okstudents."\n".
 9182:                  &Apache::loncommon::end_data_table().'<br />');
 9183:     }
 9184:     if ($failed) {
 9185:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
 9186:         $r->print(&Apache::loncommon::start_data_table()."\n".
 9187:                  &Apache::loncommon::start_data_table_header_row()."\n".
 9188:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 9189:                  &Apache::loncommon::end_data_table_header_row()."\n".
 9190:                  $badstudents."\n".
 9191:                  &Apache::loncommon::end_data_table()).'<br />'.
 9192:                  &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.');  
 9193:     }
 9194:     $r->print('</form><br />');
 9195:     return;
 9196: }
 9197: 
 9198: sub verify_scantron_grading {
 9199:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
 9200:         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
 9201:         $respnumlookup,$startline) = @_;
 9202:     my ($record,%expected,%startpos);
 9203:     return ($counter,$record) if (!ref($resource));
 9204:     return ($counter,$record) if (!$resource->is_problem());
 9205:     my $symb = $resource->symb();
 9206:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
 9207:     foreach my $part_id (@{$partids}) {
 9208:         $counter ++;
 9209:         $expected{$part_id} = 0;
 9210:         my $respnum = $counter;
 9211:         if ($randomorder || $randompick) {
 9212:             $respnum = $respnumlookup->{$counter};
 9213:             $startpos{$part_id} = $startline->{$counter} + 1;
 9214:         } else {
 9215:             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
 9216:         }
 9217:         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
 9218:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
 9219:             foreach my $item (@sub_lines) {
 9220:                 $expected{$part_id} += $item;
 9221:             }
 9222:         } else {
 9223:             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
 9224:         }
 9225:     }
 9226:     if ($symb) {
 9227:         my %recorded;
 9228:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
 9229:         if ($returnhash{'version'}) {
 9230:             my %lasthash=();
 9231:             my $version;
 9232:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 9233:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 9234:                     $lasthash{$key}=$returnhash{$version.':'.$key};
 9235:                 }
 9236:             }
 9237:             foreach my $key (keys(%lasthash)) {
 9238:                 if ($key =~ /\.scantron$/) {
 9239:                     my $value = &unescape($lasthash{$key});
 9240:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
 9241:                     if ($value eq '') {
 9242:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
 9243:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
 9244:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9245:                             }
 9246:                         }
 9247:                     } else {
 9248:                         my @tocheck;
 9249:                         my @items = split(//,$value);
 9250:                         if (($scantron_config->{'Qon'} eq 'letter') ||
 9251:                             ($scantron_config->{'Qon'} eq 'number')) {
 9252:                             if (@items < $expected{$part_id}) {
 9253:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
 9254:                                 my @singles = split(//,$fragment);
 9255:                                 foreach my $pos (@singles) {
 9256:                                     if ($pos eq ' ') {
 9257:                                         push(@tocheck,$pos);
 9258:                                     } else {
 9259:                                         my $next = shift(@items);
 9260:                                         push(@tocheck,$next);
 9261:                                     }
 9262:                                 }
 9263:                             } else {
 9264:                                 @tocheck = @items;
 9265:                             }
 9266:                             foreach my $letter (@tocheck) {
 9267:                                 if ($scantron_config->{'Qon'} eq 'letter') {
 9268:                                     if ($letter !~ /^[A-J]$/) {
 9269:                                         $letter = $scantron_config->{'Qoff'};
 9270:                                     }
 9271:                                     $recorded{$part_id} .= $letter;
 9272:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
 9273:                                     my $digit;
 9274:                                     if ($letter !~ /^[A-J]$/) {
 9275:                                         $digit = $scantron_config->{'Qoff'};
 9276:                                     } else {
 9277:                                         $digit = $lettdig->{$letter};
 9278:                                     }
 9279:                                     $recorded{$part_id} .= $digit;
 9280:                                 }
 9281:                             }
 9282:                         } else {
 9283:                             @tocheck = @items;
 9284:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
 9285:                                 my $curr_sub = shift(@tocheck);
 9286:                                 my $digit;
 9287:                                 if ($curr_sub =~ /^[A-J]$/) {
 9288:                                     $digit = $lettdig->{$curr_sub}-1;
 9289:                                 }
 9290:                                 if ($curr_sub eq 'J') {
 9291:                                     $digit += scalar($numletts);
 9292:                                 }
 9293:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 9294:                                     if ($j == $digit) {
 9295:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
 9296:                                     } else {
 9297:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9298:                                     }
 9299:                                 }
 9300:                             }
 9301:                         }
 9302:                     }
 9303:                 }
 9304:             }
 9305:         }
 9306:         foreach my $part_id (@{$partids}) {
 9307:             if ($recorded{$part_id} eq '') {
 9308:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
 9309:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 9310:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9311:                     }
 9312:                 }
 9313:             }
 9314:             $record .= $recorded{$part_id};
 9315:         }
 9316:     }
 9317:     return ($counter,$record);
 9318: }
 9319: 
 9320: sub letter_to_digits {
 9321:     my %lettdig = (
 9322:                     A => 1,
 9323:                     B => 2,
 9324:                     C => 3,
 9325:                     D => 4,
 9326:                     E => 5,
 9327:                     F => 6,
 9328:                     G => 7,
 9329:                     H => 8,
 9330:                     I => 9,
 9331:                     J => 0,
 9332:                   );
 9333:     return %lettdig;
 9334: }
 9335: 
 9336: 
 9337: #-------- end of section for handling grading scantron forms -------
 9338: #
 9339: #-------------------------------------------------------------------
 9340: 
 9341: #-------------------------- Menu interface -------------------------
 9342: #
 9343: #--- Href with symb and command ---
 9344: 
 9345: sub href_symb_cmd {
 9346:     my ($symb,$cmd)=@_;
 9347:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
 9348: }
 9349: 
 9350: sub grading_menu {
 9351:     my ($request,$symb) = @_;
 9352:     if (!$symb) {return '';}
 9353: 
 9354:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 9355:                   'command'=>'individual');
 9356:     
 9357:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9358: 
 9359:     $fields{'command'}='ungraded';
 9360:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9361: 
 9362:     $fields{'command'}='table';
 9363:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9364: 
 9365:     $fields{'command'}='all_for_one';
 9366:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9367: 
 9368:     $fields{'command'}='downloadfilesselect';
 9369:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9370: 
 9371:     $fields{'command'} = 'csvform';
 9372:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9373:     
 9374:     $fields{'command'} = 'processclicker';
 9375:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9376:     
 9377:     $fields{'command'} = 'scantron_selectphase';
 9378:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9379: 
 9380:     $fields{'command'} = 'initialverifyreceipt';
 9381:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9382:     
 9383:     my @menu = ({	categorytitle=>'Hand Grading',
 9384:             items =>[
 9385:                         {	linktext => 'Select individual students to grade',
 9386:                     		url => $url1a,
 9387:                     		permission => 'F',
 9388:                     		icon => 'grade_students.png',
 9389:                     		linktitle => 'Grade current resource for a selection of students.'
 9390:                         }, 
 9391:                         {       linktext => 'Grade ungraded submissions.',
 9392:                                 url => $url1b,
 9393:                                 permission => 'F',
 9394:                                 icon => 'ungrade_sub.png',
 9395:                                 linktitle => 'Grade all submissions that have not been graded yet.'
 9396:                         },
 9397: 
 9398:                         {       linktext => 'Grading table',
 9399:                                 url => $url1c,
 9400:                                 permission => 'F',
 9401:                                 icon => 'grading_table.png',
 9402:                                 linktitle => 'Grade current resource for all students.'
 9403:                         },
 9404:                         {       linktext => 'Grade page/folder for one student',
 9405:                                 url => $url1d,
 9406:                                 permission => 'F',
 9407:                                 icon => 'grade_PageFolder.png',
 9408:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
 9409:                         },
 9410:                         {       linktext => 'Download submissions',
 9411:                                 url => $url1e,
 9412:                                 permission => 'F',
 9413:                                 icon => 'download_sub.png',
 9414:                                 linktitle => 'Download all students submissions.'
 9415:                         }]},
 9416:                          { categorytitle=>'Automated Grading',
 9417:                items =>[
 9418: 
 9419:                 	    {	linktext => 'Upload Scores',
 9420:                     		url => $url2,
 9421:                     		permission => 'F',
 9422:                     		icon => 'uploadscores.png',
 9423:                     		linktitle => 'Specify a file containing the class scores for current resource.'
 9424:                 	    },
 9425:                 	    {	linktext => 'Process Clicker',
 9426:                     		url => $url3,
 9427:                     		permission => 'F',
 9428:                     		icon => 'addClickerInfoFile.png',
 9429:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
 9430:                 	    },
 9431:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
 9432:                     		url => $url4,
 9433:                     		permission => 'F',
 9434:                     		icon => 'bubblesheet.png',
 9435:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
 9436:                 	    },
 9437:                             {   linktext => 'Verify Receipt Number',
 9438:                                 url => $url5,
 9439:                                 permission => 'F',
 9440:                                 icon => 'receipt_number.png',
 9441:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
 9442:                             }
 9443: 
 9444:                     ]
 9445:             });
 9446: 
 9447:     # Create the menu
 9448:     my $Str;
 9449:     $Str .= '<form method="post" action="" name="gradingMenu">';
 9450:     $Str .= '<input type="hidden" name="command" value="" />'.
 9451:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 9452: 
 9453:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
 9454:     return $Str;    
 9455: }
 9456: 
 9457: 
 9458: sub ungraded {
 9459:     my ($request)=@_;
 9460:     &submit_options($request);
 9461: }
 9462: 
 9463: sub submit_options_sequence {
 9464:     my ($request,$symb) = @_;
 9465:     if (!$symb) {return '';}
 9466:     &commonJSfunctions($request);
 9467:     my $result;
 9468: 
 9469:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 9470:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 9471:     $result.=&selectfield(0).
 9472:             '<input type="hidden" name="command" value="pickStudentPage" />
 9473:             <div>
 9474:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 9475:             </div>
 9476:         </div>
 9477:   </form>';
 9478:     return $result;
 9479: }
 9480: 
 9481: sub submit_options_table {
 9482:     my ($request,$symb) = @_;
 9483:     if (!$symb) {return '';}
 9484:     &commonJSfunctions($request);
 9485:     my $result;
 9486: 
 9487:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 9488:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 9489: 
 9490:     $result.=&selectfield(0).
 9491:             '<input type="hidden" name="command" value="viewgrades" />
 9492:             <div>
 9493:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 9494:             </div>
 9495:         </div>
 9496:   </form>';
 9497:     return $result;
 9498: }
 9499: 
 9500: sub submit_options_download {
 9501:     my ($request,$symb) = @_;
 9502:     if (!$symb) {return '';}
 9503: 
 9504:     &commonJSfunctions($request);
 9505: 
 9506:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 9507:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 9508:     $result.='
 9509: <h2>
 9510:   '.&mt('Select Students for Which to Download Submissions').'
 9511: </h2>'.&selectfield(1).'
 9512:                 <input type="hidden" name="command" value="downloadfileslink" /> 
 9513:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 9514:             </div>
 9515:           </div>
 9516: 
 9517: 
 9518:   </form>';
 9519:     return $result;
 9520: }
 9521: 
 9522: #--- Displays the submissions first page -------
 9523: sub submit_options {
 9524:     my ($request,$symb) = @_;
 9525:     if (!$symb) {return '';}
 9526: 
 9527:     &commonJSfunctions($request);
 9528:     my $result;
 9529: 
 9530:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 9531: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 9532:     $result.=&selectfield(1).'
 9533:                 <input type="hidden" name="command" value="submission" /> 
 9534: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
 9535:             </div>
 9536:           </div>
 9537: 
 9538: 
 9539:   </form>';
 9540:     return $result;
 9541: }
 9542: 
 9543: sub selectfield {
 9544:    my ($full)=@_;
 9545:    my %options = 
 9546:           (&Apache::lonlocal::texthash(
 9547:              'yes'       => 'with submissions',
 9548:              'queued'    => 'in grading queue',
 9549:              'graded'    => 'with ungraded submissions',
 9550:              'incorrect' => 'with incorrect submissions',
 9551:              'all'       => 'with any status'),
 9552:              'select_form_order' => ['yes','queued','graded','incorrect','all']);
 9553:    my $result='<div class="LC_columnSection">
 9554:   
 9555:     <fieldset>
 9556:       <legend>
 9557:        '.&mt('Sections').'
 9558:       </legend>
 9559:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
 9560:     </fieldset>
 9561:   
 9562:     <fieldset>
 9563:       <legend>
 9564:         '.&mt('Groups').'
 9565:       </legend>
 9566:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
 9567:     </fieldset>
 9568:   
 9569:     <fieldset>
 9570:       <legend>
 9571:         '.&mt('Access Status').'
 9572:       </legend>
 9573:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
 9574:     </fieldset>';
 9575:     if ($full) {
 9576:        $result.='
 9577:     <fieldset>
 9578:       <legend>
 9579:         '.&mt('Submission Status').'
 9580:       </legend>'.
 9581:        &Apache::loncommon::select_form('all','submitonly',\%options).
 9582:    '</fieldset>';
 9583:     }
 9584:     $result.='</div><br />';
 9585:     return $result;
 9586: }
 9587: 
 9588: sub reset_perm {
 9589:     undef(%perm);
 9590: }
 9591: 
 9592: sub init_perm {
 9593:     &reset_perm();
 9594:     foreach my $test_perm ('vgr','mgr','opa') {
 9595: 
 9596: 	my $scope = $env{'request.course.id'};
 9597: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
 9598: 
 9599: 	    $scope .= '/'.$env{'request.course.sec'};
 9600: 	    if ( $perm{$test_perm}=
 9601: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
 9602: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
 9603: 	    } else {
 9604: 		delete($perm{$test_perm});
 9605: 	    }
 9606: 	}
 9607:     }
 9608: }
 9609: 
 9610: sub init_old_essays {
 9611:     my ($symb,$apath,$adom,$aname) = @_;
 9612:     if ($symb ne '') {
 9613:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
 9614:         if (keys(%essays) > 0) {
 9615:             $old_essays{$symb} = \%essays;
 9616:         }
 9617:     }
 9618:     return;
 9619: }
 9620: 
 9621: sub reset_old_essays {
 9622:     undef(%old_essays);
 9623: }
 9624: 
 9625: sub gather_clicker_ids {
 9626:     my %clicker_ids;
 9627: 
 9628:     my $classlist = &Apache::loncoursedata::get_classlist();
 9629: 
 9630:     # Set up a couple variables.
 9631:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
 9632:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
 9633:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
 9634: 
 9635:     foreach my $student (keys(%$classlist)) {
 9636:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
 9637:         my $username = $classlist->{$student}->[$username_idx];
 9638:         my $domain   = $classlist->{$student}->[$domain_idx];
 9639:         my $clickers =
 9640: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
 9641:         foreach my $id (split(/\,/,$clickers)) {
 9642:             $id=~s/^[\#0]+//;
 9643:             $id=~s/[\-\:]//g;
 9644:             if (exists($clicker_ids{$id})) {
 9645: 		$clicker_ids{$id}.=','.$username.':'.$domain;
 9646:             } else {
 9647: 		$clicker_ids{$id}=$username.':'.$domain;
 9648:             }
 9649:         }
 9650:     }
 9651:     return %clicker_ids;
 9652: }
 9653: 
 9654: sub gather_adv_clicker_ids {
 9655:     my %clicker_ids;
 9656:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 9657:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9658:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
 9659:     foreach my $element (sort(keys(%coursepersonnel))) {
 9660:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
 9661:             my ($puname,$pudom)=split(/\:/,$person);
 9662:             my $clickers =
 9663: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
 9664:             foreach my $id (split(/\,/,$clickers)) {
 9665: 		$id=~s/^[\#0]+//;
 9666:                 $id=~s/[\-\:]//g;
 9667: 		if (exists($clicker_ids{$id})) {
 9668: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
 9669: 		} else {
 9670: 		    $clicker_ids{$id}=$puname.':'.$pudom;
 9671: 		}
 9672:             }
 9673:         }
 9674:     }
 9675:     return %clicker_ids;
 9676: }
 9677: 
 9678: sub clicker_grading_parameters {
 9679:     return ('gradingmechanism' => 'scalar',
 9680:             'upfiletype' => 'scalar',
 9681:             'specificid' => 'scalar',
 9682:             'pcorrect' => 'scalar',
 9683:             'pincorrect' => 'scalar');
 9684: }
 9685: 
 9686: sub process_clicker {
 9687:     my ($r,$symb)=@_;
 9688:     if (!$symb) {return '';}
 9689:     my $result=&checkforfile_js();
 9690:     $result.=&Apache::loncommon::start_data_table().
 9691:              &Apache::loncommon::start_data_table_header_row().
 9692:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
 9693:              &Apache::loncommon::end_data_table_header_row().
 9694:              &Apache::loncommon::start_data_table_row()."<td>\n";
 9695: # Attempt to restore parameters from last session, set defaults if not present
 9696:     my %Saveable_Parameters=&clicker_grading_parameters();
 9697:     &Apache::loncommon::restore_course_settings('grades_clicker',
 9698:                                                  \%Saveable_Parameters);
 9699:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
 9700:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
 9701:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
 9702:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
 9703: 
 9704:     my %checked;
 9705:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
 9706:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
 9707:           $checked{$gradingmechanism}=' checked="checked"';
 9708:        }
 9709:     }
 9710: 
 9711:     my $upload=&mt("Evaluate File");
 9712:     my $type=&mt("Type");
 9713:     my $attendance=&mt("Award points just for participation");
 9714:     my $personnel=&mt("Correctness determined from response by course personnel");
 9715:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
 9716:     my $given=&mt("Correctness determined from given list of answers").' '.
 9717:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
 9718:     my $pcorrect=&mt("Percentage points for correct solution");
 9719:     my $pincorrect=&mt("Percentage points for incorrect solution");
 9720:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
 9721: 						   {'iclicker' => 'i>clicker',
 9722:                                                     'interwrite' => 'interwrite PRS',
 9723:                                                     'turning' => 'Turning Technologies'});
 9724:     $symb = &Apache::lonenc::check_encrypt($symb);
 9725:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
 9726: function sanitycheck() {
 9727: // Accept only integer percentages
 9728:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
 9729:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
 9730: // Find out grading choice
 9731:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 9732:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
 9733:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
 9734:       }
 9735:    }
 9736: // By default, new choice equals user selection
 9737:    newgradingchoice=gradingchoice;
 9738: // Not good to give more points for false answers than correct ones
 9739:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
 9740:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
 9741:    }
 9742: // If new choice is attendance only, and old choice was correctness-based, restore defaults
 9743:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
 9744:       document.forms.gradesupload.pcorrect.value=100;
 9745:       document.forms.gradesupload.pincorrect.value=100;
 9746:    }
 9747: // If the values are different, cannot be attendance only
 9748:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
 9749:        (gradingchoice=='attendance')) {
 9750:        newgradingchoice='personnel';
 9751:    }
 9752: // Change grading choice to new one
 9753:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 9754:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
 9755:          document.forms.gradesupload.gradingmechanism[i].checked=true;
 9756:       } else {
 9757:          document.forms.gradesupload.gradingmechanism[i].checked=false;
 9758:       }
 9759:    }
 9760: // Remember the old state
 9761:    document.forms.gradesupload.waschecked.value=newgradingchoice;
 9762: }
 9763: ENDUPFORM
 9764:     $result.= <<ENDUPFORM;
 9765: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 9766: <input type="hidden" name="symb" value="$symb" />
 9767: <input type="hidden" name="command" value="processclickerfile" />
 9768: <input type="file" name="upfile" size="50" />
 9769: <br /><label>$type: $selectform</label>
 9770: ENDUPFORM
 9771:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
 9772:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
 9773:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
 9774: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
 9775: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
 9776: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
 9777: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
 9778: <br />&nbsp;&nbsp;&nbsp;
 9779: <input type="text" name="givenanswer" size="50" />
 9780: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
 9781: ENDGRADINGFORM
 9782:          $result.='</td>'.&Apache::loncommon::end_data_table_row().
 9783:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
 9784:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
 9785: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
 9786: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 9787: </form>'
 9788: ENDPERCFORM
 9789:     $result.='</td>'.
 9790:              &Apache::loncommon::end_data_table_row().
 9791:              &Apache::loncommon::end_data_table();
 9792:     return $result;
 9793: }
 9794: 
 9795: sub process_clicker_file {
 9796:     my ($r,$symb)=@_;
 9797:     if (!$symb) {return '';}
 9798: 
 9799:     my %Saveable_Parameters=&clicker_grading_parameters();
 9800:     &Apache::loncommon::store_course_settings('grades_clicker',
 9801:                                               \%Saveable_Parameters);
 9802:     my $result='';
 9803:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
 9804: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
 9805: 	return $result;
 9806:     }
 9807:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
 9808:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
 9809:         return $result;
 9810:     }
 9811:     my $foundgiven=0;
 9812:     if ($env{'form.gradingmechanism'} eq 'given') {
 9813:         $env{'form.givenanswer'}=~s/^\s*//gs;
 9814:         $env{'form.givenanswer'}=~s/\s*$//gs;
 9815:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
 9816:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
 9817:         my @answers=split(/\,/,$env{'form.givenanswer'});
 9818:         $foundgiven=$#answers+1;
 9819:     }
 9820:     my %clicker_ids=&gather_clicker_ids();
 9821:     my %correct_ids;
 9822:     if ($env{'form.gradingmechanism'} eq 'personnel') {
 9823: 	%correct_ids=&gather_adv_clicker_ids();
 9824:     }
 9825:     if ($env{'form.gradingmechanism'} eq 'specific') {
 9826: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
 9827: 	   $correct_id=~tr/a-z/A-Z/;
 9828: 	   $correct_id=~s/\s//gs;
 9829: 	   $correct_id=~s/^[\#0]+//;
 9830:            $correct_id=~s/[\-\:]//g;
 9831:            if ($correct_id) {
 9832: 	      $correct_ids{$correct_id}='specified';
 9833:            }
 9834:         }
 9835:     }
 9836:     if ($env{'form.gradingmechanism'} eq 'attendance') {
 9837: 	$result.=&mt('Score based on attendance only');
 9838:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
 9839:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
 9840:     } else {
 9841: 	my $number=0;
 9842: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
 9843: 	foreach my $id (sort(keys(%correct_ids))) {
 9844: 	    $result.='<br /><tt>'.$id.'</tt> - ';
 9845: 	    if ($correct_ids{$id} eq 'specified') {
 9846: 		$result.=&mt('specified');
 9847: 	    } else {
 9848: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
 9849: 		$result.=&Apache::loncommon::plainname($uname,$udom);
 9850: 	    }
 9851: 	    $number++;
 9852: 	}
 9853:         $result.="</p>\n";
 9854:         if ($number==0) {
 9855:             $result .=
 9856:                  &Apache::lonhtmlcommon::confirm_success(
 9857:                      &mt('No IDs found to determine correct answer'),1);
 9858:             return $result;
 9859:         }
 9860:     }
 9861:     if (length($env{'form.upfile'}) < 2) {
 9862:         $result .=
 9863:             &Apache::lonhtmlcommon::confirm_success(
 9864:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
 9865:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
 9866:         return $result;
 9867:     }
 9868: 
 9869: # Were able to get all the info needed, now analyze the file
 9870: 
 9871:     $result.=&Apache::loncommon::studentbrowser_javascript();
 9872:     $symb = &Apache::lonenc::check_encrypt($symb);
 9873:     $result.=&Apache::loncommon::start_data_table().
 9874:              &Apache::loncommon::start_data_table_header_row().
 9875:              '<th>'.&mt('Evaluate clicker file').'</th>'.
 9876:              &Apache::loncommon::end_data_table_header_row().
 9877:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
 9878: <td>
 9879: <form method="post" action="/adm/grades" name="clickeranalysis">
 9880: <input type="hidden" name="symb" value="$symb" />
 9881: <input type="hidden" name="command" value="assignclickergrades" />
 9882: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
 9883: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
 9884: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
 9885: ENDHEADER
 9886:     if ($env{'form.gradingmechanism'} eq 'given') {
 9887:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
 9888:     } 
 9889:     my %responses;
 9890:     my @questiontitles;
 9891:     my $errormsg='';
 9892:     my $number=0;
 9893:     if ($env{'form.upfiletype'} eq 'iclicker') {
 9894: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
 9895:     }
 9896:     if ($env{'form.upfiletype'} eq 'interwrite') {
 9897:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
 9898:     }
 9899:     if ($env{'form.upfiletype'} eq 'turning') {
 9900:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
 9901:     }
 9902:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
 9903:              '<input type="hidden" name="number" value="'.$number.'" />'.
 9904:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
 9905:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
 9906:              '<br />';
 9907:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
 9908:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
 9909:        return $result;
 9910:     } 
 9911: # Remember Question Titles
 9912: # FIXME: Possibly need delimiter other than ":"
 9913:     for (my $i=0;$i<$number;$i++) {
 9914:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
 9915:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
 9916:     }
 9917:     my $correct_count=0;
 9918:     my $student_count=0;
 9919:     my $unknown_count=0;
 9920: # Match answers with usernames
 9921: # FIXME: Possibly need delimiter other than ":"
 9922:     foreach my $id (keys(%responses)) {
 9923:        if ($correct_ids{$id}) {
 9924:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
 9925:           $correct_count++;
 9926:        } elsif ($clicker_ids{$id}) {
 9927:           if ($clicker_ids{$id}=~/\,/) {
 9928: # More than one user with the same clicker!
 9929:              $result.="</td>".&Apache::loncommon::end_data_table_row().
 9930:                            &Apache::loncommon::start_data_table_row()."<td>".
 9931:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
 9932:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 9933:                            "<select name='multi".$id."'>";
 9934:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
 9935:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
 9936:              }
 9937:              $result.='</select>';
 9938:              $unknown_count++;
 9939:           } else {
 9940: # Good: found one and only one user with the right clicker
 9941:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
 9942:              $student_count++;
 9943:           }
 9944:        } else {
 9945:           $result.="</td>".&Apache::loncommon::end_data_table_row().
 9946:                            &Apache::loncommon::start_data_table_row()."<td>".
 9947:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
 9948:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 9949:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
 9950:                    "\n".&mt("Domain").": ".
 9951:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
 9952:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,0,$id);
 9953:           $unknown_count++;
 9954:        }
 9955:     }
 9956:     $result.='<hr />'.
 9957:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
 9958:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
 9959:        if ($correct_count==0) {
 9960:           $errormsg.="Found no correct answers for grading!";
 9961:        } elsif ($correct_count>1) {
 9962:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
 9963:        }
 9964:     }
 9965:     if ($number<1) {
 9966:        $errormsg.="Found no questions.";
 9967:     }
 9968:     if ($errormsg) {
 9969:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
 9970:     } else {
 9971:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
 9972:     }
 9973:     $result.='</form></td>'.
 9974:              &Apache::loncommon::end_data_table_row().
 9975:              &Apache::loncommon::end_data_table();
 9976:     return $result;
 9977: }
 9978: 
 9979: sub iclicker_eval {
 9980:     my ($questiontitles,$responses)=@_;
 9981:     my $number=0;
 9982:     my $errormsg='';
 9983:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 9984:         my %components=&Apache::loncommon::record_sep($line);
 9985:         my @entries=map {$components{$_}} (sort(keys(%components)));
 9986: 	if ($entries[0] eq 'Question') {
 9987: 	    for (my $i=3;$i<$#entries;$i+=6) {
 9988: 		$$questiontitles[$number]=$entries[$i];
 9989: 		$number++;
 9990: 	    }
 9991: 	}
 9992: 	if ($entries[0]=~/^\#/) {
 9993: 	    my $id=$entries[0];
 9994: 	    my @idresponses;
 9995: 	    $id=~s/^[\#0]+//;
 9996: 	    for (my $i=0;$i<$number;$i++) {
 9997: 		my $idx=3+$i*6;
 9998:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
 9999: 		push(@idresponses,$entries[$idx]);
10000: 	    }
10001: 	    $$responses{$id}=join(',',@idresponses);
10002: 	}
10003:     }
10004:     return ($errormsg,$number);
10005: }
10006: 
10007: sub interwrite_eval {
10008:     my ($questiontitles,$responses)=@_;
10009:     my $number=0;
10010:     my $errormsg='';
10011:     my $skipline=1;
10012:     my $questionnumber=0;
10013:     my %idresponses=();
10014:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10015:         my %components=&Apache::loncommon::record_sep($line);
10016:         my @entries=map {$components{$_}} (sort(keys(%components)));
10017:         if ($entries[1] eq 'Time') { $skipline=0; next; }
10018:         if ($entries[1] eq 'Response') { $skipline=1; }
10019:         next if $skipline;
10020:         if ($entries[0]!=$questionnumber) {
10021:            $questionnumber=$entries[0];
10022:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
10023:            $number++;
10024:         }
10025:         my $id=$entries[4];
10026:         $id=~s/^[\#0]+//;
10027:         $id=~s/^v\d*\://i;
10028:         $id=~s/[\-\:]//g;
10029:         $idresponses{$id}[$number]=$entries[6];
10030:     }
10031:     foreach my $id (keys(%idresponses)) {
10032:        $$responses{$id}=join(',',@{$idresponses{$id}});
10033:        $$responses{$id}=~s/^\s*\,//;
10034:     }
10035:     return ($errormsg,$number);
10036: }
10037: 
10038: sub turning_eval {
10039:     my ($questiontitles,$responses)=@_;
10040:     my $number=0;
10041:     my $errormsg='';
10042:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10043:         my %components=&Apache::loncommon::record_sep($line);
10044:         my @entries=map {$components{$_}} (sort(keys(%components)));
10045:         if ($#entries>$number) { $number=$#entries; }
10046:         my $id=$entries[0];
10047:         my @idresponses;
10048:         $id=~s/^[\#0]+//;
10049:         unless ($id) { next; }
10050:         for (my $idx=1;$idx<=$#entries;$idx++) {
10051:             $entries[$idx]=~s/\,/\;/g;
10052:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
10053:             push(@idresponses,$entries[$idx]);
10054:         }
10055:         $$responses{$id}=join(',',@idresponses);
10056:     }
10057:     for (my $i=1; $i<=$number; $i++) {
10058:         $$questiontitles[$i]=&mt('Question [_1]',$i);
10059:     }
10060:     return ($errormsg,$number);
10061: }
10062: 
10063: 
10064: sub assign_clicker_grades {
10065:     my ($r,$symb)=@_;
10066:     if (!$symb) {return '';}
10067: # See which part we are saving to
10068:     my $res_error;
10069:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
10070:     if ($res_error) {
10071:         return &navmap_errormsg();
10072:     }
10073: # FIXME: This should probably look for the first handgradeable part
10074:     my $part=$$partlist[0];
10075: # Start screen output
10076:     my $result=&Apache::loncommon::start_data_table().
10077:              &Apache::loncommon::start_data_table_header_row().
10078:              '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
10079:              &Apache::loncommon::end_data_table_header_row().
10080:              &Apache::loncommon::start_data_table_row().'<td>';
10081: # Get correct result
10082: # FIXME: Possibly need delimiter other than ":"
10083:     my @correct=();
10084:     my $gradingmechanism=$env{'form.gradingmechanism'};
10085:     my $number=$env{'form.number'};
10086:     if ($gradingmechanism ne 'attendance') {
10087:        foreach my $key (keys(%env)) {
10088:           if ($key=~/^form\.correct\:/) {
10089:              my @input=split(/\,/,$env{$key});
10090:              for (my $i=0;$i<=$#input;$i++) {
10091:                  if (($correct[$i]) && ($input[$i]) &&
10092:                      ($correct[$i] ne $input[$i])) {
10093:                     $result.='<br /><span class="LC_warning">'.
10094:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
10095:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
10096:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
10097:                     $correct[$i]=$input[$i];
10098:                  }
10099:              }
10100:           }
10101:        }
10102:        for (my $i=0;$i<$number;$i++) {
10103:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
10104:              $result.='<br /><span class="LC_error">'.
10105:                       &mt('No correct result given for question "[_1]"!',
10106:                           $env{'form.question:'.$i}).'</span>';
10107:           }
10108:        }
10109:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
10110:     }
10111: # Start grading
10112:     my $pcorrect=$env{'form.pcorrect'};
10113:     my $pincorrect=$env{'form.pincorrect'};
10114:     my $storecount=0;
10115:     my %users=();
10116:     foreach my $key (keys(%env)) {
10117:        my $user='';
10118:        if ($key=~/^form\.student\:(.*)$/) {
10119:           $user=$1;
10120:        }
10121:        if ($key=~/^form\.unknown\:(.*)$/) {
10122:           my $id=$1;
10123:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
10124:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
10125:           } elsif ($env{'form.multi'.$id}) {
10126:              $user=$env{'form.multi'.$id};
10127:           }
10128:        }
10129:        if ($user) {
10130:           if ($users{$user}) {
10131:              $result.='<br /><span class="LC_warning">'.
10132:                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
10133:                       '</span><br />';
10134:           }
10135:           $users{$user}=1; 
10136:           my @answer=split(/\,/,$env{$key});
10137:           my $sum=0;
10138:           my $realnumber=$number;
10139:           for (my $i=0;$i<$number;$i++) {
10140:              if  ($correct[$i] eq '-') {
10141:                 $realnumber--;
10142:              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/))  {
10143:                 if ($gradingmechanism eq 'attendance') {
10144:                    $sum+=$pcorrect;
10145:                 } elsif ($correct[$i] eq '*') {
10146:                    $sum+=$pcorrect;
10147:                 } else {
10148: # We actually grade if correct or not
10149:                    my $increment=$pincorrect;
10150: # Special case: numerical answer "0"
10151:                    if ($correct[$i] eq '0') {
10152:                       if ($answer[$i]=~/^[0\.]+$/) {
10153:                          $increment=$pcorrect;
10154:                       }
10155: # General numerical answer, both evaluate to something non-zero
10156:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
10157:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
10158:                          $increment=$pcorrect;
10159:                       }
10160: # Must be just alphanumeric
10161:                    } elsif ($answer[$i] eq $correct[$i]) {
10162:                       $increment=$pcorrect;
10163:                    }
10164:                    $sum+=$increment;
10165:                 }
10166:              }
10167:           }
10168:           my $ave=$sum/(100*$realnumber);
10169: # Store
10170:           my ($username,$domain)=split(/\:/,$user);
10171:           my %grades=();
10172:           $grades{"resource.$part.solved"}='correct_by_override';
10173:           $grades{"resource.$part.awarded"}=$ave;
10174:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
10175:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
10176:                                                  $env{'request.course.id'},
10177:                                                  $domain,$username);
10178:           if ($returncode ne 'ok') {
10179:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
10180:           } else {
10181:              $storecount++;
10182:           }
10183:        }
10184:     }
10185: # We are done
10186:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
10187:              '</td>'.
10188:              &Apache::loncommon::end_data_table_row().
10189:              &Apache::loncommon::end_data_table();
10190:     return $result;
10191: }
10192: 
10193: sub navmap_errormsg {
10194:     return '<div class="LC_error">'.
10195:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
10196:            &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>').
10197:            '</div>';
10198: }
10199: 
10200: sub startpage {
10201:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$js) = @_;
10202:     if ($nomenu) {
10203:         $r->print(&Apache::loncommon::start_page("Student's Version",$js,{'only_body' => '1'}));
10204:     } else {
10205:         unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
10206:         $r->print(&Apache::loncommon::start_page('Grading',$js,
10207:                                                  {'bread_crumbs' => $crumbs}));
10208:         &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
10209:     }
10210:     unless ($nodisplayflag) {
10211:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp));
10212:     }
10213: }
10214: 
10215: sub select_problem {
10216:     my ($r)=@_;
10217:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
10218:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1));
10219:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
10220:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
10221: }
10222: 
10223: sub handler {
10224:     my $request=$_[0];
10225:     &reset_caches();
10226:     if ($request->header_only) {
10227:         &Apache::loncommon::content_type($request,'text/html');
10228:         $request->send_http_header;
10229:         return OK;
10230:     }
10231:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
10232: 
10233: # see what command we need to execute
10234: 
10235:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
10236:     my $command=$commands[0];
10237: 
10238:     &init_perm();
10239:     if (!$env{'request.course.id'}) {
10240:         unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
10241:                 ($command =~ /^scantronupload/)) {
10242:             # Not in a course.
10243:             $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
10244:             return HTTP_NOT_ACCEPTABLE;
10245:         }
10246:     } elsif (!%perm) {
10247:         $request->internal_redirect('/adm/quickgrades');
10248:         return OK;
10249:     }
10250:     &Apache::loncommon::content_type($request,'text/html');
10251:     $request->send_http_header;
10252: 
10253:     if ($#commands > 0) {
10254: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
10255:     }
10256: 
10257: # see what the symb is
10258: 
10259:     my $symb=$env{'form.symb'};
10260:     unless ($symb) {
10261:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
10262:        $symb=&Apache::lonnet::symbread($url);
10263:     }
10264:     &Apache::lonenc::check_decrypt(\$symb);
10265: 
10266:     $ssi_error = 0;
10267:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
10268: #
10269: # Not called from a resource, but inside a course
10270: #    
10271:         &startpage($request,undef,[],1,1);
10272:         &select_problem($request);
10273:     } else {
10274: 	if ($command eq 'submission' && $perm{'vgr'}) {
10275:             my ($stuvcurrent,$stuvdisp,$versionform,$js);
10276:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
10277:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
10278:                     &choose_task_version_form($symb,$env{'form.student'},
10279:                                               $env{'form.userdom'});
10280:             }
10281:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,$stuvcurrent,$stuvdisp,undef,$js);
10282:             if ($versionform) {
10283:                 $request->print($versionform);
10284:             }
10285:             $request->print('<br clear="all" />');
10286: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
10287:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
10288:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
10289:                 &choose_task_version_form($symb,$env{'form.student'},
10290:                                           $env{'form.userdom'},
10291:                                           $env{'form.inhibitmenu'});
10292:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,$stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$js);
10293:             if ($versionform) {
10294:                 $request->print($versionform);
10295:             }
10296:             $request->print('<br clear="all" />');
10297:             $request->print(&show_previous_task_version($request,$symb));
10298: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
10299:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
10300:                                        {href=>'',text=>'Select student'}],1,1);
10301: 	    &pickStudentPage($request,$symb);
10302: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
10303:             &startpage($request,$symb,
10304:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
10305:                                        {href=>'',text=>'Select student'},
10306:                                        {href=>'',text=>'Grade student'}],1,1);
10307: 	    &displayPage($request,$symb);
10308: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
10309:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
10310:                                        {href=>'',text=>'Select student'},
10311:                                        {href=>'',text=>'Grade student'},
10312:                                        {href=>'',text=>'Store grades'}],1,1);
10313: 	    &updateGradeByPage($request,$symb);
10314: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
10315:             &startpage($request,$symb,[{href=>'',text=>'...'},
10316:                                        {href=>'',text=>'Modify grades'}]);
10317: 	    &processGroup($request,$symb);
10318: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
10319:             &startpage($request,$symb);
10320: 	    $request->print(&grading_menu($request,$symb));
10321: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
10322:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
10323: 	    $request->print(&submit_options($request,$symb));
10324:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
10325:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}]);
10326:             $request->print(&listStudents($request,$symb,'graded'));
10327:         } elsif ($command eq 'table' && $perm{'vgr'}) {
10328:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
10329:             $request->print(&submit_options_table($request,$symb));
10330:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
10331:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
10332:             $request->print(&submit_options_sequence($request,$symb));
10333: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
10334:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
10335: 	    $request->print(&viewgrades($request,$symb));
10336: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
10337:             &startpage($request,$symb,[{href=>'',text=>'...'},
10338:                                        {href=>'',text=>'Store grades'}]);
10339: 	    $request->print(&processHandGrade($request,$symb));
10340: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
10341:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
10342:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
10343:                                                                              text=>"Modify grades"},
10344:                                        {href=>'', text=>"Store grades"}]);
10345: 	    $request->print(&editgrades($request,$symb));
10346:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
10347:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
10348:             $request->print(&initialverifyreceipt($request,$symb));
10349: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
10350:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
10351:                                        {href=>'',text=>'Verification Result'}]);
10352: 	    $request->print(&verifyreceipt($request,$symb));
10353:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
10354:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
10355:             $request->print(&process_clicker($request,$symb));
10356:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
10357:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
10358:                                        {href=>'', text=>'Process clicker file'}]);
10359:             $request->print(&process_clicker_file($request,$symb));
10360:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
10361:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
10362:                                        {href=>'', text=>'Process clicker file'},
10363:                                        {href=>'', text=>'Store grades'}]);
10364:             $request->print(&assign_clicker_grades($request,$symb));
10365: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
10366:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10367: 	    $request->print(&upcsvScores_form($request,$symb));
10368: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
10369:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10370: 	    $request->print(&csvupload($request,$symb));
10371: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
10372:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10373: 	    $request->print(&csvuploadmap($request,$symb));
10374: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
10375: 	    if ($env{'form.associate'} ne 'Reverse Association') {
10376:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10377: 		$request->print(&csvuploadoptions($request,$symb));
10378: 	    } else {
10379: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
10380: 		    $env{'form.upfile_associate'} = 'reverse';
10381: 		} else {
10382: 		    $env{'form.upfile_associate'} = 'forward';
10383: 		}
10384:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10385: 		$request->print(&csvuploadmap($request,$symb));
10386: 	    }
10387: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
10388:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10389: 	    $request->print(&csvuploadassign($request,$symb));
10390: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
10391:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10392: 	    $request->print(&scantron_selectphase($request,undef,$symb));
10393:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
10394:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10395:  	    $request->print(&scantron_do_warning($request,$symb));
10396: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
10397:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10398: 	    $request->print(&scantron_validate_file($request,$symb));
10399: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
10400:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10401: 	    $request->print(&scantron_process_students($request,$symb));
10402:  	} elsif ($command eq 'scantronupload' && 
10403:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
10404: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
10405:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10406:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
10407:  	} elsif ($command eq 'scantronupload_save' &&
10408:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
10409: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
10410:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10411:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
10412:  	} elsif ($command eq 'scantron_download' &&
10413: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
10414:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10415:  	    $request->print(&scantron_download_scantron_data($request,$symb));
10416:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
10417:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10418:             $request->print(&checkscantron_results($request,$symb));
10419:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
10420:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}]);
10421:             $request->print(&submit_options_download($request,$symb));
10422:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
10423:             &startpage($request,$symb,
10424:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
10425:     {href=>'', text=>'Download submissions'}]);
10426:             &submit_download_link($request,$symb);
10427: 	} elsif ($command) {
10428:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
10429: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
10430: 	}
10431:     }
10432:     if ($ssi_error) {
10433: 	&ssi_print_error($request);
10434:     }
10435:     if ($env{'form.inhibitmenu'}) {
10436:         $request->print(&Apache::loncommon::end_page());
10437:     } else {
10438:         &Apache::lonquickgrades::endGradeScreen($request);
10439:     }
10440:     &reset_caches();
10441:     return OK;
10442: }
10443: 
10444: 1;
10445: 
10446: __END__;
10447: 
10448: 
10449: =head1 NAME
10450: 
10451: Apache::grades
10452: 
10453: =head1 SYNOPSIS
10454: 
10455: Handles the viewing of grades.
10456: 
10457: This is part of the LearningOnline Network with CAPA project
10458: described at http://www.lon-capa.org.
10459: 
10460: =head1 OVERVIEW
10461: 
10462: Do an ssi with retries:
10463: While I'd love to factor out this with the version in lonprintout,
10464: 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
10465: I'm not quite ready to invent (e.g. an ssi_with_retry object).
10466: 
10467: At least the logic that drives this has been pulled out into loncommon.
10468: 
10469: 
10470: 
10471: ssi_with_retries - Does the server side include of a resource.
10472:                      if the ssi call returns an error we'll retry it up to
10473:                      the number of times requested by the caller.
10474:                      If we still have a problem, no text is appended to the
10475:                      output and we set some global variables.
10476:                      to indicate to the caller an SSI error occurred.  
10477:                      All of this is supposed to deal with the issues described
10478:                      in LON-CAPA BZ 5631 see:
10479:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
10480:                      by informing the user that this happened.
10481: 
10482: Parameters:
10483:   resource   - The resource to include.  This is passed directly, without
10484:                interpretation to lonnet::ssi.
10485:   form       - The form hash parameters that guide the interpretation of the resource
10486:                
10487:   retries    - Number of retries allowed before giving up completely.
10488: Returns:
10489:   On success, returns the rendered resource identified by the resource parameter.
10490: Side Effects:
10491:   The following global variables can be set:
10492:    ssi_error                - If an unrecoverable error occurred this becomes true.
10493:                               It is up to the caller to initialize this to false
10494:                               if desired.
10495:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
10496:                               of the resource that could not be rendered by the ssi
10497:                               call.
10498:    ssi_error_message   - The error string fetched from the ssi response
10499:                               in the event of an error.
10500: 
10501: 
10502: =head1 HANDLER SUBROUTINE
10503: 
10504: ssi_with_retries()
10505: 
10506: =head1 SUBROUTINES
10507: 
10508: =over
10509: 
10510: =head1 Routines to display previous version of a Task for a specific student
10511: 
10512: Tasks are graded pass/fail. Students who have yet to pass a particular Task
10513: can receive another opportunity. Access to tasks is slot-based. If a slot
10514: requires a proctor to check-in the student, a new version of the Task will
10515: be created when the student is checked in to the new opportunity.
10516: 
10517: If a particular student has tried two or more versions of a particular task,
10518: the submission screen provides a user with vgr privileges (e.g., a Course
10519: Coordinator) the ability to display a previous version worked on by the
10520: student.  By default, the current version is displayed. If a previous version
10521: has been selected for display, submission data are only shown that pertain
10522: to that particular version, and the interface to submit grades is not shown.
10523: 
10524: =over 4
10525: 
10526: =item show_previous_task_version()
10527: 
10528: Displays a specified version of a student's Task, as the student sees it.
10529: 
10530: Inputs: 2
10531:         request - request object
10532:         symb    - unique symb for current instance of resource
10533: 
10534: Output: None.
10535: 
10536: Side Effects: calls &show_problem() to print version of Task, with
10537:               version contained in form item: $env{'form.previousversion'}
10538: 
10539: =item choose_task_version_form()
10540: 
10541: Displays a web form used to select which version of a student's view of a
10542: Task should be displayed.  Either launches a pop-up window, or replaces
10543: content in existing pop-up, or replaces page in main window.
10544: 
10545: Inputs: 4
10546:         symb    - unique symb for current instance of resource
10547:         uname   - username of student
10548:         udom    - domain of student
10549:         nomenu  - 1 if display is in a pop-up window, and hence no menu
10550:                   breadcrumbs etc., are displayed
10551: 
10552: Output: 4
10553:         current   - student's current version
10554:         displayed - student's version being displayed
10555:         result    - scalar containing HTML for web form used to switch to
10556:                     a different version (or a link to close window, if pop-up).
10557:         js        - javascript for processing selection in versions web form
10558: 
10559: Side Effects: None.
10560: 
10561: =item previous_display_javascript()
10562: 
10563: Inputs: 2
10564:         nomenu  - 1 if display is in a pop-up window, and hence no menu
10565:                   breadcrumbs etc., are displayed.
10566:         current - student's current version number.
10567: 
10568: Output: 1
10569:         js      - javascript for processing selection in versions web form.
10570: 
10571: Side Effects: None.
10572: 
10573: =back
10574: 
10575: =head1 Routines to process bubblesheet data.
10576: 
10577: =over 4
10578: 
10579: =item scantron_get_correction() : 
10580: 
10581:    Builds the interface screen to interact with the operator to fix a
10582:    specific error condition in a specific scanline
10583: 
10584:  Arguments:
10585:     $r           - Apache request object
10586:     $i           - number of the current scanline
10587:     $scan_record - hash ref as returned from &scantron_parse_scanline()
10588:     $scan_config - hash ref as returned from &get_scantron_config()
10589:     $line        - full contents of the current scanline
10590:     $error       - error condition, valid values are
10591:                    'incorrectCODE', 'duplicateCODE',
10592:                    'doublebubble', 'missingbubble',
10593:                    'duplicateID', 'incorrectID'
10594:     $arg         - extra information needed
10595:        For errors:
10596:          - duplicateID   - paper number that this studentID was seen before on
10597:          - duplicateCODE - array ref of the paper numbers this CODE was
10598:                            seen on before
10599:          - incorrectCODE - current incorrect CODE 
10600:          - doublebubble  - array ref of the bubble lines that have double
10601:                            bubble errors
10602:          - missingbubble - array ref of the bubble lines that have missing
10603:                            bubble errors
10604: 
10605:    $randomorder - True if exam folder has randomorder set
10606:    $randompick  - True if exam folder has randompick set
10607:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
10608:                      for current line to question number used for same question
10609:                      in "Master Seqence" (as seen by Course Coordinator).
10610:    $startline   - Reference to hash where key is question number (0 is first)
10611:                   and value is number of first bubble line for current student
10612:                   or code-based randompick and/or randomorder.
10613: 
10614: 
10615: 
10616: =item  scantron_get_maxbubble() : 
10617: 
10618:    Arguments:
10619:        $nav_error  - Reference to scalar which is a flag to indicate a
10620:                       failure to retrieve a navmap object.
10621:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
10622:        calling routine should trap the error condition and display the warning
10623:        found in &navmap_errormsg().
10624: 
10625:        $scantron_config - Reference to bubblesheet format configuration hash.
10626: 
10627:    Returns the maximum number of bubble lines that are expected to
10628:    occur. Does this by walking the selected sequence rendering the
10629:    resource and then checking &Apache::lonxml::get_problem_counter()
10630:    for what the current value of the problem counter is.
10631: 
10632:    Caches the results to $env{'form.scantron_maxbubble'},
10633:    $env{'form.scantron.bubble_lines.n'}, 
10634:    $env{'form.scantron.first_bubble_line.n'} and
10635:    $env{"form.scantron.sub_bubblelines.n"}
10636:    which are the total number of bubble lines, the number of bubble
10637:    lines for response n and number of the first bubble line for response n,
10638:    and a comma separated list of numbers of bubble lines for sub-questions
10639:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
10640: 
10641: 
10642: =item  scantron_validate_missingbubbles() : 
10643: 
10644:    Validates all scanlines in the selected file to not have any
10645:     answers that don't have bubbles that have not been verified
10646:     to be bubble free.
10647: 
10648: =item  scantron_process_students() : 
10649: 
10650:    Routine that does the actual grading of the bubblesheet information.
10651: 
10652:    The parsed scanline hash is added to %env 
10653: 
10654:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
10655:    foreach resource , with the form data of
10656: 
10657: 	'submitted'     =>'scantron' 
10658: 	'grade_target'  =>'grade',
10659: 	'grade_username'=> username of student
10660: 	'grade_domain'  => domain of student
10661: 	'grade_courseid'=> of course
10662: 	'grade_symb'    => symb of resource to grade
10663: 
10664:     This triggers a grading pass. The problem grading code takes care
10665:     of converting the bubbled letter information (now in %env) into a
10666:     valid submission.
10667: 
10668: =item  scantron_upload_scantron_data() :
10669: 
10670:     Creates the screen for adding a new bubblesheet data file to a course.
10671: 
10672: =item  scantron_upload_scantron_data_save() : 
10673: 
10674:    Adds a provided bubble information data file to the course if user
10675:    has the correct privileges to do so. 
10676: 
10677: =item  valid_file() :
10678: 
10679:    Validates that the requested bubble data file exists in the course.
10680: 
10681: =item  scantron_download_scantron_data() : 
10682: 
10683:    Shows a list of the three internal files (original, corrected,
10684:    skipped) for a specific bubblesheet data file that exists in the
10685:    course.
10686: 
10687: =item  scantron_validate_ID() : 
10688: 
10689:    Validates all scanlines in the selected file to not have any
10690:    invalid or underspecified student/employee IDs
10691: 
10692: =item navmap_errormsg() :
10693: 
10694:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
10695:    Should be called whenever the request to instantiate a navmap object fails.
10696: 
10697: =back
10698: 
10699: =back
10700: 
10701: =cut

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